Joysticks are used in many things, including video game controllers. While we probably don’t think about it, the position of the joystick must be converted into some kind of electronic signal that can be processed and turned into another electronic output. This is possible because a joystick is effectively two potentiometers, one for each axis. In this example we only use one of the axes to control the up/down motion of an arm.
Parts:
1 – Arduino Uno
1 – L298N Motor Driver Board
1 – Dual Axis Joystick
2 – Limit Switches
1 – 9V battery
1 – Tollbooth Setup
Wiring:
Code:
const int up = 13; //pin 13 on Arduino wired to "in4" on the L298N Motor Driver
const int down = 12; //pin 12 on Arduino wired to "in3" on the L298N Motor Driver
const int stickPin = 0 ; // declares the joystick button on Analog 0
const int limitUpPin = 11; // declares upper limit switch on pin 11
const int limitDownPin = 10; // declares lower limit switch on pin 10
// Variables
int limitDownState = 0; // variable for reading the Down limitswitch status
int limitUpState = 0; // variable for reading the Up limitswitch status
void setup()
{
//establishes the mode of each pin used on Arduino
//sets up serial communication if needed
Serial.begin(9600);
pinMode(stickPin, INPUT);
pinMode(limitDownPin, INPUT_PULLUP);
pinMode(limitUpPin, INPUT_PULLUP);
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
}
//the main loop of the program
void loop()
{
//checks the levels of the analog pin and the upper limit switch
int stick = analogRead(stickPin); // read the value of the stickPin
limitUpState = digitalRead(limitUpPin); // read the state of the limitswitch value:
// used for trouble-shooting, this prints the reading of the joystick to the serial monitor Serial.println("UP: ");
Serial.println(limitUpState);
// if the joystick is pushed up AND the upper limit switch is unpressed,
//then the motor will be enabled in the up direction
if ((stick > 600) && (limitUpState == HIGH))
{
digitalWrite(up, HIGH);
digitalWrite(down, LOW);
delay(20);
}
else {
digitalWrite(up, LOW);
digitalWrite(down, LOW);
delay(20);
}
// used for trouble-shooting, this prints the reading of the joystick to the serial monitor
stick = analogRead(stick);
limitDownState = digitalRead(limitDownPin);
Serial.println("DOWN: ");
Serial.println(limitDownState);
// if the joystick is pushed up AND the upper limit switch is unpressed, //then the motor will be enabled in the up direction
if ((stick < 300) && (limitDownState == HIGH))
{
digitalWrite(up, LOW);
digitalWrite(down, HIGH);
delay(20);
}
else {
digitalWrite(up, LOW);
digitalWrite(down, LOW);
delay(20);
}
}