How to move a servo quickly and without delay function

Im trying to move a servo from one place to another while using the typical for loop you find in the servo's library example.

``````int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
servo1.write(pos1);
delay(15);
}

for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
servo1.write(pos1);
delay(15);
}
``````

The thing is that while this does work, I want to be able to move the servo a little quicker but I cant use the delay function because of some connectivity issues with another library named BLYNK. How could i move the servo from lightOFF to lightON the quickest way possible without the delay function? Sorry for my grammar i'm not a native english speaker. Thank you!

The quickest way possible from `LightON` to `LightOFF` is simply `servo1.write(lightOFF);` without loops or delays, in one go; no need to do it degree by degree. For example:

``````int lightON = 180;
int lightOFF = 90;

for (pos1 = lightOFF; pos1 <= lightON; pos1++) {
servo1.write(pos1);
delay(15);
}

servo1.write(lightOFF);
``````

If you want it to move a few degrees every loop and do other things in the loop while it moves, you can time it with `millis()` instead of `delay()`. The code below should move the servo 5 degrees every 0.5s:

``````int moveTime = 500; // Move every 0.5s
unsigned long int startMillis = 0;
int position = lightOFF;
int step = 5; // Move 5 degrees

void loop() {
if (millis() - startMillis >= moveTime) {
servo1.write(position);
if (position <= lightON) {
position = position + step;
}
startMillis = millis();
}
// Do other things
}
``````

Untested and incomplete, but you get the idea.

The best way is to use map() function.

``````void loop() {
unsigned long progress = millis() - startMillis;

int angle = map(progress, 0, MOVING_PEDIOD, lightOFF , lightON);
servo1.write(angle);
}
``````

The above code use the millis() function, therefore you do not need to worry about blocking other code.

Full instruction is available on How to control speed of servo motor

• Nice idea! It should be combined with `constrain()` in order to avoid overshooting (`map()` does not implicitly `constrain()`). Dec 2 '20 at 8:05