Joystick Control with Arduino


This code is available on my GitHub page here

Keyes version is KY023

There are a number of different versions of this and sometimes the pin outs will differ from those shown here. The joystick consists of two potentiometers at right angles, one controlled when the stick is moved in the Y direction (up/down) and the other in the X direction. There is normally a switch operated when the button is pushed. The potentiometers are connected to Vcc and ground and the value is read from the middle pin.

This sketch is a basic way of testing the joystick, later blogs will show how to use the joystick to select items from a menu. The values for X and Y as well as the switch state are printed in the Serial Monitor.

Use this sketch to measure the values of X and Y when the joystick is in its home position in the centre. Up is when the value of Y increases, down is when the value of Y decreases. Left is when the value of X increases, Right is when the value of X decreases.


/*************************************************
Joystick Test
prints the output from the joystick on the Serial Monitor

Connections:
Gnd on Joystick to Gnd on Arduino
Vcc on Joytick to 5 volts on Arduino
VrX on Joystick to A0 on Arduino
VrY on Joystick to A1 on Arduino
Sw on Joystick to pin 2 on Arduino

*************************************************/
// definitions for pins
#define xPin 14
#define yPin 15
#define joySwitch 2
#define ledPin 13

// variables
boolean switchState = true; // it will be false when pressed
int xValue = 0;
int yValue = 0;

void setup(void){
Serial.begin(9600);
pinMode(joySwitch, INPUT_PULLUP); // turn on pullup resistor
pinMode(ledPin, OUTPUT); // onboard LED
}


void loop (){

// main code will go here and joyStick() is called as a subroutine
joyStick();
}


void joyStick(){
// this routine reads the joystick values
xValue = analogRead(xPin);
yValue = analogRead(yPin);
switchState = digitalRead(joySwitch);
// remove following lines if not required
Serial.print("X value = ");
Serial.println(xValue);
Serial.print("Y value = ");
Serial.println(yValue);
Serial.print("Switch state = ");
Serial.println(switchState);
if (switchState == false){ // switch pressed
digitalWrite(ledPin, HIGH);
}
else{
digitalWrite(ledPin, LOW);
}
//
delay(1000); // delay to allow data to be seen
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s