Read an Analog Joystick (Arduino)
Read X/Y position and the button from a thumb joystick. Learn analogRead on two axes plus a digital button.
Beginner15 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
joystick.ino
// Read a 2-axis joystick and its button.
const int xPin = A0, yPin = A1, swPin = 2;
void setup() {
pinMode(swPin, INPUT_PULLUP); // button reads LOW when pressed
Serial.begin(9600);
}
void loop() {
int x = analogRead(xPin); // ~0..1023, centered near 512
int y = analogRead(yPin);
bool pressed = digitalRead(swPin) == LOW;
Serial.print("X: "); Serial.print(x);
Serial.print(" Y: "); Serial.print(y);
Serial.print(" Button: "); Serial.println(pressed ? "DOWN" : "up");
delay(200);
}
Steps
- Wire: +5V and GND to power, VRx to A0, VRy to A1, SW to D2.
- Upload, open the Serial Monitor.
- Move the stick and press it — watch X, Y, and the button change.