The 5-way joystick on the shield is great for implementing menu navigation or even for use as a tiny game controller. To minimize the number of pins required, the joystick uses a different resistor on each leg of the control to create a variable voltage divider that can be monitored with a single analog pin. Each movement of the joystick control connects a different resistor and results in a different voltage reading.
In the code example below, the CheckJoystick() function reads the analog pin and compares the result with 5 different ranges to determine which (if any) direction the stick has been moved. If you upload this to your Arduino and open the Serial Monitor, you will see the current joystick state printed to the screen.

You can use this code as the input method for your menu system or game:
void setup() 
  // initialize serial communication at 9600 bits per second:

#define Neutral 0
#define Press 1
#define Up 2
#define Down 3
#define Right 4
#define Left 5

// Check the joystick position
int CheckJoystick()
  int joystickState = analogRead(3);
  if (joystickState < 50) return Left;
  if (joystickState < 150) return Down;
  if (joystickState < 250) return Press;
  if (joystickState < 500) return Right;
  if (joystickState < 650) return Up;
  return Neutral;

void loop() 
  int joy = CheckJoystick();
  switch (joy)
    case Left:
    case Right:
    case Up:
    case Down:
    case Press:

This guide was first published on Aug 29, 2012. It was last updated on Apr 17, 2024.

This page (Reading the Joystick) was last updated on May 03, 2013.

Text editor powered by tinymce.