When I run this program, one servo ends up waiting for the other's block to be over, however I want them to be able to move freely, or be able to have both myservo and myservo2 running at the same time.
The problem when I try that is that the servos are still moving in sync, in that mean they are both going from 0 to 90 degrees at the same rate, and look like they are being mirrored by eachother.
I'm sorry, I'm new to Arduino- so please excuse my descriptions.
What Im trying to do is have one servo at 90 degrees while the other is at 45, and vice-versa (both moving between 0 and 90 degrees constantly, back and fourth, at about 1 degree every 40 milliseconds).
#include <Servo.h>
Servo myservo;
Servo myservo2;
int pos = 0;
void setup()
{
myservo.attach(8);
myservo2.attach(9);
}
void loop()
{
// While Servo A moves from 0 to 90
// Servo B moves from 45 to 90 to 45
for (pos = 0; pos <= 90; pos++)
{
myservo.write(pos);
int pos2;
if (pos <= 45) // 0 to 45
pos2 = pos + 45;
else // 46 to 90
pos2 = (90 + 45) - pos;
myservo2.write(pos2);
delay(40);
}
// While Servo A moves from 90 to 0
// Servo B moves from 45 to 0 to 45
for (pos = 90; pos >= 0; pos--)
{
myservo.write(pos);
int pos2;
if (pos > 45) // 90 to 46
pos2 = pos + 45; // 45 to 0
else // 46 to 0
pos2 = 46 - pos; // 0 to 46
myservo2.write(pos2);
delay(40);
}
}
You can make a millis-timer that updates all the servo motors every 10ms or every 20ms. Within that timer it is possible to calculate the new position. That allows to move fast or slow and every servo motor moves independent of each other.
Demonstration (click on the start button in the middle-upper of the screen): https://wokwi.com/arduino/projects/305087394119418434.
You could also use my MobaTools lib instead of the builtin servo lib. The MoToServo class allows you to specify the speed of the servo movement ( individually for each servo ), so you don't have to bother with it in for loops. You simply execute your write() commands for the servos and they will move to that position with the set speed. The sketch is not blocked while the servos are moving.