In this article, I will show you how to interface a 2-axis Joystick in Arduino. This is similar to a PlayStation 2 analog joystick. You can use this in controlling motors, servos, or use it as an input device.
Interfacing 2-Axis Joystick in Arduino: Steps in Creating the Device
Step 1: Gathering the Components
To start off, this project will have two parts: the Arduino Device and the Program. First thing to do is to collect the hardware components and make the device. To do that, you will be needing the following:
Quantity | Components |
1 | Arduino Uno |
1 | Joystick Module |
Arduino UNO
You will be using Arduino Uno for this project. It is an easy to use microprocessor board. Arduino Uno is suitable for any projects and is the cheapest and widely used microprocessor board in the Arduino family. This is great for all kinds of IoT projects.
Joystick Module
This is a joystick module you will be using. It has 5 pins – GND, 5V, VRX or HORZ, VRY or VERT, and SW. VRX and VRY is connected to the analog pins. SW is the push button function. When you push the analog stick, it triggers a switch at the side.
Step 2: Connecting the Arduino Components
Now you are ready to connect the components to the Arduino Uno. Connect the power and the ground pins to 5V and GND. Next is to connect the VRX and VRY to A0 and A1. Lastly, connect SW pin to a digital pin.
Step 3: The Arduino Code
Copy the code below to a new sketch in the Arduino IDE. Once done, you can upload it to the Arduino Uno.
// Arduino pin numbers
const int SW_pin = 2; // digital pin connected to switch output
const int X_pin = 0; // analog pin connected to X output
const int Y_pin = 1; // analog pin connected to Y output
void setup() {
pinMode(SW_pin, INPUT);
digitalWrite(SW_pin, HIGH);
Serial.begin(9600);
}
void loop() {
Serial.print("Switch: ");
Serial.print(digitalRead(SW_pin));
Serial.print(" | ");
Serial.print("X-axis: ");
Serial.print(analogRead(X_pin));
Serial.print(" | ");
Serial.print("Y-axis: ");
Serial.print(analogRead(Y_pin));
Serial.println(" | ");
delay(200);
}
Now upload the sketch to the Arduino.
Step 4: Open the Serial Monitor
After you successfully upload the sketch, open the serial monitor of the Arduino. Here you can see the X and Y axis values.
Conclusion
So there you have it! 2-Axis Joystick Interfacing in Arduino. This project is intimidating at first but you will see that it is fairly easy to do. You can combine this to other Arduino projects and build an awesome system!
Download
Click the button below to download the source code.
Related Articles
Inquiries
Feel free to write your questions about this at the comments below.