Try Embedded

Designing for low power

Sleep modes and wake sources, entering them on STM32 and AVR, clocks and pins that draw, race to sleep.

Sleeping is the job

A low-power device spends almost all its life asleep, so the firmware's main job is to get to sleep quickly, sleep as deeply as it can, and wake only for a reason. The previous lesson showed how to find where the charge goes; this one is the toolbox for cutting it.

The modes

Every MCU family has a ladder of modes, each turning more off and waking more slowly:

Mode (STM32 / AVR)What stopsWakes onTypical currentWake-up
Sleep / Idlethe core clockany interrupt30 to 50 % of Runimmediate
Stop / Power-saveevery high-speed clock; RAM and registers keptEXTI lines (pins), RTC, some peripherals' own wake-ups1 to 20 µA (STM32), 1 µA with a 32 kHz timer (AVR)a few µs; the clocks restart from the internal oscillator
Standby / Power-downthe regulator for the core; RAM lost (STM32), RAM kept (AVR)wake-up pins, RTC, watchdog, reset0.1 to 2 µAlike a reset (STM32)
Shutdownalmost everythingwake-up pins, resettens of nAa full boot

The choice is made by what must wake the device. A door sensor needs a pin interrupt: Stop on an STM32, power-down on an AVR (whose external interrupts and pin changes work asleep). A logger that wakes on time needs the RTC and its 32 kHz crystal. A device that must notice a UART byte at once needs that UART awake, often Sleep only, unless the UART can wake from Stop (the LPUART of an L4 or G0 can).

Entering them

On a Cortex-M, the instruction is always WFI (or WFE); what it does depends on two bits. SCB->SCR SLEEPDEEP chooses Sleep (0) or a deep mode (1); the deep mode is then chosen in the PWR peripheral (PDDS and LPDS on an F4, LPMS on a G0 or L5). On an AVR, SMCR holds the mode and the enable bit, and the SLEEP instruction enters it.

/* STM32F4: Stop mode with the low-power regulator, woken by a pin's EXTI line. */
RCC->APB1ENR |= RCC_APB1ENR_PWREN;
PWR->CR = (PWR->CR & ~PWR_CR_PDDS) | PWR_CR_LPDS;   /* Stop, not Standby; low-power regulator */
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
__WFI();                                            /* asleep here until an EXTI interrupt */
SCB->SCR &= ~SCB_SCR_SLEEPDEEP_Msk;
clock_setup();                                      /* Stop restarts on the HSI: set the PLL up again */
/* AVR: power-down, woken by the watchdog's interrupt (WDIE) every 8 s. */
ADCSRA &= ~_BV(ADEN);              /* the ADC draws ~300 uA even asleep */
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_bod_disable();               /* the brown-out detector for the sleep: ~20 uA */
sleep_cpu();
sleep_disable();

Two traps on the STM32 side: after Stop the system clock is the internal 16 MHz oscillator, whatever it was before, so the PLL and the baud rates must be set up again; and SysTick, which stops with the clocks, keeps no time across Stop, so use the RTC for anything that must.

Everything else that draws

The mode is half of it. The other half is everything still powered:

  • Peripheral clocks. Each enabled peripheral clock costs current even when the peripheral is idle; enable a clock for the moment the peripheral is used. An STM32's RCC has separate enable bits for Sleep mode (...LPENR), so peripherals can be clocked when running and gated when asleep.
  • Pins. A floating digital input's buffer switches on noise and draws current; set unused pins to analog mode (STM32) or outputs driven low (AVR). A pull-up against a low signal draws V/R for as long as it is low.
  • The ADC, comparators, references and the brown-out detector draw tens to hundreds of µA on their own; disable them for the sleep.
  • Debug: with a debugger attached, or DBGMCU bits set, the core's clock may stay on in Stop. Measure without the probe.
  • External parts: power sensors from a GPIO or a load switch and turn them off; pick a regulator with a quiescent current in µA, or run from the battery directly.

Running less

