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.)

asked Aug 1, 2015 at 1:34
5
  • "unsigned long lastCheck = 0 - fiveMinutes;" Are you sure you meant that? Commented Aug 1, 2015 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. Commented Aug 1, 2015 at 2:01
  • Post the disassembly of loop(). Commented Aug 1, 2015 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()? Commented Aug 1, 2015 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. Commented Aug 2, 2015 at 20:39

1 Answer 1

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;
...
answered Aug 1, 2015 at 2:07

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.