Hi guys, I’m a newbie here. I’ve been trying to get 2 servos to work with my Arduino. I think I may have messed up a bit with the functions. If anyone can help that’d be great!
#include <Servo.h>
byte servoPin1 = 8; // servo signal connection
byte servoPin2 = 9;
Servo A;
Servo B;
int servo1Pos = 90;
int servo2Pos = 90;
int servoMax = 220;
int servoMin = 0;
int servoMove = 8; // number of degrees per movement
byte potPin1 = A0; // center pin of joystick or potentiometer connected here
byte potPin2 = A1;
int potValue1 = 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
void setup() {
Serial.begin(9600);
Serial.println(“Starting JoystickServo.ino”);
A.attach(servoPin1);
A.write(servo1Pos);
B.attach(servoPin2);
B.write(servo2Pos);
}
void loop() {
readJoystick( potValue1, servo1Pos, potPin1);
readJoystick( potValue2, servo2Pos, potPin2);
moveServo(A, servo1Pos);
moveServo(B, servo2Pos);
showPosition(potValue1,servo1Pos);
showPosition(potValue2,servo2Pos);
}
void readJoystick(int val,int pos,byte pin) {
// read the joystick
val = analogRead(pin);
// figure if a move is required
if (val > potCentre + potDeadRange) {
pos += servoMove;
}
if (val < potCentre - potDeadRange) {
pos -= servoMove;
}
// check that the values are within limits
if (pos > servoMax) {
pos = servoMax;
}
if (pos < servoMin) {
pos = servoMin;
}
}
void moveServo(Servo servo, int pos) {
(servo).write(pos);
}
void showPosition( int val,int pos) {
Serial.print("PotValue1 “);
Serial.print(val);
Serial.print(” Servo1Pos ");
Serial.println(pos);
}