1

I have the following snippet of code:

const unsigned long fiveMinutes = 5 * 60 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

The doStuff() routine is getting called on every loop() iteration, because the value of lastCheck isn't getting updated. I thought Icould update global variables inside subroutines, but the behavior I'm seeing says otherwise. What am I doing wrong? (doStuff() is defined and works correctly, I'm not posting it here for brevity.)

  • "unsigned long lastCheck = 0 - fiveMinutes;" Are you sure you meant that? – Ignacio Vazquez-Abrams Aug 1 '15 at 1:55
  • Yes. It works with that line, the line of concern is lastCheck = now; inside loop(). That line doesn't update the lastCheck variable correctly. – John Aug 1 '15 at 2:01
  • Post the disassembly of loop(). – Ignacio Vazquez-Abrams Aug 1 '15 at 2:20
  • It really would be useful if we could see what doStuff() is doing. Maybe it resets the Arduino and it is constantly rebooting itself. Does the program have the same side effect if doStuff is simplified to just a println()? – Octopus Aug 1 '15 at 6:42
  • I have the following snippet of code: - Unfortunately snippets don't cut it as I try to explain at Snippets R Us! - you need to post a Minimal, Complete, and Verifiable example. That is, code that actually demonstrates your point. – Nick Gammon Aug 2 '15 at 20:39
1

I modified your code to produce a working example:

const unsigned long fiveMinutes = 20 * 1000UL;
unsigned long lastCheck = 0 - fiveMinutes;
unsigned long now = 0;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  Serial.println (fiveMinutes);
  }  // end of setup

void doStuff ()
  {
  Serial.println ("Doing stuff");
  }    

void loop() {
  now = millis();
  if ( now - lastCheck >= fiveMinutes ) {
    doStuff();
    lastCheck = now;
  }
}

I reduced the interval to 20 seconds, and Ignacio Vazquez-Abrams is correct about the initial test, however apart from that, I see "Doing stuff" every 20 seconds.


I thought I could update global variables inside subroutines ...

You can.


Are you sure you didn't have:

void loop() {
  unsigned long lastCheck;
...

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.