Skip to content

Instantly share code, notes, and snippets.

@simonebaracchi
Created August 18, 2015 17:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonebaracchi/b17bb0b20bc076025932 to your computer and use it in GitHub Desktop.
Save simonebaracchi/b17bb0b20bc076025932 to your computer and use it in GitHub Desktop.
Routines for power saving on the Arduino. Posted at http://simonebaracchi.eu/posts/arduino-power-cutter/
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
// watchdog interrupt
ISR (WDT_vect)
{
wdt_disable(); // disable watchdog
}
void
power_saving_sleep()
{
// disable ADC
byte old_ADCSRA = ADCSRA;
ADCSRA = 0;
power_all_disable();
PCIFR |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2); // clear any outstanding interrupts
PCICR = 0;
TWCR = bit(TWEN) | bit(TWIE) | bit(TWEA) | bit(TWINT);
digitalWrite (A4, LOW);
digitalWrite (A5, LOW);
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
wdt_reset(); // pat the dog
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
noInterrupts (); // timed sequence follows
sleep_enable();
// turn off brown-out enable in software
MCUCR = bit (BODS) | bit (BODSE);
MCUCR = bit (BODS);
interrupts (); // guarantees next instruction executed
sleep_cpu ();
// cancel sleep as a precaution
sleep_disable();
power_all_enable();
ADCSRA = old_ADCSRA;
}
void
power_saving_init()
{
for (byte i = 0; i &lt;= A5; i++) {
pinMode (i, OUTPUT);
digitalWrite (i, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment