CNAP
03 / Templates · beginner

ANALOG JOYSTICK

Open in Playground

Read 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
Circuit
Code
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);
}
Components
  • Arduino Uno
    01
  • Analog Joystick
    02
Wiring
Component PinArduino Pin
Joystick VCC5V
Joystick GNDGND
Joystick VERT (Y axis)A0
Joystick HORZ (X axis)A1
Joystick SEL (button)Pin 2