// https://forum.arduino.cc/t/testing-millis-with-servos-and-experiencing-odd-behavior/1092322
// https://wokwi.com/projects/357135312156712961
# include <Servo.h>
Servo myServo;
// I changed this for the moment:
unsigned long MOVING_TIME = 2500;
unsigned long moveStartTime;
int startAngle = 0;
int stopAngle = 180;
void setup() {
Serial.begin(115200);
Serial.println("Servo World!\n");
myServo.attach(9);
myServo.write(stopAngle);
delay(1000);
moveStartTime = millis(); // start moving
}
void loop() {
unsigned long currentMillis = millis();
unsigned long progress = currentMillis - moveStartTime;
if (progress <= MOVING_TIME) {
long angle = map(progress, 0, MOVING_TIME, stopAngle, startAngle);
myServo.write(angle);
// reporting section
static unsigned long timeOfLastReport;
static int lastReportedAngle = -1;
if (lastReportedAngle != angle) { // just print if the new issued angle is different
Serial.print(currentMillis - timeOfLastReport);
Serial.print(" ms later told servo to ");
Serial.println(angle);
timeOfLastReport = currentMillis;
lastReportedAngle = angle;
}
// end reporting section - remove it when you dare
}
}