#include<Servo.h>
//define the pins for servo,joystick,button
const int servopin1=9;
const int servopin2=10;
const int joystickX=A0;
const int joystickY=A1;
const int buttonpin=2;
//define the joystick home position and deadband
const int joystickhomeX=512;
const int joystickhomeY=512;
const int joystickdeadband=50;
//defining the servo position for left and right
const int servo1left=0;
const int servo1right=180;
const int servo2up=0;
const int servo2down=180;
const int servo1home=90;
const int servo2home=90;
//define increment and decrement position amount
const int servo1step=1;
const int servo2step=1;
// create servo instances for servo classes for the servos
Servo servo1;
Servo servo2;
//intialize the servo position to their home position
int servo1position=servo1home;
int servo2position=servo2home;
void setup(){
//attach the servos
servo1.attach(servopin1);
servo2.attach(servopin2);
//set the button pin as input
pinMode(buttonpin,INPUT_PULLUP);
}
void loop(){
//read the joystick value
int joystickvalueX=analogRead(joystickX);
int joystickvalueY=analogRead(joystickY);
//check if the joystick in the left position
if(joystickvalueX < joystickhomeX-joystickdeadband){
//move the servopin1 to left
if(servo1position > servo1left){
servo1position -= servo1step;
}
}
//check if the joystick in the right position
if(joystickvalueX > joystickhomeX+joystickdeadband){
//move the servo to right
if(servo1position < servo1right){
servo1position +=servo1step;
}
}
//check if the joystick is in up position
if(joystickvalueY< joystickhomeY -joystickdeadband){
if(servo2position< servo2up){
servo2position -= servo2step;
}
}
//check if the joystick in downword position
if(joystickvalueY > joystickhomeY + joystickdeadband){
if(servo2position< servo2down){
servo2position += servo2step;
}
}
//check if the button is pressed it goes back to 90
if(digitalRead(buttonpin)==LOW){
servo1position=servo1home;
servo2position=servo2home;
}
//write the servo position to their respective servos
servo1.write(servo1position);
servo2.write(servo2position);
delay(10);
}