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.)
1 Answer 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;
...
unsigned long lastCheck = 0 - fiveMinutes;
" Are you sure you meant that?lastCheck = now;
insideloop()
. That line doesn't update thelastCheck
variable correctly.loop()
.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.