I've been experimenting with the low power library from RocketScream to gain some knowledge about low power operation and eventually trying to run a Mega328P of a CR2032 lithium battery for an extended period of time.
For anybody who is interested in the watchdog timer, extended sleep times and low power operation etc, I thought I'd share this.
The code is quite simple, it sleeps for 1 hour, wakes up, prints a full stop character (+CR&LF) to the serial port and goes back to sleep again for another hour.
#include "LowPower.h"
// 1 hour = 3600 seconds
const uint16_t delayOneHour = 3600;
void setup()
{
Serial.begin(9600);
Serial.println(F("Low Power Sleep Demo"));
Serial.println(F("Using WDT to wake every hour -ish!"));
Serial.flush();
delay(1000);
}
void loop()
{
Serial.println(".");
Serial.flush();
longSleep( delayOneHour );
}
void longSleep( uint16_t sleepInSeconds )
{
if ( sleepInSeconds & 0x01 ) LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);
if ( sleepInSeconds & 0x02 ) LowPower.powerDown(SLEEP_2S, ADC_OFF, BOD_OFF);
if ( sleepInSeconds & 0x04 ) LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);
while ( sleepInSeconds & 0xFFF8 ) {
sleepInSeconds = sleepInSeconds - 8;
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}
}
I left it running for about a day with the IDE serial monitor generating a timestamp each time the 328P woke up and printed to the serial port. This is the output from the serial monitor:
16:24:09.946 -> Low Power Sleep Demo
16:24:09.946 -> Using WDT to wake every hour -ish!
16:24:10.996 -> .
17:24:50.772 -> .
18:25:32.029 -> .
19:26:12.896 -> .
20:26:54.528 -> .
21:27:35.270 -> .
22:28:15.707 -> .
23:28:55.938 -> .
00:29:36.059 -> .
01:30:15.984 -> .
02:30:55.757 -> .
03:31:35.496 -> .
04:32:15.228 -> .
05:32:54.898 -> .
06:33:34.540 -> .
07:34:14.113 -> .
08:34:53.622 -> .
09:35:33.096 -> .
10:36:12.641 -> .
11:36:53.565 -> .
12:37:35.515 -> .
13:38:18.985 -> .
14:39:03.378 -> .
15:39:48.886 -> .
16:40:34.937 -> .
As you can see, it oversleeps by roughly 40 seconds per hour, resulting in it oversleeping by around 16 minutes a day. The watchdog timer clock isn't particularly accurate but it's good enough to wake the processor up every so often to carry out a task.
Anyways, hope this is of interest.