1

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;
asked Feb 11, 2021 at 12:52
2
  • Simple problem: You are not updating the currentMillis variable anywhere. Its value does not magically update, when you have once assigned the value of millis() to it. Insert currentMillis = millis() right at the start of the loop() function. Commented Feb 11, 2021 at 12:56
  • Thank you for your response. I thought it automatically updated with the latest value of millis() constantly. So it would only update at each iteration of the loop? If you would like to post this is an answer I can accept it if that makes any difference to you, because it is very helpful to me. Commented Feb 11, 2021 at 13:02

1 Answer 1

2

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.

answered Feb 11, 2021 at 13:09
1
  • 1
    Thanks again for your help. Commented Feb 11, 2021 at 13:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.