Joystick direction
Read an analog joystick's two axes and its push button, and print which way it is pushed.
Input · Beginner
In a real product: Electric wheelchair (Medical): A joystick sets the chair's direction and speed.
A thumb joystick is two potentiometers at right angles plus a push button. Each axis gives a voltage, centred at about 2.5 V. This project prints which way the stick is pushed.
What you'll learn
- Reading two analog axes
- Turning raw readings into directions with thresholds
- Leaving a dead zone around the centre
How it works
VERT goes to A0 and HORZ to A1. Centred, both read about 512. Pushing up raises VERT and pushing left raises HORZ (on this module), so readings above 700 or below 300 count as a push. Anything in between is the dead zone, so a stick that does not quite centre still reads "center".
Pressing the stick connects SEL to GND. With INPUT_PULLUP on pin 2 that reads LOW.
Try this
- Move the joystick by setting its sliders in the part's popover while it runs.
- Use it to move a dot on an OLED display.
- Report the angle and distance from the centre instead of four directions.
sketch.ino
// An analog joystick: VERT on A0, HORZ on A1, its button (SEL) on pin 2.
const int VERT = A0, HORZ = A1, SEL = 2;
void setup() {
pinMode(SEL, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int x = analogRead(HORZ), y = analogRead(VERT);
bool pressed = digitalRead(SEL) == LOW;
const char *direction = "center";
if (y > 700) direction = "up";
else if (y < 300) direction = "down";
else if (x > 700) direction = "left";
else if (x < 300) direction = "right";
Serial.print("X: ");
Serial.print(x);
Serial.print(" Y: ");
Serial.print(y);
Serial.print(" -> ");
Serial.print(direction);
Serial.println(pressed ? " (pressed)" : "");
delay(300);
}