Sleeping and Time Keeping

I would like to sleep my Arduino between sensor readings to conserve power. To do this I am using a watch dog timer. The Arduino sleeps for 8 seconds then wakes up and checks to see the time. However, the time as reported by millis() is definitely not correct. So my question is, how can I keep time while sleeping?

void loop()
{
  ReceiveDataFromBluetooth();
  ReceiveDataFromSerial();
  
  if(f_wdt == 1)//go to sleep
  {
    f_wdt = 0;
    sleepUntilTime = points*MilliSecondsToSleepBetweenDataCollectionCycles-delayOfNodeToBaseStation;
    while(millis()<sleepUntilTime)
    {
      Serial.print("The time is " + String(millis()) + " Continue to sleep until " + sleepUntilTime);
      delay(30);
      enterSleep();
      if(bluetooth.available()||Serial.available()) // don't sleep if there is communication
        break;
    }
  }
  if(millis()>sleepUntilTime) // if it's data collection time
  {
    Serial.println("data collected");
    data[points] = analogRead(A0);
    points++;
    points = points % lengthOfDataToSend;
    sleepUntilTime = points*MilliSecondsToSleepBetweenDataCollectionCycles-delayOfNodeToBaseStation;
  }
  numberOfIdleCycles++;
  if(numberOfIdleCycles >= NumberOfAcceptableIdleCyclesBeforeSleeping) // if you're idle
  {
    f_wdt = 1; //go to sleep next cycle
    
    numberOfIdleCycles=0;
  }

If you are asleep in low-power mode for 8 seconds then when you wake up you have been asleep 8000mS so just adjust your logic by that amount. Not a perfect solution, but it will give you an approximation.

Nick has some good low-power pointers here: low power

Ray

Of course, an external I2C clock is the right answer.

The WD timer is very inaccurate isn't it? Also it will reset the code so millis() will start from scratch. But as Ray says that doesn't matter because by definition it's been 8 secs since the last time.

But that still leaves the accuracy of the WD, I would look into that.

An RTC is a better way, also IIRC the Mega1284 has an real time timer that can be used for this sort of thing.


Rob