#include<Servo.h> // including Servo library
// defining servo, joystick and button pin configurations
#define s1Pin 9
#define s2Pin 10
#define joystickX A0
#define joystickY A1
#define button 2
//naming the both servo motors
Servo s1;
Servo s2;
// defining joystick axis parameters
const int joystickhomeX = 512;
const int joystickhomeY = 512;
const int joystickDeadband = 50;
// defining servo1 and servo2 movement with angles
const int s1left = 0;
const int s1right = 180;
const int s2up = 0;
const int s2down = 180;
const int s1home = 90;
const int s2home = 90;
const int s1step = 1;
const int s2step = 1;
int s1position = s1home;
int s2position = s2home;
void setup()
{
s1.attach(s1Pin);
s2.attach(s2Pin);
pinMode(button,INPUT_PULLUP);
}
void loop()
{
int joystickValueX = analogRead(joystickX); // read Joystick X axis value
int joystickValueY = analogRead(joystickY); // read Joystick Y axis value
// check if Joystick in the Left position
if (joystickValueX < joystickhomeX - joystickDeadband)
{
if(s1position > s1left)
{
s1position -= s1step;
}
}
// check if Joystick in the Right position
if(joystickValueX > joystickhomeX - joystickDeadband)
{
if(s1position < s1right)
{
s1position += s1step;
}
}
// check if the joystick is in UP position
if(joystickValueY < joystickhomeY - joystickDeadband)
{
if(s2position > s2up)
{
s2position -= s2step;
}
}
// check if Joystick is in Down position
if(joystickValueY > joystickhomeY - joystickDeadband)
{
if(s2position < s2down)
{
s2position += s2step;
}
}
// check if button is pressed & move servo to their home postion
if(digitalRead(button) == LOW)
{
s1position = s1home;
s2position = s2home;
}
// write the servo position to their respective servo
s1.write(s1position);
s2.write(s2position);
}