4

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 can't use the delay() function because of some connectivity issues with another library (BLYNK).

How could I move the servo from lightOFF to lightON the quickest way possible without using the delay() function?

0

2 Answers 2

6

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.

2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.