The Complete Guide to Low-Power Firmware on Microcontrollers
Learn low-power firmware from the energy model to sleep modes, clocks, pins, wake-up sources, measurement and battery budgets, with a complete STM32 example.

A sensor on a farm gate, a tracker on a shipping crate, a remote on a coffee table and a meter on a wall all run from a battery that nobody wants to change. The microcontroller inside is a modern, fast chip that could draw tens of milliamps, and it has to live on a few microamps on average. The distance between those two numbers is closed by firmware, and most of the work is not in clever tricks. It is in understanding where the energy goes, choosing the right state for each moment, and checking the result with an instrument instead of a guess. This guide covers the whole subject for a beginner: the energy model that explains every decision, the ladder of low-power states a chip offers, how clocks, voltage, peripherals and pins add up, how to wake from sleep and how to structure the firmware around it, how to measure, and how to turn a measurement into a battery life. The worked examples use an STM32F411 for the core ideas and an STM32L476 for the full project, with notes for ESP32, RP2040, AVR and nRF52 where their behaviour differs. Facts come from the vendors' reference manuals and datasheets, the Cortex-M4 Devices Generic User Guide, and the STM32CubeF4 and CubeL4 HAL documentation. Code builds with arm-none-eabi-gcc 13.3 and CMSIS device headers.
The energy model: charge and time
Battery life is a division. A battery holds a quantity of charge, measured in milliamp-hours, and the device consumes charge at a rate measured in milliamps. Divide capacity by average current and you get hours. Everything in low-power design is a way of lowering that average current, and the average is a sum over time:
average current = (sum of current x time for each state) / total time
The product of current and time is the charge a state consumes. A state that draws 10 mA for 10 ms uses 100 microcoulombs, and a state that draws 3 microamps for a full minute uses 180 microcoulombs, which is more. This is the first idea to absorb, because it reverses intuition. The big, scary currents are brief, and the tiny currents last forever, so both matter, and the way to find which one dominates is to multiply, not to look at the biggest number.
A typical sensor spends nearly all its time asleep and a few milliseconds a minute awake. The average then sits just above the sleep current, with the active phase adding a share set by its duty cycle: the fraction of time spent active. A device that is active 0.1 percent of the time at 5 mA adds 5 microamps to the average. If its sleep current is 3 microamps, the active phase contributes more than the sleep. If the sleep current is 100 microamps because a pin leaks, the sleep dominates and no amount of active-phase optimisation helps. That is the usual story of a device that misses its battery target.
Two strategies follow from the model. The first is to spend as much time as possible in the lowest-power state that still lets the device do its job. The second is to make the active phase as short and as cheap as possible. Both come before any micro-optimisation.
Where the current goes
A CMOS microcontroller draws current in three ways, and each one is controlled by something different.
Dynamic current flows every time a transistor switches, to charge and discharge the tiny capacitances of the logic. To first order it follows P = C x V^2 x f: capacitance switched, times the square of the supply voltage, times the clock frequency. It disappears when the clock stops. Lowering the frequency reduces it linearly, lowering the voltage reduces it by the square, and gating the clock of a block removes that block's capacitance from the sum.
Static current flows even when nothing switches. Transistors are not perfect switches, and a small leakage current flows through them all the time. It depends on the process, the voltage and strongly on temperature, so a chip that sleeps at 2 microamps at room temperature may sleep at several times that in a hot enclosure. Static current is what sets the floor of the deepest sleep modes, and the main control you have is to turn off whole power domains so that the leakage is removed with them.
Analog and bias current flows in blocks that need a steady bias to work: oscillators, regulators, the brown-out detector, the ADC reference, the radio. Each is on or off, and each has a datasheet figure. A crystal oscillator, a voltage regulator in its normal mode and a brown-out detector can each cost microamps while the CPU does nothing.
The datasheet gives these as tables: run-mode current at a few frequencies with peripherals on and off, sleep-mode currents, and per-block figures. Read them before designing. They tell you, for your chip and your supply voltage, how much the whole thing could possibly save.
The ladder of states
Every microcontroller family offers a ladder of states, from fully running to almost completely off. The names are the vendor's, and the ideas are common.
| State | What stops | What stays | Wake-up cost |
|---|---|---|---|
| Run, high speed | Nothing | Everything | None |
| Run, reduced | Nothing, but slower clock and lower voltage | Everything | Frequency change |
| Sleep | The CPU clock | All peripherals and clocks | Instant |
| Deep sleep or Stop | Most clocks, oscillators, PLL | RAM, registers, a few wake-up sources | Oscillator start and clock restore |
| Standby | The core power domain | A small backup domain: RTC, a few registers | A full reset |
| Shutdown or off | Nearly everything | Maybe one wake pin | A cold start |
The Arm architecture defines only the first step into that ladder: the WFI and WFE instructions, which stop the core, and the SLEEPDEEP bit in the System Control Register, which permits the chip to go deeper. Everything below the core is the vendor's design. STMicroelectronics calls the modes Sleep, Stop and Standby. Nordic calls them System ON idle and System OFF, ESP32 calls them light sleep and deep sleep, and Raspberry Pi calls the deepest one dormant. The mapping is close enough that learning one makes the others easy, and the later sections show each.
Moving down the ladder saves current and costs two things. The first is wake-up time and energy: restarting an oscillator and a PLL takes microseconds to milliseconds and draws current meanwhile. The second is state: the deeper the mode, the more of the chip loses its contents, until in Standby everything but a few backup words is gone and the program starts over. A good design picks the shallowest state that meets the current budget, because the deeper states bring more complexity and more things to restore.
The post on sleep, stop and standby modes goes through the three STM32 levels in detail, and the post comparing Stop and Standby gives a break-even rule for choosing between them.
Step one: stop the CPU when it has nothing to do
The cheapest saving requires one instruction. A program that spins in a main loop waiting for events keeps the core running at full speed to do nothing. The WFI instruction stops the core until an interrupt arrives, and CMSIS provides it as __WFI():
#include "stm32f4xx.h"
volatile uint8_t event;
int main(void)
{
board_init();
for (;;) {
__disable_irq();
if (!event) {
__WFI(); // sleeps until an interrupt; a pending one wakes it even while masked
}
__enable_irq();
if (event) {
event = 0;
handle_event();
}
}
}The __disable_irq() before the test and __enable_irq() after the __WFI() close a race: an interrupt that arrives between the check and the instruction would otherwise be handled before the sleep, and the core would then sleep through the event it was waiting for. The post on putting a Cortex-M to sleep with WFI explains why the pattern is correct. The sleep this gives is shallow, with all clocks running, so the saving is the core's own current. At a high clock that is a large share of the run-mode current, and the wake-up is instant.
The same idea in other ecosystems has other names. In an RTOS, the idle task executes WFI, and a tickless idle mode extends the sleep by stopping the periodic tick. On the Arduino and AVR, sleep_cpu() from <avr/sleep.h> does the same.
Step two: lower what runs when you are awake
If the device has to be awake for some time, make that time cheap. Three controls apply: the frequency, the voltage and the clock gates.
Frequency. Dynamic current falls in proportion to the clock. A program that needs 2 million instructions a second does not need a 100 MHz clock. Run slower, and the core is active for a longer time at a lower current. The trade-off is not always in favour of slow: the energy per task is the current times the time, and a core running at a lower frequency at the same voltage takes proportionally longer, so dynamic energy per task stays about the same while static current is paid for longer. The practical rule is to pick the lowest frequency that finishes in the time available at the lowest voltage that supports it, and to use "run fast, then sleep deeply" when the sleep is much cheaper than the leakage of running long.
Voltage. On parts with a configurable core regulator, a lower voltage range reduces both dynamic and leakage current but limits the maximum frequency. The STM32F411 has three scales: scale 1 up to 100 MHz, scale 2 up to 84 MHz and scale 3 up to 64 MHz. Raise the voltage before raising the frequency, and lower the frequency before lowering the voltage.
#include "stm32f4xx_hal.h"
void run_at_48mhz_scale3(void)
{
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3);
// then configure the PLL for 48 MHz, with one flash wait state
}Clock gates. Every peripheral has an enable bit in the reset and clock control block. A peripheral without a clock draws almost no dynamic current. After reset most peripherals are off, and the HAL turns on what you initialise. Audit the enable registers at the end of start-up, and switch off what the firmware does not use:
void clocks_audit(void)
{
printf("AHB1ENR=0x%08lX APB1ENR=0x%08lX APB2ENR=0x%08lX\r\n",
(unsigned long)RCC->AHB1ENR, (unsigned long)RCC->APB1ENR, (unsigned long)RCC->APB2ENR);
}Decode each set bit against the register description. A bit left on from development, such as a timer you tried and dropped, is a small permanent drain. The post on lowering STM32 run current covers voltage scaling and clock gating step by step, with the limits from the reference manual.
Step three: pins, the quiet leak
Pins are where most excess sleep current hides. A CMOS input that nothing drives floats to an indeterminate voltage, and when it lingers between the logic thresholds, both transistors of its input stage conduct and current flows from the supply to ground continuously. Multiply by the pins of a package and a chip with a datasheet sleep current of 2 microamps can measure 40 on the bench.
Three kinds of pin problems recur. A floating input, with no driver and no pull, is the first. A pull resistor that fights a driver is the second: an internal pull-up of tens of kilohms holding against a device that pulls the line low draws the supply voltage divided by the resistance, continuously. And a driven pin that feeds a load, or a signal that back-powers a chip whose supply is off, is the third.
The cure is to set every pin deliberately before sleep. On STM32 the analog mode disconnects the digital input buffer and is the lowest-leakage state for an unused pin:
void pins_to_analog(GPIO_TypeDef *port)
{
port->MODER = 0xFFFFFFFFu; // analog mode on all sixteen pins
port->PUPDR = 0; // no pull
}
void unused_pins_low_power(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN;
pins_to_analog(GPIOB);
pins_to_analog(GPIOC);
// port A keeps its SWD pins and the pins the application uses
}The chapter on I/O in each reference manual lists the reset state of each port, which is sometimes already analog or floating. Look it up, then write the states you want. The post on floating GPIO leakage explains the mechanism with the structure of the input buffer and shows the equivalents on nRF52 and AVR.
Step four: wake up on the right thing
A sleeping chip needs something to wake it. The sources fall into a few groups, and the deeper the sleep, the fewer of them work.
| Source | Works in Sleep | Works in Stop | Works in Standby |
|---|---|---|---|
| Any enabled interrupt | Yes | No | No |
| GPIO edge through EXTI | Yes | Yes | No, except the WKUP pins |
| RTC alarm or wake-up timer | Yes | Yes | Yes |
| Low-power timer | Yes | Yes, on parts that have one | Varies |
| UART with wake-up detection | Yes | On parts that support it | No |
| Independent watchdog reset | Yes | Yes | Yes |
| External reset | Yes | Yes | Yes |
For periodic work, the real-time clock is the standard source. It runs from a low-speed oscillator in the backup domain, which stays powered in the deepest modes, and it can raise a wake-up on a timer or an alarm. On an STM32F4 the alarm wakes the chip from Stop through EXTI line 17, which the HAL arranges when you set the alarm with interrupt:
RTC_AlarmTypeDef a = {0};
a.AlarmTime.Seconds = 0;
a.AlarmMask = RTC_ALARMMASK_DATEWEEKDAY | RTC_ALARMMASK_HOURS | RTC_ALARMMASK_MINUTES;
a.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
a.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
a.AlarmDateWeekDay = 1;
a.Alarm = RTC_ALARM_A;
HAL_RTC_SetAlarm_IT(&hrtc, &a, RTC_FORMAT_BIN);With all fields but the seconds masked, the alarm matches once per minute. The post on entering Stop and waking on an RTC alarm builds the full sequence. For event-driven devices, a GPIO edge from a button or a sensor's interrupt pin is the source, wired through EXTI. Choose the wake-up source before choosing the sleep depth, because it limits the depth: a source that only works in Sleep means the chip cannot go to Stop.
Step five: handle what the deeper modes take away
Stop and Standby switch off clocks and, in Standby, the whole core domain. After waking, the program has to put back what the mode removed.
Leaving Stop on an STM32F4, the system clock is the 16 MHz internal oscillator, and the HSE crystal and the PLL are off. Every peripheral whose timing depends on the system clock, such as a UART baud divider, is now wrong. The standard practice is to run the clock configuration again after the wake-up:
void sleep_until_alarm(void)
{
HAL_SuspendTick(); // no tick wake-ups
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
SystemClock_Config(); // HSE and PLL are off after Stop
HAL_ResumeTick();
}Leaving Standby, the chip resets, and the program starts at the reset vector with RAM empty. It must tell a wake-up from a power-on by reading the standby flag, and restore the state it needs from the backup registers or the backup SRAM:
int woke_from_standby(void)
{
RCC->APB1ENR |= RCC_APB1ENR_PWREN;
if (PWR->CSR & PWR_CSR_SBF) {
PWR->CR |= PWR_CR_CSBF; // clear the flag so the next boot reports correctly
return 1;
}
return 0;
}Less obvious is what happens to the peripherals. Stop keeps the register contents, so a UART does not need to be reconfigured, only re-clocked. Standby loses everything outside the backup domain, so every driver starts again, and the time that takes counts as part of the active phase. A sensor that took 50 ms to initialise on a cold boot takes 50 ms after every Standby wake-up, so a wake-up that happens once a second pays it once a second. That cost is what makes Stop better than Standby for short periods, and the post comparing the two gives the break-even arithmetic.
Step six: structure the firmware around sleeping
The way you organise the program decides how easy it is to sleep. Two structures work well.
The superloop with a sleep at the bottom. Handlers set flags or fill buffers, the main loop processes them and then sleeps with the guarded WFI. This suits most designs and is easy to reason about. The risk is a handler that wakes the chip more often than needed, such as a free-running timer interrupt at 1 kHz.
Interrupt-only firmware. When all the work can be done in handlers, there is no main loop, and the chip can go to sleep whenever the last handler returns. The Cortex-M has a bit for this, SLEEPONEXIT in the System Control Register, which makes the core sleep instead of returning to thread mode:
int main(void)
{
board_init();
SCB->SCR |= SCB_SCR_SLEEPONEXIT_Msk;
__WFI();
for (;;) { } // never reached while the bit is set
}The firmware then lives entirely in handlers, and the post on SLEEPONEXIT explains the design rules and where it does not fit, notably with an RTOS.
In an RTOS, the equivalent is tickless idle. The kernel normally wakes every tick, 1 ms for a 1 kHz tick, which prevents deep sleep. In tickless mode, when the idle task runs, the kernel computes the time to the next scheduled event, programs a low-power timer for that moment, stops the tick and enters the low-power mode, then adds the slept time to the tick count on wake-up. FreeRTOS exposes it as configUSE_TICKLESS_IDLE, and Zephyr has its own power management subsystem. The RTOS posts in this series cover it.
Step seven: measure
A claim about current is not credible without a measurement. The tool is a power profiler or a source-measure unit placed in series with the supply, and what it shows is the current over time, from which you can read the sleep level, the active bursts and how often they occur. Before measuring, remove everything on the board that is not part of the system under test: the debugger's supply path, the power LED, the USB bridge. A development board can easily draw more in its support circuitry than the microcontroller does in sleep.
The method that works is to mark the phases of the firmware with GPIO pins and record the pins together with the current. The firmware sets one pin high while awake and low while asleep, and a second pin high during a radio transmission. The capture then shows which part of the trace is which phase, and a short script can compute the average per phase from the exported data. The post on measuring microamp sleep current gives the whole procedure with a script.
Things that make a measurement lie are worth knowing:
A debug probe attached to a powered target can supply current through the protection diodes of the SWD pins, which changes the reading.
The first milliseconds after a large current step show glitches from the instrument's range switching.
Sleep currents drift as capacitors settle and the part warms, so wait before reading.
A measurement taken with markers enabled includes the markers' own small current.
A multimeter averages and cannot show bursts, so use it only to confirm a steady sleep level.
Step eight: turn current into battery life
The calculation takes the profile, which lists each state with its current and duration. Multiply to get the charge per phase, sum for the cycle, divide by the cycle time for the average current, and divide the battery's usable capacity by it. A worked example makes the method concrete.
A node wakes once a minute: 1 ms to start up at 2 mA, 5 ms measuring at 3 mA, 8 ms transmitting at 9 mA and 6 ms processing at 4 mA, then sleeps for the remaining 59.98 s at 3 microamps. In microcoulombs, the phases consume 2, 15, 72 and 24 for the active ones and 179.94 for sleep, a total of 292.94 per minute, and an average current of 4.88 microamps. The sleep takes 61 percent of the charge and the radio 25 percent. Halving the sleep current would save about 31 percent of the total, and halving the radio on-time about 12 percent.
The battery side needs care. A CR2032's rated capacity of about 225 mAh is measured under gentle conditions. The usable capacity at your pulse current, cut-off voltage and temperature is lower, so take it from the discharge curves in the cell's datasheet, and add the cell's self-discharge as an equivalent constant current. With 70 percent usable capacity and 1 percent per year self-discharge, the example runs for about 3.5 years, against 5.3 from the naive division. The dedicated post on budgeting battery life covers the arithmetic, the margins to apply, and how to check that the radio pulse does not pull a worn cell below the minimum voltage.
Make the active phase cheap
The awake time is short, but it is where the largest currents live, so it repays attention. Four habits shorten it or lower its current.
Do the work in one burst. Waking the chip costs energy: oscillators start, the regulator settles, caches fill. Doing one task per wake-up pays that overhead each time, and batching several tasks into one wake-up pays it once. A sensor that samples every second but reports every minute should sample from the wake-up, store the samples, and send them together, with the radio switched on once.
Power peripherals only while they work. An ADC, a sensor and a radio each have an on-state current. Enable the clock, do the conversion, disable the clock, as in the logger above. External sensors often have a shutdown pin or a supply that a GPIO can switch, and the time they need to settle after power-up counts as active time, so choose sensors whose start-up is short.
Let DMA and peripherals do the waiting. A polled transfer keeps the core running while the bytes move. A DMA transfer lets the core sleep, and the chip wakes only at the end. For anything longer than a few bytes, hand the transfer to DMA and execute WFI while it runs. The post on polling, interrupts and DMA works through the arithmetic that decides when each pays.
Minimise radio on-time. In a wireless device the radio is the biggest consumer by far, so everything that shortens its on-time matters most: a smaller payload, a faster data rate where range allows, fewer retries, and connection parameters that let it sleep between events. Count retries in the budget, since a transmission that fails and repeats doubles its share of the charge.
What the clock choice costs in sleep
The clock source decides the sleep floor as much as the mode does. A high-speed crystal oscillator draws current while running and takes time to start, which is why Stop modes switch it off and wake on an internal RC oscillator that starts in microseconds. The real-time clock runs from a low-speed source, either an internal RC or a 32.768 kHz crystal. The internal source is free and inaccurate, the crystal costs a part and a small current and keeps good time. If the device must keep wall-clock time across long sleeps, or wake on a schedule precise to a second per day, use the crystal. If it only needs to wake roughly once a minute, the RC is enough.
Be aware of how the chip restarts its clocks. After Stop, an STM32F4 runs from the internal 16 MHz oscillator until your code switches back to the crystal and PLL, and waiting for those to lock is active time. A design that wakes briefly to do a few microseconds of work can stay on the internal oscillator for the whole active phase and skip the restore, which saves both time and energy. The post on a low-power manager shows how to snapshot and restore the clock state when a restore is needed.
An RTOS and low power
An operating system's periodic tick prevents deep sleep, because the chip wakes for it. A 1 kHz tick wakes the core a thousand times a second, each wake-up costing a few microseconds of active current, which adds a steady floor to the average. The fix is tickless idle: when only the idle task is ready, the kernel works out when the next timeout expires, stops the tick, programs a timer that keeps running in the chosen sleep mode, and sleeps until then. On waking it corrects the tick count for the time slept.
In FreeRTOS this is configUSE_TICKLESS_IDLE, with the port providing vPortSuppressTicksAndSleep and the macros configPRE_SLEEP_PROCESSING and configPOST_SLEEP_PROCESSING as hooks for your own sleep-entry code. The application must make sure the timer used for the wake-up works in the sleep mode it chooses, which on STM32 usually means the RTC wake-up timer or a low-power timer instead of SysTick, since SysTick stops in the deeper modes. Zephyr has a power management subsystem with named power states, and the kernel enters them through the idle thread and policy callbacks. In both cases the rules from this guide still hold: pins have to be set, peripherals have to be gated, and the sleep current has to be measured.
An RTOS also changes how work is expressed. Instead of a flag and a loop, a task blocks on a queue or a semaphore with a long timeout, and the kernel sleeps when all tasks are blocked. A task that polls, or that wakes every few milliseconds for no reason, defeats the sleep, so audit the periods of timers and delays across all tasks. A software timer with a one-second period that nobody needs keeps the chip waking every second.
Testing the sleep path
Sleep code fails in ways that ordinary testing does not reach, so test it deliberately.
Wake from every source you rely on, in every mode you use. A source that works from Sleep may not work from Stop, and the failure is silent: the device sleeps and never wakes. Test with the real wiring, since a wake pin with a floating line wakes at random.
Test the wake-up at the edges of the timing. Trigger the wake-up event immediately before entering sleep, to prove the guard against the lost wake-up works. Trigger it during the entry. Trigger two events close together.
Test the restore. After a wake from Stop, check that the system clock is what you expect by reading the clock source status and by toggling a pin in a loop of known length. After a wake from Standby, check that the restored state is the saved state, and that a cold boot with garbage in the backup memory is detected.
Test over a long run. A device that sleeps and wakes a thousand times may leak memory in a driver, lose a flag, or drift in the RTC. Leave it running for a day with a logger watching the current and the wake-up count.
Test at temperature extremes if the product will see them. Sleep current rises with temperature, the internal RC oscillators drift, and a coin cell's capacity and internal resistance change, so a design that passes on a bench at room temperature can fail in a freezer or a hot cab.
When it does not work: a diagnosis table
| Symptom | Likely causes |
|---|---|
| Sleep current far above the datasheet | Floating or fought pins, debugger path, regulator quiescent current, a peripheral clock left on |
| The chip wakes immediately after entering sleep | A pending interrupt or an uncleared wake-up flag, a SysTick that is still running |
| It never wakes | The wake source does not work in this mode, the NVIC vector is not enabled, a pin is held at the wake level |
| Garbled output after waking from Stop | The UART baud divider was computed for the old clock, or the line was cut mid-byte |
| The debugger disconnects at the first sleep | The debug clocks stop in low-power modes, so set the DBGMCU bits in debug builds |
| Battery life half of the calculation | Capacity derated, retries not counted, self-discharge and cold not included |
| Works on the bench, fails in the field | Temperature, a weaker cell, an antenna in a different environment, retries |
| Random resets in sleep | A watchdog with a timeout shorter than the sleep, or brown-out on the pulse |
The first two rows account for most of the cases. Start with them, with a profiler on the board, before reading any code.
A complete example: a one-minute logger on an STM32L476
The pieces combine into a small program. The target is a NUCLEO-L476RG, an STM32 with a low-power regulator and the Stop 2 mode, whose current is among the lowest of the family. The program wakes once a minute from the RTC wake-up timer, reads the internal temperature sensor, prints a line and sleeps again. It uses STM32CubeL4 HAL 1.18 with the code generated for the clock, UART and RTC set up in the usual way.
The first part is a clean start: classify the boot, set the pins, and configure the wake-up timer.
#include "stm32l4xx_hal.h"
#include <stdio.h>
extern RTC_HandleTypeDef hrtc;
extern UART_HandleTypeDef huart2;
extern ADC_HandleTypeDef hadc1;
static volatile uint8_t woke;
void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *h)
{
(void)h;
woke = 1;
}
void RTC_WKUP_IRQHandler(void)
{
HAL_RTCEx_WakeUpTimerIRQHandler(&hrtc);
}
static void wakeup_timer_start(uint32_t seconds)
{
HAL_RTCEx_DeactivateWakeUpTimer(&hrtc);
HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, seconds - 1u, RTC_WAKEUPCLOCK_CK_SPRE_16BITS);
}With the one-hertz CK_SPRE clock source, the counter value is the number of seconds minus one, so 59 gives 60 seconds. The next part reads the temperature and prints it, then keeps the active phase as short as possible: power the peripherals only while they are needed.
static int32_t read_temperature_centi(void)
{
__HAL_RCC_ADC_CLK_ENABLE();
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 10);
uint32_t raw = HAL_ADC_GetValue(&hadc1);
HAL_ADC_Stop(&hadc1);
__HAL_RCC_ADC_CLK_DISABLE();
// simple linear conversion of the internal sensor; see the datasheet for the calibration points
return (int32_t)(raw * 10 / 41);
}
static void report(uint32_t n, int32_t temp_centi)
{
char line[48];
int len = snprintf(line, sizeof line, "sample %lu: %ld.%02ld C\r\n",
(unsigned long)n, (long)(temp_centi / 100), (long)(temp_centi % 100));
HAL_UART_Transmit(&huart2, (uint8_t *)line, (uint16_t)len, 100);
}The conversion in read_temperature_centi is a placeholder for the device's two-point calibration, which the datasheet and the factory calibration values in system memory describe, so a real program replaces it. What matters here is the structure: enable the ADC clock, convert, stop, disable the clock.
The last part is the loop. It sleeps in Stop 2, which on the STM32L4 keeps the RAM and registers with a very low current, and restores the clock after waking:
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_RTC_Init();
MX_ADC1_Init();
wakeup_timer_start(60);
uint32_t n = 0;
for (;;) {
report(++n, read_temperature_centi());
// wait for the UART to finish before its clock stops
while (__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TC) == RESET) { }
woke = 0;
HAL_SuspendTick();
HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI);
SystemClock_Config(); // the clock restarts from MSI after Stop
HAL_ResumeTick();
}
}sample 1: 24.37 C
sample 2: 24.41 C
sample 3: 24.40 C
(one line per minute)The temperatures are example values. The loop has no flag test before sleeping, since nothing else can wake it except the timer, so the race from the earlier sections does not arise; a design that had several wake-up sources would use the guarded form. Waiting for the UART's transmission-complete flag before sleeping is a detail that costs people hours: if Stop begins while a byte is still shifting out, the clock stops mid-byte and the last characters of the line are lost or garbled.
Now check the program against the guide's steps. The CPU sleeps whenever there is nothing to do. The active phase is short, and it powers the ADC only while converting. The pins that the board does not use would be set to analog in MX_GPIO_Init and, on the Nucleo board, the ST-LINK part of the board must be isolated for a meaningful measurement. The wake-up source is the RTC, which works in Stop 2. The clock is restored after the wake-up. A measurement with a profiler, with the debugger's DBGMCU bits left clear, would show a flat sleep trace with one short burst a minute, and the budget arithmetic above would turn it into a battery life.
The same ideas on other chips
The structure transfers, with different names and registers.
| Family | Shallow sleep | Deep sleep | Deepest | Wake-up in the deepest |
|---|---|---|---|---|
| STM32 | Sleep (WFI) | Stop | Standby, Shutdown | WKUP pins, RTC, reset |
| ESP32 | Light sleep | Deep sleep | Same, with the ULP coprocessor running | Timer, ext0, ext1, touch, ULP |
| RP2040 | WFI with clock gating | Sleep clocks | Dormant | GPIO edge or level |
| AVR | Idle | Power-save, Power-down | Power-down | Pin change, INT0 and INT1, watchdog, TWI |
| nRF52 | System ON idle | System ON with low-power clocks | System OFF | GPIO sense, reset, NFC field, LPCOMP |
On an ESP32, deep sleep is a reboot, with only the RTC memory surviving, so persistent state goes in RTC_DATA_ATTR variables, and the ULP coprocessor can run while the main cores are off. On an RP2040, the clock gating registers choose which blocks are clocked during sleep, and dormant mode stops the crystal, leaving only a GPIO edge to wake the chip. On an AVR, set_sleep_mode(SLEEP_MODE_PWR_DOWN) with the sequence cli(); if (!flag) { sleep_enable(); sei(); sleep_cpu(); sleep_disable(); } sei(); is the safe form. On an nRF52, the DC-DC regulator lowers the active and radio current for a coin cell if the board carries the inductor, and the System OFF mode is the deepest. Each of these has a post in this series.
A checklist before shipping
Run through this list on every low-power design.
The profile is written down, with a current and a duration for each state, and the average and the share per phase are computed.
The sleep current was measured on the real board with the debugger disconnected, and it matches the datasheet to within a reasoned margin.
Every pin has a deliberate state in sleep, and no pull resistor fights a driver.
Every peripheral clock that the firmware does not use is off, and every peripheral that is used is off outside its active window.
The wake-up source works in the chosen mode, and the clock and state restoration after wake-up is tested, including a wake-up from a cold start of the oscillator.
The firmware cannot sleep through an event: the flag check and the sleep are atomic.
The
DBGMCUdebug-in-sleep bits and any freeze bits are off in the release build.The battery budget uses usable capacity, includes self-discharge and has a margin, and the radio pulse was checked against the cell's internal resistance at end of life and low temperature.
The watchdog configuration still works with the sleep pattern: a watchdog that runs in Stop mode must be fed or have a timeout longer than the sleep.
Where low power is not the goal
Low-power design adds complexity, and it is not always worth it. A mains-powered device gains nothing from a Standby mode that complicates start-up. A device that is always busy has no sleep to optimise. And a prototype that has to work next week should run at full speed with the simplest code and move to lower power once the function is right. The skill is knowing when the battery budget actually constrains the product, and then spending effort in the order the energy model dictates: sleep current first, wake-up cost and active duty cycle second, and the micro-optimisation of instructions last.


