Thursday, August 1, 2013

Today's Sensor is the Joy Stick!

I am slowly going through all 37 of the modules in the Sunfounder lab kit, one a day. 

Tonight I wired up the joystick, and tried out the sketch from the documentation.  The markings on the board were good, and with the help of the sketch I was quickly reading the analog values, but the digital button seemed to not work.  I remembered that there is a built in 20K ohm resistor inside the Arduino.  This means that the pin will normally be high, and then go low when you press the button.

Save this file as Joystick.ino inside a Joystick directory in your Arduino folder.
int jX = 0; // Analog pins for X and Y axis.
int jY = 1;
int jZ = 7; // Digital pin on Z axis.

void setup ()
  pinMode (jX, INPUT);
  pinMode (jY, INPUT);
  pinMode (jZ, INPUT);
  digitalWrite(jZ, HIGH);  // This was missing.
  // The above line sets the pin high
  // and engages an internal resistor.
  Serial.begin (9600);

void loop ()
  int x, y, z;
  static int px, py, pz;
  x = analogRead (jX) / 10.24 - 50;
  y = analogRead (jY) / 10.24 - 50;
  z = digitalRead (jZ) ;
  if ( px!=x || py!=y || pz!=z ){
    Serial.print (x, DEC);
    Serial.print (",");
    Serial.print (y, DEC);
    Serial.print (",");
    Serial.println (z, DEC);
  delay (200);

I added in some logic to only report when there is a change, the static keyword only allocates the variables once, and then stores the old value. I also scaled the range from 0 to 99 on the x and y axis, and then subtracted 50 so that center scale is zero.

The pin out markings were good on this one.