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;
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. – chrisl Feb 11 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. – Zhelyazko Grudov Feb 11 at 13:02
3

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.