Problem controlling two servos in Sync and opposite Direction.

Dear All,

I am new to Arduino and I am still in learning phase. I was trying to rotate two servos in opposite direction using a pot. (modified the example given to control servo). I tried to change the scale in map but it dose not work.

val = map(val, 0, 1023, 0, 180); this is for motor 1 which works fine

val2 == map(val2, 1023,0,180,0) this is for motor 2 which is not working properly,

Kindly help!

Controlling a servo position using a potentiometer (variable resistor)
by Michal Rinott

modified on 8 Nov 2013
by Scott Fitzgerald


#include <Servo.h>

Servo myservo1;
Servo myservo2;// create servo object to control a servo

int potpin = 0; // analog pin used to connect the potentiometer
int val ; // variable to read the value from the analog pin
int val2 ;
void setup()
myservo1.attach(9);// attaches the servo on pin 9 to the servo object
myservo2.attach(10); // attaches the servo on pin 10 to the servo object

void loop()
{ val=90;// make it vertical initially
val = analogRead(potpin);// reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180); // scale it to use it with the servo (value between 0 and 180)
myservo1.write(val);// sets the servo position according to the scaled value
val2 = map(val2, 1023,0,180,0); // Scale it in the opposite direction
// waits for the servo to get there

If you want the two servos to move at the same time you must put the code on successive lines


If you want one servo to move CW and the other CCW by the same amount do it like this



You set val2 to 90 before calling map, which is nonsense.

I think you are using too many variables and assignments and confusing yourself, try the much simpler code:

  int val = analogRead(potpin);
  myservo1.write (map (val, 0, 1023, 0, 180)) ;
  myservo2.write (map (val, 0, 1023, 180, 0)) ;

Both the codes work wonderfully! Thanks a Lot Robin2 and MarkT!

Wanted the motors to be in vertical state initially(2 sec) before the controls take over that’s why the 90 thing, MarkT. Please let me know if you have any better suggestion.

But again, Thanks guys!

hi, so what does the code look like now?

hi, so what does the code look like now?

This Thread is 4.5 years dead.

If you want advice I suggest you start your own Thread and describe your own problem.