Lesson 27 Joystick PS2

Share for us

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 (SunFounder Mega2560 board)

– 1 * USB data cable

– 1 * Joystick PS2 module

– Several jumper wires

Experimental Principle

This module has two analog outputs (corresponding toand 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 the SunFounder Uno board:

Joystick PS2SunFounder Uno
GNDGND
VCC5V
XA0
YA1
SW8

Step 2: Program (Please refer to the example code in LEARN -> Get Tutorials on our website)

Step 3: Compile the code

Step 4: Upload the sketch to the SunFounder Uno board

Now, 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.

 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 SunFounder Uno R3
* GND GND
* VCC 5V
* Bt 8
* 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 swPin = 8; //Bt attach to digital 8void setup()
{
  pinMode(swPin,INPUT); //set btpin as INPUT 
  digitalWrite(swPin, HIGH); //and HIGH
  Serial.begin(9600); //initialize serial monitor
}void loop()
{
  Serial.print(“X: “); //print “X: “
  Serial.print(analogRead(xPin),DEC); //read the value of A0 and print it in decimal
  Serial.print(“|Y: “); //print “|Y: “
  Serial.print(analogRead(yPin),DEC); //read the value of A1 and print it in decimal
  Serial.print(“|Z: “); //print “|Z: “
  Serial.println(digitalRead(swPin)); //read the value of pin8 and print it
  delay(500); //delay 500ms
}