Hello, I recently created a small project of 4 servos controlled using an Arduino Uno. Each set of two servos can be controlled while the joystick is either pressed, or not pressed.
The code I used:
//add the servo library
#include <Servo.h>
//define our servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
//define joystick pins (Analog)
int joyX = A0;
int joyY = A1;
int joyZ = A2;
void setup ()
{
pinMode (joyX, INPUT);
pinMode (joyY, INPUT);
pinMode (joyZ, INPUT);
Serial.begin (9600);
//attaches our servos on pins PWM 3-5-6-9
servo1.attach(3);
servo2.attach(5);
servo3.attach(6);
servo4.attach(9);
}
void loop ()
{
//variables to read the values from the analog pins
int joyVal;
int pinVal;
pinVal = analogRead (joyZ); //Reads the vales of the joystick button
if (pinVal == 0) //If button value equals 0, execute first servo set
{
//read the value of joystick (between 0-1023)
joyVal = analogRead(joyX);
joyVal = map(joyVal, 0, 1023, 0, 180); //servo value between 0-180
servo1.write(joyVal); //set the servo position according to the joystick value
joyVal = analogRead(joyY);
joyVal = map (joyVal, 0, 1023, 0, 180);
servo2.write(joyVal);
}
if(pinVal != 0) //If button does not equal 0, execute second servo set
{
joyVal = analogRead(joyX);
joyVal = map(joyVal, 0, 1023, 0, 180); //servo value between 0-180
servo3.write(joyVal); //set the servo position according to the joystick value
joyVal = analogRead(joyY);
joyVal = map (joyVal, 0, 1023, 0, 180);
servo4.write(joyVal);
}
delay(15);
}
Again, with this code one servo set is controlled while the joystick button is pressed and the other while the joystick is not pressed.
I would like to rewrite the code so that I can toggle back and forth between the servo sets simply by clicking the button once. Someone mentioned to me I should use the following:
Debounce Code
Variable for the stick mode (e.g. "boolean stickMode")
And finally a while() loop that checks for the value of stickMode, then controls the appropriate servos under that condition, AND checks to see if the button is clicked (with the debounce code) and, if so, it switches to the other mode.
I'm very new to coding/arduino so if anyone can offer insight to this I appreciate all help. Thank you everyone!