Controlling Servo with Millis

I am trying to be able to control a servos movement with millis and without delay. I tried combining the "sweep" sketch and the "blinkwithoutdelay" sketch but for some reason that doesnt work.

Any idea on why this doesn't work? Any help is appreciated.

Here is the code I came up with:

#include <Servo.h>

Servo myservo;
int pos = 0;

long previousMillis = 0;
long interval = 15;

void setup()
{
myservo.attach(9);
}

void loop() {

unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval){
previousMillis = currentMillis;

for(pos = 0; pos < 180; pos += 1)
{
myservo.write(pos);

}
for(pos = 180; pos>=1; pos-=1)
{
myservo.write(pos);

}
}
}

-The code also doesn't work when I take one of those for loops out and only have the servo sweep in one direction once.

Try:
unsigned long previousMillis = 0;

Do you mean:
unsigned long interval = 15000UL;

Put some delay in eg:
for(pos = 0; pos < 180; pos += 1)
{
myservo.write(pos);
delay(20);
}
etc.

Use T to format your code

I cant add a delay, I would like to keep the rest of the code running while the servo sweeps because the rest of the code contains leds that are time sensitive and are in sync with music. Is there any other way to control a servos position and speed without using delay?

I cant add a delay, I would like to keep the rest of the code running while the servo sweeps because the rest of the code contains leds that are time sensitive and are in sync with music. Is there any other way to control a servos position and speed without using delay?

Try it, just to see what happens.
You can take them out later or use mills() to replace them (see blink without delay examples).

I don't think you have quite grasped the concept.

Your program runs the code within the IF statement at 15 millisec intervals. But within that IF statement you try to move the servo all the way left and then all the way right (or vice versa) - all within 15 millisecs?

Your program needs to be redesigned so that within the IF statement it only moves the servo a single step on the way between 0 and 180 or between 180 and 0.

...R

You always need state variables when replacing delay() by millis(), since you have
to always restart where you left off.

int position = 0 ;    // state variable
boolean forward = false ;   // state variable

unsigned long ts = millis () ;   // time accounting.
#define DELAY 20


void loop ()
{
  if (millis () - ts >= DELAY)
  {
    ts += DELAY ;   // setup timestamp for next time.
    if (forward)
    {
      servo.write (-- position) ;  // progress the servo
      if (position == 0)  // test for reverse
        forward = false ;
    }
    else
    {
      servo.write (++ position) ;  // progress the servo
      if (position == 180)  // test for reverse
        forward = true ;
    }
  }
  // other stuff
}
1 Like