ZachLabs Arduino

Lab 9: X/Y Joysticks

The X/Y joystick in your kit is similar to the analog sticks on video game controllers. From an electrical standpoint it is just two potentiometers (X and Y) and a button (for when the joystick is clicked).

Example Program

Connect the X/Y joystick to your Arduino by making the following connections with the long M-to-F jumper wires included in your kit, and then upload the program to your Arduino:

X/Y Joystick Arduino Pin
GND GND
+5V 5V
VRX A0
VRY A1
SW 2
void setup()
{
    Serial.begin(9600);
    pinMode(A0, INPUT);     // X-axis
    pinMode(A1, INPUT);     // Y-axis
    pinMode(2, INPUT_PULLUP);   // Button
}

void loop()
{
    Serial.print("X=");
    Serial.print(analogRead(A0));
    Serial.print(" | Y=");
    Serial.print(analogRead(A1));
    Serial.print(" | B=");
    Serial.println(digitalRead(2));
}

If you open the serial monitor in the Arduino IDE you should see a stream of values being printed indicating the X and Y position of the joystick (from 0 to 1023) and whether or not the button is currently pressed down.

Assignment

Wire up four LEDs that correspond to the +X, -X, +Y, and -Y directions and have them turn on when the joystick is pushed in that direction. When the joystick is pushed diagonally in two directions at once (like +X and +Y) both LEDs should turn on. When the joystick is centered the LEDs should all be off. When the joystick button is pushed the LEDs should all be turned on, regardless of whether the joystick is centered or being pushed in a direction.

It may not be obvious, but the simple way to implement the diagonal behavior described above is to handle the X and Y axes separately.