// Simple demonstration to show how to move a servo with a joystick
// or potentiometer so that the servo does not lose its position
// when the joystick centres itself
#include <Servo.h>
byte servoPin = 2; // servo signal connection
byte servoPin2 = 3;
Servo myServo1;
Servo myServo2;
int servoPos = 90;
int servoMax = 180;
int servoMin = 0;
int servoMove = 5; // number of degrees per movement
byte potPin = A0; // center pin of joystick or potentiometer connected here
byte potpin2 = A3;
int potValue = 0;
int potValue2 = 0;
int potCentre = 512; // adjust to suit your joystick
int potDeadRange = 50; // movements by this much either side of centre are ignored
unsigned long curMillis;
unsigned long readIntervalMillis = 50;
unsigned long lastReadMillis;
void setup() {
Serial.begin(9600);
Serial.println("Starting JoystickServo.ino");
myServo1.attach(servoPin);
myServo2.attach(servoPin2);
myServo1.write(servoPos);
myServo2.write(servoPos);
}
void loop() {
curMillis = millis();
readJoystick();
moveServo();
showPosition();
}
void readJoystick() {
// check the time
if (curMillis - lastReadMillis >= readIntervalMillis) {
lastReadMillis += readIntervalMillis;
// read the joystick
potValue = analogRead(potPin);
potValue2 = analogRead(potpin2);
// figure if a move is required
if (potValue > potCentre + potDeadRange) {
servoPos += servoMove;
}
if (potValue < potCentre - potDeadRange) {
servoPos -= servoMove;
}
// check that the values are within limits
if (servoPos > servoMax) {
servoPos = servoMax;
}
if (servoPos < servoMin) {
servoPos = servoMin;
}
}
}
void moveServo() {
myServo1.write(servoPos);
myServo2.write(servoPos);
}
void showPosition() {
Serial.print("PotValue ");
Serial.print(potValue);
Serial.print(" ServoPos ");
Serial.println(servoPos);
}