Joystick

This chapter will show you how to connect a joystick to your Arduino board read the current x- and y-value using p5.js and JavaScript.

What is a joystick?

A joystick can be moved in two directions: horizontally and vertically. Some joysticks also can be pressed like a button.

Using a joystick in p5js

The basic syntax is:

let joystick = connectSensor( SENSOR_JOYSTICK, pins, minValue, maxValue );

Note that when you connect the joystick, there are 5 cables going from the joystick to the Arduino. You must pass an object as argument for pins in this format: {vrx:'A0', vry:'A1', sw:7}.

In the following example the vrx pin of the joystick is connected to the A0 pin on the Arduino, the vry pin is connected to the A1 pin and the sw pin of the joystick is connected to the digital pin 7 on the Arduino.

If you don’t define a minValue and maxValue, the values returned will range from 0 to 1024:

let joystick = connectSensor( SENSOR_JOYSTICK, {vrx:'A0', vry:'A1', sw:7} );

Here we would like the joystick-position to be mapped to values between 0 and 100:

let joystick = connectSensor( SENSOR_JOYSTICK, {vrx:'A0', vry:'A1', sw:7}, 0, 100 );

Hardware

Wiring

Wiring a joystick to Arduino and p5js Javascript

Code

let joystick;
let filling = 'black';

function setup () {
   createCanvas(400, 400);

   joystick = connectSensor( SENSOR_JOYSTICK, {vrx:'A0', vry:'A1', sw:7}, 0, width );
   joystick.pressed( joystickPressed );
   joystick.released( joystickReleased );
}

function draw () {
   background( 255 );

   fill( filling );
   circle( joystick.valueX(), joystick.valueY(), 50 );
}

function joystickPressed() {
   filling = 'red';
}

function joystickReleased() {
   filling = 'black';
}