controlling 2 servos independently

I am trying to control 2 servos independently with 2 potentiometers. the code i am using controls both servos in unison, which i do not want. can somebody explain to me what i have wrong in my code? Thanks :slight_smile:

here is my code:

#include <Servo.h>

Servo myservo1;
Servo myservo2;

int potpin1 = 1;
int potpin2 = 2;

int val1;
int val2;

void setup()
{
myservo1.attach(1);
myservo2.attach(2);

}

void loop()
{
val1 = analogRead(potpin1);
val1 = map(val1, 0, 1023, 0, 179);
myservo1.write(val1);

val2 = analogRead(potpin2);
val2 = map(val2, 0, 1023, 0, 179);
myservo2.write(val2);

}

Can't see much wrong with the code (except there's too much of it, and it isn't enclosed in code tags) - have you checked your wiring?

Also, not a good idea to use serial pins for other I/O - you may want to use them for debugging.

Do both pots control both servos ?

Yes each individual pot controls both servos in unison

Try the below code which will print out to the serial monitor to see what is happening. I changed to analog input pins to match my pot connection and the servo pins to allow use of the serial monitor on pins 0 and 1 for debugging.

//zoomkat dual pot/servo test 12-2912

#include <Servo.h> 
Servo myservo1;
Servo myservo2;

int potpin1 = 0;  //my pot pin
int potpin2 = 1;

int newval1, oldval1;
int newval2, oldval2;

void setup() 
{
  Serial.begin(9600);  
  myservo1.attach(2);  
  myservo2.attach(3);
  Serial.println("testing dual pot servo");  
}

void loop() 
{ 
  newval1 = analogRead(potpin1);           
  newval1 = map(newval1, 0, 1023, 0, 179); 
  if (newval1 < (oldval1-2) || newval1 > (oldval1+2)){  
    myservo1.write(newval1);
    Serial.print("1- ");
    Serial.println(newval1);
    oldval1=newval1;
  }

  newval2 = analogRead(potpin2);
  newval2 = map(newval2, 0, 1023, 0, 179);
  if (newval2 < (oldval2-2) || newval2 > (oldval2+2)){  
    myservo2.write(newval2);
    Serial.print("2- ");    
    Serial.println(newval2);
    oldval2=newval2;
  }
  delay(50);
}

I’m guessing it has something to do with having attached the servos to pins 1 and 2 not say 9 and 10.

But I also note you have no delay as recommended in the Knob example as shown arrowed below. I wonder if that’s part of the problem?

void loop() 
{ 
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023) 
  val = map(val, 0, 1023, 0, 179);     // scale it to use it with the servo (value between 0 and 180) 
  myservo.write(val);                  // sets the servo position according to the scaled value 
  delay(15);                         // waits for the servo to get there  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}

Incidentally I have code very similar to yours to drive two servos from a joystick (which is two pots in one mechanism) with the pots read on A4 and A5 and servos attached to pins 9 and 10… works as expected.