I'm trying to control two servos using one joystick. I need each servo to remain in its end orientation after the joystick is released instead of returning to center. This is my current code. Thank you.
#include <Servo.h>
int servoPin1 = 6;
int servoPin2 = 7; // servo signal connection
Servo myServo1;
Servo myServo2;
int servoPos1 = 90;
int servoPos2 = 90;
int servoMax = 165;
int servoMin = 15;
int servoMove = 3; // number of degrees per movement
int joyPin1 = A0;
int joyPin2 = A1;
int joyValue1 = 0;
int joyValue2 = 0;
int joyCenter = 350; // neutral value of joystick
int joyDeadRange = 150; // movements by this much either side of center are ignored
unsigned long curMillis;
unsigned long readIntervalMillis = 100;
unsigned long lastReadMillis;
void setup() {
Serial.begin(9600);
myServo1.attach(servoPin1);
myServo1.write(servoPos1);
myServo2.attach(servoPin2);
myServo2.write(servoPos2);
}
void loop() {{
curMillis = millis();
readJoystick();
moveServo();
showPosition();
}}
void readJoystick() {
// check the time
if (curMillis - lastReadMillis >= readIntervalMillis) {
lastReadMillis += readIntervalMillis;
// read the joystick
joyValue1 = analogRead(joyPin1);
// figure if a move is required
if (joyValue1 > joyCenter + joyDeadRange) {
servoPos1 += servoMove;
}
if (joyValue1 < joyCenter - joyDeadRange) {
servoPos1 -= servoMove;
}
// check that the values are within limits
if (servoPos1 > servoMax) {
servoPos1 = servoMax;
}
if (servoPos1 < servoMin) {
servoPos1 = servoMin;
}
}
joyValue2 = analogRead(joyPin2);
// figure if a move is required
if (joyValue2 > joyCenter + joyDeadRange) {
servoPos1 += servoMove;
}
if (joyValue2 < joyCenter - joyDeadRange) {
servoPos1 -= servoMove;
}
// check that the values are within limits
if (servoPos2 > servoMax) {
servoPos2 = servoMax;
}
if (servoPos2 < servoMin) {
servoPos2 = servoMin;
}
}
void moveServo() {
myServo1.write(servoPos1);
myServo2.write(servoPos2);
}
void showPosition() {
Serial.print("JoyValue1 ");
Serial.print(joyValue1);
Serial.print(" ServoPos1 ");
Serial.println(servoPos1);
Serial.print("JoyValue2 ");
Serial.print(joyValue2);
Serial.print(" ServoPos2 ");
Serial.println(servoPos2);
}