Joystick
In this project, you'll learn how a joystick works.
The KY-023 joystick is simply a combination of two potentiometers, one for the x axis and one for the y axis and a push button.
Two analog input pins on the Arduino board is used to read the analog values from the two potentiometers.
|
| Parts needed:
- Arduino
- KY-023 joystick
- Wires
- Breadboard
Software stuff you'll learn:
- analogRead
- digitalRead
- Serial.begin
- Serial.println
|
| 1
| Making the connections
|
|
| The joystick has five connection pins:
- Connect the GND pin on the joystick to GND on the Arduino.
- Connect the +5V pin on the joystick to 5V on the Arduino.
- Connect the VRX pin on the joystick to pin A0 on the Arduino. This is the variable resistor for the x axis.
- Connect the VRY pin on the joystick to pin A1 on the Arduino. This is the variable resistor for the y axis.
- Connect the SW pin on the joystick to pin A2 on the Arduino. This is the push button switch. (Alternatively, you can connect this to a digital pin.)
|
| 2
| Create a new program by selecting File from the menu
then select New.
|
|
| Then type in this program.
The Serial.begin command
prepares the serial monitor for printing outputs. The number 9600 is the speed at which the monitor will communicate at.
The analogRead command
reads in an analog value (a number between 0 and 1023) from the specified analog input pin A0.
This number is assigned and stored in the value variable.
The Serial.println command
prints out the number that is stored in the value variable to the monitor.
|
int VRX = A0;
int VRY = A1;
int SW = A2;
void setup() {
Serial.begin(9600);
pinMode(SW, INPUT_PULLUP); // using the internal pull-up resistor
}
void loop() {
int x = analogRead(VRX);
int y = analogRead(VRY);
int b = digitalRead(SW);
Serial.print("X axis value: ");
Serial.print(x);
Serial.print(" Y axis value: ");
Serial.print(y);
if (b == LOW) {
Serial.println(" Button pressed");
} else {
Serial.println(" Button not pressed");
}
delay(100);
}
|
| 3
| Open the serial monitor by clicking on the Serial Monitor icon.
Make sure that the baud rate (number at the bottom right corner of the monitor) matches the number specifed in the
Serial.begin command. In this case, it is 9600.
|
|
| 4
| Run the program and move the joystick and press the button.
What is the smallest and largest number that you get?
What are the x and y axis values when you don't touch the joystick?
|
| |