Button joystick with Arduino

In this tutorial I will be explaining how to use a joystick with Arduino. A joystick is included in our sensor kit. This particular joystick also has a button included, which means you will have a lot of options when using it.

A joystick basically just consists of two potentiometers which can work together. In this way, we can measure the values and get the position of the joystick. If you add the button, that means there are 5 pins in total.

Hooking everything up

First of all, we will have to connect everything. You’ll have to plug the joystick into a breadboard for now, to be able to plug in all of the wires. After that, you’ll have to connect the GND pin to GND on the Arduino, 5V+ to 5V, VRx to A0, VRy to A1 and finally, SW to pin 9.

Arduino scematic for joystick with button

Programming the Arduino

Secondly, you’ll have to program the Arduino. In this tutorial I will only show you how to read off the joystick, if you want to use it for anything else though, you can obviously add your own code. The first piece of code will initialize everything.

int xval; //value of x axes 
int yval; //value of y axes
int buttonstate; //state of button

void setup() {
   Serial.begin(9600); //serial for printing the values
   pinMode(9, INPUT_PULLUP);
 }

In this piece of code we read off all of the values and then print them. We use analogRead to read the resistance on the potentiometers, which will always return a value between 0 and 1024. When the joystick is not being touched, it will return 512 on both axes and 1 for the button.

void loop() {
    xval = analogRead(0);
    yval = analogRead(1);
    buttonstate = digitalRead(9);

    //printing all of the values
    Serial.println(xval);
    Serial.println(yval);
    Serial.println(buttonstate);
    delay(200);// Wait 0.2 seconds between reads to avoid spam.
 }

After uploading this, you should now see all of the values printed in the serial monitor. I hope you have learned something and can use this in your next project.

Leave a Reply

Your email address will not be published. Required fields are marked *

[]