Wednesday, January 22, 2014

Arduino Esplora example for Accelerometer

This example read Accelerometer senser on Esplora board, and display on LCD screen accordingly; such that you can know how Accelerometer work.


#include <TFT.h>
#include <SPI.h>
#include <Esplora.h>

const int MAX_W = 160;
const int MAX_H = 128;
int xCenter = MAX_W/2;
int yCenter = MAX_H/2;

int xPos = xCenter; 
int yPos = yCenter;
int xPrev = xCenter;
int yPrev = yCenter;
char printoutX[5];
char printoutY[5];
char printoutZ[5];


void setup(){
  Serial.begin(9600);
  Mouse.begin();
  
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printoutX,5);
  dummy.toCharArray(printoutY,5);
  dummy.toCharArray(printoutZ,5);
}

void loop(){
  
  if(Esplora.readButton(SWITCH_1) == LOW){
    EsploraTFT.background(0,0,0);
  }
  
  int xValue = Esplora.readAccelerometer(X_AXIS);
  int yValue = Esplora.readAccelerometer(Y_AXIS);
  int zValue = Esplora.readAccelerometer(Z_AXIS);
  
  
  xPos = map(xValue, -512, 512, MAX_H, 0);
  yPos = map(yValue, -512, 512, 0, MAX_H);
  
  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutZ,0,30);
  
  String(xValue).toCharArray(printoutX,5);
  String(yValue).toCharArray(printoutY,5);
  String(zValue).toCharArray(printoutZ,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutZ,0,30);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  delay(10);
}

No comments:

Post a Comment