Tuesday, January 14, 2014

Arduino Esplora example: read joystick and display on TFT

This example read joystick on Arduino Esplora, and display on TFT shield.


The function Esplora.readJoystickX() and Esplora.readJoystickY().
  • Esplora.readJoystickX() read the position of the X-axis of the joystick. When the joystick is in the center, it returns zero. Positive values indicate the joystick has moved to the right and negative values when moved to the left.
  • Esplora.readJoystickY() read the position of the Y-axis of the joystick. When the joystick is in the center, it returns zero. Positive values indicate the joystick has moved up and negative values when moved down.
With function map(value, fromLow, fromHigh, toLow, toHigh), it's easy to map value from joysticks to screen coordinates. It re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between.

Example code:
#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];

void setup(){
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.line(xCenter, 0, xCenter, MAX_H);
  EsploraTFT.line(0, yCenter, MAX_W, yCenter);

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

void loop(){
  int xValue = Esplora.readJoystickX();
  int yValue = Esplora.readJoystickY();

  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  
  String(xValue).toCharArray(printoutX,5);
  String(yValue).toCharArray(printoutY,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  
  //map stick value to TFT screen position
  xPos = map( xValue, 512, -512, 0, MAX_W);
  yPos = map( yValue, 512, -512, MAX_H, 0);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    EsploraTFT.stroke(0,0,255);
    EsploraTFT.point(xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  delay(50);
}

Next example: Auto center Arduino Esplora Joystick Mouse

No comments:

Post a Comment