confusion regarding seperate control of two servo motors

Hi,

Sorry if this is noobish, I am quite new to programming for Arduino. I wish to have several servo motors move at random intervals an entire 180 degrees and then back again immediately. I programed this successfully for one servo, but when I attempted to adapt the code, the servos started to act strangely.

here is my initial code;

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 

 
void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object 
} 
 
void loop() 
{ 
  myservo.write(0);                  // sets the servo position according to the scaled value 
  delay(random(500, 10000));                           // waits for the servo to get there 
  myservo.write(179);                  // sets the servo position according to the scaled value 
  delay(500);                           // waits for the servo to get there 
}

This one worked as I wished. When I adapted the code however, it seems that servo 1 waits for a random amount of time between the specified frame, and then moves. At this point, servo 2 moves after the 500 time value input, and servo one seems to wait for a random time to move back to its original position. Basically servo 2 just follows servo 1 strangely. I do not know why, but I do not know much about adding another object for Arduino.

here the my failed coding;

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
Servo myservo2;
 
void setup() 
{ 
  myservo.attach(9);
  myservo2.attach(10); // attaches the servo on pin 9 to the servo object 
} 
 
void loop() 
{ 
  myservo.write(0);                  // sets the servo position according to the scaled value 
  delay(random(500, 10000));                           // waits for the servo to get there 
  myservo.write(179);                  // sets the servo position according to the scaled value 
  delay(500);     // waits for the servo to get there 

myservo2.write(0);                  // sets the servo position according to the scaled value 
  delay(random(500, 10000));                           // waits for the servo to get there 
  myservo2.write(179);                  // sets the servo position according to the scaled value 
  delay(500);

}

Any assistance and/or help would be hugely appreciated.

Cheers :slight_smile:

Sorry, put code in code tagz!
I know this is probably really simple, if someone could even just point me in the right direction?

After this:

  delay(500);     // waits for the servo to get there

You need to do this:

myservo.write(0);

Otherwise the servo won't return to it's starting position until the second servo is done. Same thing for the second servo.

Thx WildBill! That works a treat, I really appreciate the help.