03 / Templates · beginner
ANALOG JOYSTICK
Open in PlaygroundRead both axes of an analog joystick plus its built-in pushbutton, printing X/Y position and button state to the Serial Monitor.
beginnerjoystickanalog inputdigital inputserial
sketch.inoArduino C++
27 lines
// Analog Joystick — 2-Axis Input Demo
// Drag the joystick on the canvas (or use arrow keys) and click the knob
// to press the button. Prints X, Y, and button state to Serial.
const int VERT_PIN = A0;
const int HORZ_PIN = A1;
const int SEL_PIN = 2;
void setup() {
pinMode(SEL_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int x = analogRead(HORZ_PIN);
int y = analogRead(VERT_PIN);
bool pressed = digitalRead(SEL_PIN) == LOW;
Serial.print("X: ");
Serial.print(x);
Serial.print(" Y: ");
Serial.print(y);
Serial.print(" Button: ");
Serial.println(pressed ? "PRESSED" : "released");
delay(150);
}- Arduino Uno01
- Analog Joystick02
| Component Pin | Arduino Pin |
|---|---|
| Joystick VCC | 5V |
| Joystick GND | GND |
| Joystick VERT (Y axis) | A0 |
| Joystick HORZ (X axis) | A1 |
| Joystick SEL (button) | Pin 2 |