You are resetting the timer on the first phase [write(15)
] instead of after the last phase [after write(65)
]! The previousMillis = currentMillis
should be only after the last phase, before the loop repeats. Not only that, but the time at which each phase executes needs to be different. Currently every if()
statement is set to run after interval has elapsed. If, for example, you wanted interval to be the delay between each phase, you could use interval*1 on the first phase, interval*2 on the second, and interval*3 on the third. For example:
if (currentMillis - previousMillis <= interval * 1) {
// Runs from interval*0 to interval*1;
myservo.write(15);
}
else if (currentMillis - previousMillis <= interval * 2) {
// Runs from interval*1 to interval*2;
myservo.write(35);
}
else if (currentMillis - previousMillis <= interval * 3) {
// Runs from interval*2 to interval*3;
myservo.write(65);
}
else {
// Runs once after interval*3;
// *or* runs on first iteration when previousMillis is zero;
previousMillis = currentMillis;// Reset the loop;
}
To put the above logic in English:
write(15)
while time is between 0 and 1 intervals;
write(35)
while time is between 1 and 2 intervals;
write(65)
while time is between 2 and 3 intervals;
- reset the loop once time reaches 3+ intervals.
Note the use of else if
instead of simply if
on consecutive statements. This prevents more than one code block from running on the same iteration of the loop()
.
Edit: I highly recommend having a small delay (like 1ms) somewhere in the loop()
, such as at the end. It would be a bad idea to constantly run the write()
function when the value is the same as on the last call.
On the other hand, if your starting value is indeed 150 and the loop should start only after interval*1, you may want to iterate from interval*2 through interval*4:
if (currentMillis - previousMillis <= interval * 1) {
// Runs from interval*0 to interval*1;
// Do nothing; servo is set to either 150 or 65 during this time;
}
else if (currentMillis - previousMillis <= interval * 2) {
// Runs from interval*1 to interval*2;
myservo.write(15);
}
else if (currentMillis - previousMillis <= interval * 3) {
// Runs from interval*2 to interval*3;
myservo.write(35);
}
else if (currentMillis - previousMillis <= interval * 4) {
// Runs from interval*3 to interval*4;
myservo.write(65);
}
else {
// Runs once after interval*4;
// *or* runs on first iteration when previousMillis is zero;
previousMillis = currentMillis;// Reset the loop;
}