Two servos with different "delay"

Hello I'm new to programming and currently I'm trying to move several servos with different movement at the same time.

The problem I have is that I need different delays for each Servo. When I'm using the "delay" command it applies to every servo.

What do I do wrong?

#include <Servo.h>
Servo servo1;
Servo servo2;

int pos = 0;
void setup() {
servo1.attach(9);
servo2.attach(10);

}

void loop() {
for (pos = -60; pos <= 190; pos += 1) { // goes from -60 degrees to 190 degrees
// in steps of 1 degree
servo1.write(pos);
servo1.write(150 - (pos/2));
delay(30); // should be the delay for Servo1 only

servo2.write(pos);
servo2.write(100 - (pos/2));

delay(15); // should be the delay of Servo2 only
}

Two_Servos.ino (518 Bytes)

You need to use an approach like that which user UKHeliBob advocates, shown below in pseudocode. Do this for each servo...

Have a look at blink without delay, then think of the following as "sweep without delay".

UKHeliBob:
....don't move the servos from their current position to their target position all in one command. Move them a little every now and again using millis() for timing. Use a boolean variable to stop them moving when the target position is reached

For one servo, something like this

start of loop()
  get current time from millis()
  if current time - previous move time >= wait period and the moving variable is true
     move a little
     save the time of the move
     change the target position a little
      if at the target position
        set the boolean to false
      end if
    end if
end of loop()

You need to use an approach like that which user UKHeliBob advocates

Not just me !

See Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.

UKHeliBob:
Not just me !

No, but you were the author of the pseudocode I gave; my main concern was citing you as author, not meaning that you had in anyway cornered the market on delay()-less thinking :wink:

Thanks for the mention but you should, perhaps, have pointed out that as the OP wants to control 2 servos with different timing the code will need to be duplicated or, better, used with arrays or structs to reuse the same code rather than duplicating it

UKHeliBob:
you should, perhaps, have pointed out that as the OP wants to control 2 servos with different timing the code will need to be duplicated

I did say that he or she would need to "do" the code twice.

I did say that he or she would need to "do" the code twice.

Indeed you did.

My apologies

UKHeliBob:
My apologies

No probs Squire