Introduction
A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots. A Joystick PS2 is used here.
Components
– 1 * SunFounder Uno board
– 1 * USB data cable
– 1 * Joystick PS2 module
– 1 * 5-Pin anti-reverse cable
Experimental Principle
This module has two analog outputs (corresponding to X and Y coordinates) and one digital output representing whether it is pressed on Z axis.
Experimental Procedures
Step 1: Build the circuit
The wiring between the Joystick PS2 and SunFounder Uno board:
Joystick PS2 | SunFounder Uno |
GND | GND |
VCC | 5V |
Bt | 7 |
x | A0 |
y | A1 |
Step 2: Program (Please refer to the example code in LEARN -> Get Tutorial on our website)
Step 3: Compile
Step 4: Upload the sketch to SunFounder Uno board
Now, push the rocker and the coordinates of X and Y axes displayed on Serial Monitor will change accordingly; press the button, and the coordinate of Z=0 will also be displayed.
Code
/********************************************* * name:Joystick PS2 * function:push the joystick and the coordinates of X and Y axes displayed on Serial Monitor will change accordingly; * press down the joystick, and the coordinate of Z=0 will also be displayed. connection: Joystick PS2 Uno R3 GND GND VCC 5V Bt 7 x A0 y A1 ***********************************************/ //Email: support@sunfounder.com //Website: www.sunfounder.comconst int xPin = A0; //X attach to A0 const int yPin = A1; //Y attach to A1 const int btPin = 7; //Bt attach to digital 7void setup() { pinMode(btPin,INPUT); //set btpin as INPUT digitalWrite(btPin, HIGH); //and HIGH Serial.begin(9600); //initialize serial }void loop() { Serial.print(“X: “);//print “X: “ Serial.print(analogRead(xPin),DEC); //read the value of A0 and print it in decimal Serial.print(“\tY: “); //print “Y: “ Serial.print(analogRead(yPin),DEC); //read the value of A1 and print it in decimal Serial.print(“\tZ: “); //print “Z: “ Serial.println(digitalRead(btPin)); ////read the value of pin7 and print it delay(100);//delay 100ms } |