Tapatalk

Using millis() with LowPower - Thoughts?

Using millis() with LowPower - Thoughts?

21

PostDec 31, 2018#1

Hello,

Working on a project wherein the loop() I want to use millis() to execute code based on a number of different intervals. Because millis() does not update while sleeping, I came up with the following concept. Interested in feedback. The advantage of this approach is that any library or code that uses mills for timing, does not require changes.


// code snippet

unsigned long lastEvent = 0;  // last time in millis() event fired.
#define ONE_HOUR (60*60*1000L)   // one hour


loop()
{
unsigned long currentMillis = millis();
if((unsigned long)(currentMills - lastEvent) >= ONE_HOUR)
{
... do stuff
lastEvent = currentMills;
}

LowPower.powerDown(SLEEP_8S,ADC_OFF,BOD_OFF); // goto sleep for 8S
accountForSleep(8000); // add 8 seconds If we wake from an interrupt, our millis() clock will be a little fast... 
}

void accountForSleep(unsigned long adjustment)
{
  extern volatile unsigned long timer0_millis;
  byte statusReg = SREG;
  cli();
  timer0_millis += adjustment;  // Need interrupts off for atomicity
  SREG = statusReg;
}

Thoughts?