When the device is awake, it should finish fast and go back to sleep: race to sleep. A faster clock draws more current but for less time, and because Run current has a fixed part as well as the per-MHz part, the charge for a job is often lowest at a high clock. The exception is waiting: a 10 ms sensor conversion costs the same time at any clock, so wait for it asleep (Sleep mode with the conversion's interrupt, or Stop with a timer).

Avoid busy-waiting at all. A loop that polls a flag runs the core at full current doing nothing; an interrupt and a WFI do the same job for a fraction of it. Make every wait a sleep:

/* Spins at full current between the 200 ms samples: about 3.8 mA on an STM32F446 at 16 MHz. */
for (;;) {
  if (ticks >= next) { next += 200; sample(); }
}

/* Sleeps between them, woken by SysTick and the UART's interrupt: about 2.2 mA. Stop with an RTC wake-up: µA. */
for (;;) {
  if (ticks >= next) { next += 200; sample(); }
  __WFI();
}
#include <stdio.h>

/* The charge one job costs at two clocks: the Run current has a fixed part and a part per MHz. */
static double job_uas(double mhz, double cycles, double base_ua, double ua_per_mhz) {
  double seconds = cycles / (mhz * 1e6);
  return (base_ua + ua_per_mhz * mhz) * seconds;
}

int main(void) {
  /* 2 million cycles of work; Run = 1.3 mA + 0.1 mA/MHz (in uA below). */
  printf("at  8 MHz: %.0f uA.s\n", job_uas(8, 2e6, 1300, 100));
  printf("at 64 MHz: %.0f uA.s\n", job_uas(64, 2e6, 1300, 100));
  return 0;
}

Waking well

Each wake-up costs more than the work it does when the wake-up itself is slow: an oscillator that takes 1 ms to start, a PLL that takes 100 µs to lock, a regulator that settles, a boot that re-initialises everything after Standby. So:

  • Wake less often. Batch: collect ten samples in RAM and send them in one radio burst.
  • Wake for a reason. A pin interrupt from a sensor's threshold output (an accelerometer's motion interrupt, a comparator) instead of polling the sensor on a timer.
  • Keep the fast path short. After a door interrupt, the firmware does not need the full clock tree, the display or the logging subsystem: read, decide, go back.

Going deeper

Interview question: How do you choose a sleep mode for a battery-powered device?

Answer: From what must wake it and what must survive the sleep. List the wake sources the application needs (a pin, the RTC, a UART byte, a peripheral's event) and what state must be kept (RAM, registers, a running counter), then pick the deepest mode that still offers those: Stop keeps RAM and wakes on EXTI and the RTC in microseconds; Standby loses RAM and wakes like a reset, so state goes to backup registers; Sleep is for wake sources that need the high-speed clocks. Then account for the wake-up time and energy: a deeper mode that takes a millisecond to wake can cost more than a lighter one if the device wakes often. Finally turn off everything else that draws: peripheral clocks, floating pins, analog blocks, external parts.

Interview question: Why should a battery-powered device avoid busy-wait loops, and what replaces them?

Answer: A busy-wait keeps the core and its clock running at full Run current while it does nothing but poll, often for the longest phase of the device's cycle. Replacing it with an interrupt and WFI lets the core sleep until the event: a timer's interrupt for a delay, the peripheral's own completion interrupt for a conversion or transfer, a DMA transfer for a stream of bytes. The waiting then costs the Sleep or Stop current instead of the Run current, which is several times to thousands of times lower.

Interview question: Is it better to run a job at a low clock or a high one, to save energy?

Answer: Usually high, and then sleep: race to sleep. The Run current has a fixed part, the regulator, flash and analog blocks, as well as a part per MHz, so at a low clock the fixed part is paid for longer and the job's total charge is higher. The exceptions are when the work is limited by something external, such as waiting for a sensor or a slow bus, which takes the same time at any clock and should be done asleep, and when the higher clock needs a higher core voltage, extra flash wait states or a PLL whose start-up energy outweighs the saving.

Explain it: In your own words, explain what decides which sleep mode a device can use, and why its current is not the only figure that matters.

Answer: The wake sources decide it: a mode is only usable if what must wake the device still works in it, and if what must survive, RAM or a running clock, still does. Among the usable modes the deepest has the lowest current, but each wake-up from a deep mode costs time and charge, restarting oscillators and the PLL, re-initialising after a Standby. A device that wakes often can spend more on wake-ups than it saves asleep, so the choice weighs the sleep current against how often and how expensively the device wakes.