Arduino - Joystick

by DIYables in Circuits > Arduino

8 Views, 0 Favorites, 0 Comments

Arduino - Joystick

This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://arduinogetstarted.com/tutorials/arduino-joystick

This build reads a joystick module with Arduino. The joystick has two potentiometers set at 90 degrees to each other for X and Y position, plus a built-in pushbutton. You get two analog readings (0-1023) for position and one digital reading for the button, useful for direction control, menu navigation, or driving servos in a pan-tilt setup.

Supplies

Wiring

Connect the joystick's GND pin to Arduino GND and its VCC pin to Arduino 5V. Connect VRX to analog pin A1 and VRY to analog pin A0. Connect SW, the pushbutton output, to a digital pin. SW is normally open and needs a pull-up so it reads HIGH when not pressed and LOW when pressed. For a permanent build, a screw terminal shield on the Arduino makes the wires easier to secure.

How It Works

Moving the thumbstick left/right changes the voltage on VRX between 0 and 5V, read by Arduino's analog input as a value from 0 to 1023, with 0 at one end and 1023 at the other. Moving it up/down does the same on VRY. Moving diagonally changes both at once, in proportion to the position on each axis. Pressing the thumbstick down closes the internal pushbutton; with a pull-up resistor the SW pin's digital reading goes from HIGH to LOW.

Code

The analog axes are read directly with analogRead() on the VRX and VRY pins. The pushbutton is handled with the ezButton library, which adds debounce and can enable the internal pull-up. Example sketches build on these two reads: one just prints X and Y, one adds the button state, one converts the analog values into MOVE_LEFT, MOVE_RIGHT, MOVE_UP, MOVE_DOWN commands, and another converts the readings into angles to drive two servos, for example in a pan-tilt camera.

arduino-joystick.ino - the sketch from the tutorial, unchanged.

/*
* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-joystick
*/

#define VRX_PIN A1 // Arduino pin connected to VRX pin
#define VRY_PIN A0 // Arduino pin connected to VRY pin

int xValue = 0; // To store value of the X axis
int yValue = 0; // To store value of the Y axis

void setup() {
Serial.begin(9600) ;
}

void loop() {
// read analog X and Y analog values
xValue = analogRead(VRX_PIN);
yValue = analogRead(VRY_PIN);

// print data to Serial Monitor on Arduino IDE
Serial.print("x = ");
Serial.print(xValue);
Serial.print(", y = ");
Serial.println(yValue);
delay(200);
}

Full Tutorial

The complete tutorial, wiring diagram and code explanation: https://arduinogetstarted.com/tutorials/arduino-joystick