Put an AVR to Sleep With sleep_mode and Wake on Pin Change
Use avr-libc set_sleep_mode, sleep_enable and sleep_cpu to power down an ATmega328P and wake on a pin change interrupt, with the race-free sequence.

An ATmega328P running at 5 V and 16 MHz draws several milliamps just by existing, and the same chip in its deepest sleep state draws a tiny fraction of that. A battery-powered AVR project spends nearly all of its time there. The avr-libc header <avr/sleep.h> gives a small set of macros to get the chip into sleep, and the Power Management and Sleep Modes chapter of the ATmega328P datasheet says which interrupts can wake each mode. This post builds a complete program that powers the chip down, wakes it on a pin change from a button, does a short piece of work and goes back to sleep, in the order that avoids missing a wake-up. It uses avr-gcc 7.3.0 with avr-libc 2.0.0 (the toolchain bundled with Arduino AVR core 1.8.6) and a bare ATmega328P at 16 MHz.
The macros
The header gives you these, as documented in the avr-libc manual:
| Macro | What it does |
|---|---|
set_sleep_mode(mode) | Writes the sleep mode bits in SMCR |
sleep_enable() | Sets the SE bit, which permits the sleep instruction to act |
sleep_cpu() | Executes the sleep instruction |
sleep_disable() | Clears the SE bit |
sleep_mode() | sleep_enable(), sleep_cpu(), sleep_disable() in one |
sleep_bod_disable() | Disables brown-out detection during sleep, on parts that support it |
The SMCR register holds the mode in the SM2:0 bits and the enable in SE. The sleep modes available on the ATmega328P are Idle, ADC noise reduction, Power-down, Power-save, Standby and Extended standby, and the avr-libc constants are SLEEP_MODE_IDLE, SLEEP_MODE_ADC, SLEEP_MODE_PWR_DOWN, SLEEP_MODE_PWR_SAVE, SLEEP_MODE_STANDBY and SLEEP_MODE_EXT_STANDBY.
For the lowest consumption use SLEEP_MODE_PWR_DOWN. In power-down mode the main oscillator stops, and only a few things can wake the chip, because nothing is clocked: an external reset, the watchdog interrupt, a brown-out reset, a TWI address match, an external level interrupt on INT0 or INT1, and a pin change interrupt. A pin change interrupt works in power-down because the pin change logic is asynchronous, so it does not need a running clock. A timer compare interrupt does not work there, because the timer is not running.
Configure the pin change interrupt
The ATmega328P groups its pins into three pin change interrupt banks: PCINT0 to PCINT7 on port B, PCINT8 to PCINT14 on port C, and PCINT16 to PCINT23 on port D. Each bank has one interrupt vector (PCINT0_vect, PCINT1_vect, PCINT2_vect), one enable bit in PCICR and a per-pin mask register (PCMSK0, PCMSK1, PCMSK2).
A button on PB0 (Arduino pin 8), wired to ground with the internal pull-up enabled, belongs to bank 0:
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
static void pin_change_init(void)
{
DDRB &= ~(1 << PB0); // input
PORTB |= (1 << PB0); // internal pull-up
PCMSK0 |= (1 << PCINT0); // PB0 may trigger the bank 0 interrupt
PCICR |= (1 << PCIE0); // enable bank 0
}
ISR(PCINT0_vect)
{
// nothing to do: the wake-up itself is the event
}The handler can be empty. The interrupt exists to bring the core out of sleep, and the main code then decides what happened. An empty handler would normally be written with the EMPTY_INTERRUPT(PCINT0_vect) macro from <avr/interrupt.h>, which generates a handler with no prologue.
A pin change interrupt fires on any edge, press and release both, so the main code reads the pin after waking to see which one it was.
The race-free sleep sequence
The avr-libc manual documents the pattern to use when a flag set by an interrupt decides whether to sleep. The problem is the same as with any wait: an interrupt that fires between the flag test and the sleep instruction would be handled before sleeping, and the chip would then sleep with the event already consumed. The sleep instruction on the AVR has a useful property: it executes the instruction after sei before any pending interrupt is taken. The sequence is:
volatile uint8_t pressed;
ISR(PCINT0_vect)
{
pressed = 1;
}
static void sleep_until_event(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli(); // no interrupt can slip in between test and sleep
if (!pressed) {
sleep_enable();
sleep_bod_disable(); // save more current: must be followed within 3 cycles by sleep
sei(); // the instruction after sei always executes
sleep_cpu(); // an interrupt that is already pending wakes immediately
sleep_disable();
}
sei();
}
int main(void)
{
power_adc_disable();
power_spi_disable();
power_twi_disable();
power_timer1_disable();
power_timer2_disable();
pin_change_init();
sei();
for (;;) {
sleep_until_event();
if (pressed) {
pressed = 0;
PORTB ^= (1 << PB5); // toggle the LED on the Arduino board
}
}
}The central trick is sei(); sleep_cpu();. The AVR instruction set guarantees that the instruction following SEI executes before any pending interrupt is serviced, so the sleep instruction runs with the interrupt enabled but not yet taken. If an interrupt was pending, it wakes the sleep immediately, since the chip handles it after sleep returns. If nothing was pending, the chip sleeps and the interrupt wakes it. No ordering lets the event be lost. This is the pattern in the avr-libc <avr/sleep.h> documentation, and sleep_mode() alone does not give it, because it does not control the interrupt flag.
sleep_bod_disable() is a macro on the parts that support software control of the brown-out detector in sleep, such as the ATmega328P (the ATmega328 non-P variant lacks it). It must be executed with interrupts disabled and the sleep instruction must follow within three clock cycles, which is why it sits right before sei() and sleep_cpu(). The datasheet describes the timing of the BODS and BODSE bits.
Power reduction before sleep
Sleep stops the CPU, but the peripherals that are still clocked keep drawing current, and some are clocked in some modes. Two layers cut that:
power_xxx_disable()from<avr/power.h>sets the bits inPRR, the power reduction register, which switches the peripheral's clock off in all modes. Re-enable one withpower_xxx_enable()before using it again.Disable the ADC explicitly before sleep, since the ADC keeps drawing unless
ADENis cleared:ADCSRA &= ~(1 << ADEN);.power_adc_disable()only works when the ADC is already disabled.
Pins matter too. A floating input draws shoot-through current when its voltage sits in the transition region, so configure every unused pin as an output driven low, or as an input with the pull-up enabled, as the datasheet's I/O chapter recommends under "Digital input enable and sleep modes". The next posts in this series return to that leakage topic.
What the output looks like
With no console, the visible behaviour is the LED toggling on each press. Measure current with a meter in series with the supply, on a bare chip or a board with the voltage regulator and the USB-serial chip removed or disabled. On an Arduino Uno board the regulator and the USB chip dominate the current, so the sleep gain is hidden:
ammeter, bare ATmega328P at 5 V, 16 MHz crystal:
awake, running the loop: milliamp range
power-down, ADC and BOD off: microamp range (see datasheet table for your voltage)
press button: brief rise, LED toggles, back to sleepThe ranges are the ones the datasheet gives, and your numbers depend on voltage, temperature and pin states, so measure them.
Wake-up time
In power-down the oscillator is stopped, and on wake-up the AVR must wait for it to restart before executing. The wait is defined by the start-up time fuses, CKSEL and SUT, which come from the datasheet's table of start-up times, and it can be long with a ceramic resonator or crystal and short with the internal RC oscillator. For a project that wakes often, the choice of clock source and fuses affects the average current as much as the sleep mode.


