Sorry to bother but I am at my wits end. I'm experimenting with timers, and starting very simple. The following code is supposed to print the content of a variable each time an interval of time has passed, then update that variable. But for some reason I'm getting no output on the serial monitor.
I have used the serial monitor before on other projects without issue, so I'm not sure what the problem could be.
Is there any error in my code?
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;
void setup() {
Serial.begin(9600);
}
void loop() {
if (currentMillis - previousMillis >= interval) {
Serial.println(previousMillis);
previousMillis = currentMillis;
}
else {
;
}
}
// previousMillis += interval;
1 Answer 1
Since currentMillis
is just a simple variable, it will not automatically update. In fact the initialization with millis()
in global scope is unnecessary. Just initialize the value with 0. At the time, where the global variables are created, the time is 0ms anyways.
You need to update the currentMillis
variable everytime, before using it. So just insert
currentMillis = millis();
right at the start of the loop()
function.
-
1Thanks again for your help.Zhelyazko Grudov– Zhelyazko Grudov2021年02月11日 13:11:36 +00:00Commented Feb 11, 2021 at 13:11
currentMillis
variable anywhere. Its value does not magically update, when you have once assigned the value ofmillis()
to it. InsertcurrentMillis = millis()
right at the start of theloop()
function.