Servo code not working as intended

Hey guys, I am new to this community and this is my first post, so I don’t really know if this is the right section for this question…

Anyway, I am trying out a project where I can program my servo to turn to 2 position with a delay in between. I tried using Millis so that the servo can work every few seconds that I want. Here is the code below

[#define pos1 155
#define pos2 20

#include <Servo.h>

//variables
Servo mainServo;

unsigned long previousMillis = 0;
unsigned long interval=3000;

void setup()
{

mainServo.attach(3);

}

void loop()
{

unsigned long currentMillis = millis();

if(currentMillis - previousMillis >= interval)
{
previousMillis=currentMillis;
mainServo.write(pos1); //move servo to fill position 1

delay(3000);

mainServo.write(pos2);//move servo to fill position 2

}

}

]

Somehow the code does not work. It is able to do 1 round of the program but it does not loop. I would appreciate any help in rectifying the problem. THANKS IN ADVANCE

There is hardly any point in using millis() to control the time when things happen when you then stuff a stump-stupid call to delay() in the code.

Why would you do that?

Go check the BlinkWithoutDelay example if you haven’t already - the clue is in the name!

The problem with the current code is that when the servo moves to pos1 and the delay() starts millis() is still getting larger so as soon as the servo moves back to pos2 the millis() test is satisfied again so it moves straight back to pos1. In practice it will not actually move to pos2 because there is no time for it to get there.

You could fix that but really should be using millis() for all timing.

The demo Several Things at a Time is an extended example of BWoD and includes some servo code.

...R