Learn how to use an analog joystick to control your Arduino-based projects with precision.
An analog joystick is a simple controller that provides analog signals for two axes (X and Y) and a digital signal for button press detection. It allows for smoother and more precise control than simple buttons.
Analog joysticks are affordable and can be found for approximately €0.75 on online platforms like eBay and AliExpress.
To connect the joystick to Arduino:
The following code reads the joystick's analog values for the X and Y axes and the button's digital state, then displays the readings via the serial monitor:
/*
GND - GND
Vcc - 5v
VRx - A0
VRy - A1
SW - D9
*/
const int pinLED = 13;
const int pinJoyX = A0;
const int pinJoyY = A1;
const int pinJoyButton = 9;
void setup() {
pinMode(pinJoyButton , INPUT_PULLUP); // activate pull-up resistor
Serial.begin(9600);
}
void loop() {
int Xvalue = 0;
int Yvalue = 0;
bool buttonValue = false;
// Read values
Xvalue = analogRead(pinJoyX);
delay(100); // A small pause between analog readings
Yvalue = analogRead(pinJoyY);
buttonValue = digitalRead(pinJoyButton);
// Display values via serial
Serial.print("X: ");
Serial.print(Xvalue);
Serial.print(" | Y: ");
Serial.print(Yvalue);
Serial.print(" | Button: ");
Serial.println(buttonValue);
delay(1000);
}