Skip to content

Instantly share code, notes, and snippets.

@bigjosh
Created August 8, 2017 00:28
Show Gist options
  • Save bigjosh/1ec5ff5d38fd64de1c958edbc55e2a07 to your computer and use it in GitHub Desktop.
Save bigjosh/1ec5ff5d38fd64de1c958edbc55e2a07 to your computer and use it in GitHub Desktop.
Code to make a very low power delay by setting the watchdog timer and then sleeping.
// Goto bed, will only wake up on button press interrupt (if enabled) or WDT
static void deepSleep(void) {
set_sleep_mode( SLEEP_MODE_PWR_DOWN );
sleep_enable();
sleep_cpu(); // Good night
}
// Don't do anything, just the interrupt itself will wake us up
// TODO: If we ever need more code space, this could be replaced by an IRET in the VECTOR table.
EMPTY_INTERRUPT( WDT_vect );
#define HOWLONG_16MS (_BV(WDIE) )
#define HOWLONG_32MS (_BV(WDIE) | _BV( WDP0) )
#define HOWLONG_64MS (_BV(WDIE) | _BV( WDP1) )
#define HOWLONG_125MS (_BV(WDIE) | _BV( WDP1) | _BV( WDP0) )
#define HOWLONG_250MS (_BV(WDIE) | _BV( WDP2) )
#define HOWLONG_500MS (_BV(WDIE) | _BV( WDP2) | _BV( WDP0) )
#define HOWLONG_1S (_BV(WDIE) | _BV( WDP2) | _BV( WDP1) )
#define HOWLONG_2S (_BV(WDIE) | _BV( WDP2) | _BV( WDP1) | _BV( WDP0) )
#define HOWLONG_4S (_BV(WDIE) | _BV( WDP3) )
#define HOWLONG_8S (_BV(WDIE) | _BV( WDP3) | _BV( WDP0) )
// Goto sleep - get woken up by the watchdog timer or other interrupt like button
// This is very power efficient since chip is stopped except for WDT
// Note that if the timer was on entering here that it will stay on, so LED will still stay lit.
static void sleepFor( uint8_t howlong ) {
wdt_reset();
WDTCR = howlong; // Enable WDT Interrupt (WDIE and timeout bits all included in the howlong values)
sei();
deepSleep();
cli();
WDTCR = 0; // Turn off the WDT interrupt (no special sequence needed here)
// (assigning all bits to zero is 1 instruction and we don't care about the other bits getting clobbered
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment