Basic Usage - PalladinoMarco/AlignedJoystick GitHub Wiki
This documentation will guide you in configuring an analog joystick to your Arduino, in addition to providing some basic library usage information also provides some basic information about code writing in general. The documentation here assumes a simple configuration of one or more joysticks by reading the raw data. For more complex uses to calibrate joysticks and achieve axis alignment, see advanced documentation.
Before you begin
This library only works with analog joysticks.
Setting up the joystick
We throw the beginning lines of our file .ino:
#include <AlignedJoy.h>
#define PIN_X 0
#define PIN_Y 1
So far, what has been written includes the library, set a definition of macros so that wherever PIN_X
and PIN_Y
is seen later in the code is replaced by the respective pin numbers where you connected the analog signals of the respective axes of the joystick. Now, let's actually setup our joystick:
AlignedJoy joystick_1(PIN_X, PIN_Y);
joystick_1 is the name I gave as an example to the joystick. Write the name you prefer.
Read the joystick
To read the values of the respective axes of the joystick we use the read(axis_t axis)
method in the loop function, passing as a parameter the axis we want to read using the flags (X and Y) defined by the library.
void loop() {
joystick_1.read(X);
joystick_1.read(Y);
}
Install more than one joystick
If you want to connect more than one joystick just add the other two pins used, install it creating a new object in the class and read the joysticks; you’ll get a sketch like this:
#include <AlignedJoy.h>
// PIN DEFINITION
// joystick 1
#define PIN_JOY1_X 0 //(up down)
#define PIN_JOY1_Y 1 //(left right)
// joystick 2
#define PIN_JOY2_X 2 //(up down)
#define PIN_JOY2_Y 3 //(left right)
// CLASS CONSTRUCTORs
// new joystick object
AlignedJoy joystick_1(PIN_JOY1_X, PIN_JOY1_Y);
AlignedJoy joystick_2(PIN_JOY2_X, PIN_JOY2_Y);
void setup() {
// SERIAL SETUP FOR DEBUG
Serial.begin(9600);
while(!Serial){}
}
void loop() {
// for read axis value use "read" method. For x axis -> objectname.read(X); for y axis -> objectname.read(Y).
// print joystick 1 axes value
Serial.print("joystick_1 X -> ");
Serial.print(joystick_1.read(X));
Serial.print(" | Y -> ");
Serial.print(joystick_1.read(Y));
// print joystick 1 axes value
Serial.print(" -|- joystick_2 X -> ");
Serial.print(joystick_2.read(X));
Serial.print(" | Y -> ");
Serial.println(joystick_2.read(Y));
delay(500);
}
This sketch is among the examples of the library under the name "Read_two_joystick.ino".
In the sketch is implemented the use of the serial to display the values read by the respective joysticks.