A coin cell lasts 98 days at 100 µA of sleep current and 2.7 years at 10 µA. A faster CPU cannot fix that: below 1% duty, the sleep floor is the whole budget.
Drag Sleep current down from 100 to 10 µA and watch the lifetime roll. Then press Debugger attached and watch the floor jump. Then we build, piece by piece, where power goes, how a chip sleeps, how radios and sensors wake it, and how to measure it.
You need Ohm’s law (current is voltage over resistance) and a first look at what happens between reset and main(). We build the rest from zero.
Built from primary sources: the STM32L476 datasheet, the nRF52840 product specification, the ESP32-C6 datasheet, the Nordic PPK2 guide, the Linux kernel power documentation and the Zephyr power docs. The Field Guide lists each with what we checked.
The 235 mAh cell capacity is a typical light-load figure and the AA and 18650 values are mid-range typical values: real capacity falls with load and cold (Chapter 8). Self-discharge is ignored. The debugger adds an illustrative 350 µA to the floor: the real number depends on the part and the probe settings. The bursts are drawn wider than their true length so you can see them. The lifetime is computed live: capacity divided by average current.
Chapter 0
Turn a coin cell into a number of days, and find out why the part that sleeps decides the answer
You build a soil sensor. It wakes once every ten seconds, reads a probe, sends a short radio message and goes back to sleep. The datasheet says the chip sleeps at 2 µA. You power it from a coin cell and plan for a three year life.
Four months later the sensors in the field go dead. You bring one back to the bench and measure it. It draws 20 µA while asleep, ten times the datasheet. Nothing is broken. Something small is leaking, and over a hundred days a small leak adds up to the whole battery.
A battery stores a fixed amount of charge. We count that charge in milliamp hours (mAh): a cell rated 235 mAh can supply 235 mA for one hour, or 1 mA for 235 hours, or 0.1 mA for 2,350 hours. Current is the rate the bucket drains. Divide the bucket by the rate and you have the time until it is empty.
The current is not constant. A firmware part spends almost all its time asleep at a tiny current and a little time awake at a big one. So we need the average current: the steady current that would drain the same charge over the same time. It is a weighted mean, and the weights are the fractions of time spent in each state.
Now the numbers from the hero at the top of the page. The cell is a CR2032 and we use 235 mAh as a typical light-load capacity. Sleep is 100 µA. First, ignore the bursts and look only at the floor.
235 mAh ÷ 0.100 mA = 2,350 h = 97.9 days | 235 mAh ÷ 0.010 mA = 23,500 h = 2.68 years
Cutting the floor tenfold stretched the life from 98 days to 2.7 years. Now add the bursts. The part wakes for 5 ms every 10 s at 8 mA, so d = 0.005 s ÷ 10 s = 0.0005, or 0.05%. The bursts add 8,000 µA × 0.0005 = 4.0 µA to the average.
100 µA floor: 99.95 + 4.0 = 103.95 µA, so 235,000 ÷ 103.95 = 2,261 h = 94 days
10 µA floor: 9.995 + 4.0 = 13.995 µA, so 235,000 ÷ 13.995 = 16,792 h = 1.9 years
The bursts cost 4 µA in both cases. With a 100 µA floor they are a rounding error. With a 10 µA floor they are 29% of the budget, and they start to matter. That is the shape of the whole lesson.
The bursts equal the floor when Iactive × d = Isleep. Solve for d: d = Isleep / Iactive. With a 100 µA floor and an 8 mA burst, that is 100 / 8,000 = 1.25%. Below about 1% duty, the floor is more than half of the average. With a 10 µA floor the crossover is 0.125%.
So a faster CPU does not help here. Finish the 5 ms job in 2.5 ms and you save 2 µA of 104. Cut the floor from 100 to 10 µA and you save 90. Below about 1% duty, effort belongs on the floor. The bursts get their turn in Chapters 1 and 2.
The chip should sleep at 2.0 µA. It draws far more. Switch each suspect off, one at a time, and watch the floor fall. Start with the debugger.
Illustrative values, not a datasheet. The chip and its sensor sum to 2.0 µA (the STM32L476 Stop 2 figure with the clock running is 1.4 µA, and we add 0.6 µA for a sensor). The pull-up is Ohm’s law: 3.0 V across 330 kΩ is 9.1 µA. The floating input (3.1 µA), the UART clock (5.8 µA) and the debugger (350 µA) are round example values; yours differ.
Every suspect in the device is a real family of bugs. A floating input is a pin that nothing drives: it drifts to the middle of the supply range, and the input circuit leaks while it does. A pull-up is a resistor from a pin to the supply. If something pulls that pin low while you sleep, current flows through the resistor all the time. A peripheral clock that stays enabled keeps its block switching.
Symptom: the unit draws ten times the datasheet sleep current. Measurement: first detach the debugger and power cycle, because a connected probe can keep clocks running and hold the floor high. Then measure the floor with a tool that can read microamps (Chapter 7). Fix: strip the board one part at a time. Disable one peripheral, re-measure, and watch for the step down. Look for the floating input, the driven pull-up and the UART left on.
On real hardware. Take an STM32 Nucleo-L476RG or an nRF52840 DK. Put the board in its deepest sleep, power it through a profiler, and record the floor with the debugger attached and again after you detach it and power cycle. Compare both to the datasheet.
The device above is that hunt in miniature. The debugger hid everything else under 350 µA. Once it was off, three small leaks of 3.1, 9.1 and 5.8 µA remained. Their sum is the missing 18 µA.
The hero has four knobs and a switch. Each part of the lesson explains one of them.
Chapter 1
Split a chip’s power into the part that switches and the part that leaks, and find the one lever that moves both
You want to save battery, so you halve the clock of a busy processor. The code now takes twice as long. You expected half the energy. You measure and find the battery drains almost as fast as before. Sometimes it drains faster.
The reason sits inside the chip. Power has two sources, and a slower clock only helps one of them, and only a little. To see why, we need the picture of a single switch.
A digital chip is billions of tiny switches called transistors. Each switch drives a wire, and a wire behaves like a small bucket for charge. We call that bucket a capacitor. Flipping a signal from 0 to 1 fills the bucket from the supply. Flipping it back empties the bucket to ground.
Filling a capacitor C from a supply V draws a charge C × V from the supply, and the supply gives it at V. That is an energy of C × V². Half of it is stored in the wire. The other half is lost as heat on the way. Emptying the wire turns the stored half into heat too. So each full fill and empty costs about C V² of energy, all of it ending as heat.
Not every wire flips on every clock tick. The activity factor a is the fraction of the total capacitance that flips in one cycle. Multiply the energy per cycle by the number of cycles per second f and you have power.
Put in a worked number. Take a = 0.1, C = 10 nF, V = 1 V, f = 1 GHz. Then Pdyn = 0.1 × 10−8 F × 1² V × 109 Hz = 1 W.
Now lower the voltage to 0.5 V. A transistor needs time to charge a wire, and with less voltage it charges slower, so the clock must slow as well. In the simplest model f falls in proportion to V, so f becomes 0.5 GHz.
0.1 × 10−8 × 0.5² × 0.5 × 109 = 0.125 W (one eighth of 1 W)
Half the voltage and half the clock gave one eighth of the power. The voltage counts twice: once squared in the energy per switch, and once through the lower clock it forces. The Linux kernel’s energy model uses the same shape: its simple registration path computes power as C × V² × f.
Power is a rate. A battery cares about energy, and a task has a fixed amount of work. Say the task takes N clock cycles. At frequency f it takes t = N / f seconds. Multiply power by time.
The dynamic part is a C V² f × N / f = a C V² N. The frequency cancels. A slower clock alone does not reduce the energy a task burns in its switches. It only spreads that energy over more time. The leakage part is V × Ileak × N / f, and it grows as f falls, because the chip leaks for longer.
So there are two ways to slow down. If you only lower f and keep V, dynamic energy stays the same and leakage energy rises. The task costs more. If you lower V as well, dynamic energy falls with V². Leakage energy still rises with the longer time, so there is a best voltage in the middle. Try it.
The curve is the energy of one task of one billion cycles. Drag the voltage. Then switch to Clock only, where the voltage stays at 1.0 V, and drag again.
Illustrative model, not a real chip: a = 0.1, C = 10 nF, a threshold voltage of 0.3 V, the clock set by f = 1 GHz × (V − 0.3) / 0.7, and a leakage current of 150 mA. The energy is computed live as a C V² N + V Ileak N / f for N = 109 cycles.
In the model the cheapest point is near 0.5 V and 286 MHz. There the task takes 3.5 s and burns 0.51 J, against 1.15 J at full speed. Go lower and leakage takes over: at 0.4 V the task costs 0.58 J. The cheapest speed is not the slowest speed.
Symptom: you halve the clock and the battery lasts no longer. Measurement: do not read power. Integrate the current over the whole task, including the time spent waiting, at each setting. Energy per task is the number that counts. Fix: change the clock only together with the voltage, using the operating points the vendor gives you.
On real hardware. Take an STM32 Nucleo-L476RG and put a current meter in the board’s IDD jumper path (see the board user manual). Run a fixed loop of one million iterations at 4, 16 and 80 MHz with the same regulator range, and integrate the charge. The datasheet quotes about 100 µA per MHz in run mode with the LDO, so the current should fall in proportion to the clock while the charge per task stays about equal. Then lower the core voltage range and measure again.
c/* STM32L4 HAL: lower the core voltage first, then the clock (the order matters). */ void go_slow_and_low(void) { __HAL_RCC_PWR_CLK_ENABLE(); HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE2); // lower core voltage range /* ...then switch SYSCLK to a slower source and set flash latency for that range */ }
Chapter 2
Decide how long each burst should last, and learn which number in the datasheet makes the decision
Your firmware has a job every 100 ms: filter a block of sensor samples. The job needs 400,000 clock cycles. You can run it fast and sleep a long time. You can run it slowly and sleep a short time. Both finish before the next block arrives. Which one empties the battery slower?
Two schools disagree. Race to idle says: finish as fast as you can, then drop into the deepest sleep. Dynamic voltage and frequency scaling (DVFS) says: run only as fast as the deadline needs, at the lowest voltage that speed allows. The answer comes from arithmetic on three numbers.
The STM32L476 datasheet quotes about 100 µA per MHz in run mode when the core runs from its internal regulator. At 80 MHz that is 100 × 80 = 8,000 µA, or 8 mA. At 8 MHz it is 0.8 mA. This is the same C V² f shape from Chapter 1: the current grows in proportion to the clock.
The chip also pays a fixed price for being awake that does not shrink with the clock: the regulator, the flash and the clock sources. We call this the awake overhead I0. The datasheet figure per MHz hides it, so we add it back as a separate term.
Use charge instead of energy, because the supply voltage is constant. For one period T the part runs for t = N / f and idles for the rest.
Expand the brackets. The k f s term times N / f leaves k s N, with no f in it. So Q = k s N + Iidle T + (I0 − Iidle) N / f. Read the last term. If the awake overhead I0 is bigger than the idle current, then Q falls as f rises. Fast wins. If idle is not cheaper than awake overhead, slow wins. Voltage changes the first term: a lower voltage lowers s, and that favours the slow, low-voltage point.
Worked example with N = 400,000, T = 100 ms, k = 100 µA per MHz, I0 = 300 µA and a deep idle of 1.1 µA. At 80 MHz the job takes 5 ms at 8.3 mA, so the run part is 41.5 µC and the idle part is 0.1 µC: 41.6 µC in all. Drop to 26 MHz at a lower voltage (s = 0.69, an illustrative value): the job takes 15.4 ms at 2.1 mA, so 32.2 µC plus 0.1 µC of idle: 32.3 µC. The middle point wins by 22%.
Now make idle shallow. Suppose the part only waits in a light sleep that draws 1 mA. The idle terms become 95 µC at 80 MHz, 84.6 µC at 26 MHz and 50 µC at 8 MHz. The totals are 136.5, 116.8 and 92.6 µC. Slow now wins, because the long idle is the expensive part and the slow run shortens it. The depth of sleep decides who wins.
Each bar is the charge drawn in one 100 ms period: warm is the job, teal is the wait. Drag the idle current from deep sleep up to a shallow wait. Then switch the voltage drop off.
Illustrative model on the L476 shape: 100 µA per MHz at the high voltage, an awake overhead of 300 µA, a job of 400,000 cycles every 100 ms, and a voltage factor of 0.69 at the two low clocks when the toggle is on (the real low-voltage range and its limits are in the datasheet). The charge is computed live from the equation above.
Vendors do not let you pick any voltage and clock you like. They publish a table of operating performance points (OPPs): the allowed pairs of voltage and frequency, each tested to work. The kernel’s cpufreq code reads that table, and the Chapter 1 curve is drawn only at those points. So the practical question is never “what is the best clock?” but “which listed point has the lowest charge for this job and this deadline?” Write the charge for each row of the table, using the equation above, and pick the lowest that still meets the deadline.
The same trade-off appears in Linux as cpufreq governors. The performance governor pins the top clock. The schedutil governor follows the scheduler’s load. Symptom: a board in a closed box runs hot and slows down after ten minutes. Measurement: read the clock and the temperature over time. You see the clock fall when the chip reaches its limit. Fix: let the governor follow the load, and size the heat path for the average power, not the peak. Chapter 6 returns to this on bigger boards, and the edge-device thermal limits get their own lesson.
On real hardware. On an STM32 Nucleo-L476RG, run the 400,000 cycle job once per 100 ms at 80 MHz and again at the lowest clock that meets the deadline. Put a current profiler on the supply and integrate a whole minute at each setting. Compare the averages to the model and note which idle mode you used between jobs.
Chapter 3
Climb down the ladder of sleep depth, and learn what each rung throws away and what wakes it up
A button sits on your board. The firmware must notice a press, but presses are rare. The simplest code is while (!pressed) {}. The core runs flat out, executing the same few instructions, and the battery drains at the full run current. You need the chip to stop doing anything until the button moves.
Every microcontroller offers this. The more it switches off, the less it draws and the more it forgets. So sleep modes are a ladder. Each rung down saves current, loses some state and takes longer to climb back up.
On an Arm Cortex-M part, the instruction WFI means wait for interrupt. The core stops its clock until any enabled interrupt arrives, then runs the interrupt handler. A related instruction, WFE, waits for an event instead. A bit in the System Control Register, called SLEEPDEEP, tells the chip to go further than a plain core stop and enter the vendor’s deeper modes. What those modes do is up to the vendor, so each chip has its own table.
A wake source is the signal that ends the sleep: a pin edge, a timer, the real-time clock alarm, a radio event or a serial byte. A deep mode can only be woken by sources that stay powered. That is the second thing the ladder trades away.
The STM32L476 datasheet gives these currents. Stop 2 draws 1.1 µA, or 1.4 µA with the real-time clock running. The core, the registers and the main memory keep their contents, and the program continues after the sleep instruction. Standby draws 120 nA, or 420 nA with the clock. Most memory is lost, and waking works like a reset, so the firmware starts again at the reset vector. Shutdown draws 30 nA and wakes only from the wakeup pins, the real-time clock or a reset. The reference manual (RM0351) has the exact lists of what each mode keeps, and you should read it for your part before you design around it.
The Nordic nRF52840 has a similar pair. In System ON with no memory retained and the real-time clock waking it, the product specification gives 1.5 µA at 3 V. In System OFF it gives 0.4 µA. System OFF also wakes through a reset. The ratio is 3.75: the same trade of depth for a harder restart.
A deeper rung saves current but costs a bigger wake. Standby restarts the firmware: it re-enables clocks, restores peripherals and reads saved state from the memory that survived. Say that takes 3 ms at 3 mA, which is 9 µC each wake (an illustrative figure; measure yours). A Stop 2 wake costs a few microseconds of run current, say 0.05 µC.
Compare the averages for a wake every T seconds, both with the clock running. Stop 2 gives 1.4 µA + 0.05 µC / T. Standby gives 0.42 µA + 9 µC / T. They are equal when 0.98 µA = 8.95 µC / T, so T = 9.1 s. Wake more often than every 9 seconds and Stop 2 uses less. Wake less often and Standby wins. The break-even is the extra wake charge divided by the current saved.
Top: the four modes, current on a log scale. Bottom: average current against the wake period. Drag the period across 9 seconds. Then switch on the 1 kHz tick.
The four currents are the STM32L476 datasheet figures (run is 100 µA per MHz at 80 MHz, Stop 2 and Standby are the “with RTC” values, Shutdown is 30 nA). The wake charges, 0.05 µC for Stop 2 and 9 µC for Standby, are illustrative. Wake latency also grows with depth: read it from your part’s datasheet.
Look at the ladder in the device. From run to Stop 2 is a factor of 5,700. From Stop 2 to Shutdown is a factor of 47. The big step is the first one, and it is nearly free: it keeps your state. Go deeper only when the period is long, as the chart shows.
Symptom: you call WFI in the idle loop, yet the measured floor is 50 µA, not 1.4. Measurement: capture the current at 100 kS/s or more and zoom in. You see a spike every millisecond. The RTOS tick, a timer interrupt (SysTick on Arm cores) that fires 1,000 times a second, wakes the core each time. At 0.05 µC per wake that adds 1,000 × 0.05 = 50 µA. Fix: use tickless idle: before sleeping, the kernel looks up the next timer deadline, programs a low-power timer for that moment and stops the tick. Zephyr and FreeRTOS both offer it. In Zephyr, the power-management policy also picks the deepest state whose minimum residency plus exit latency fits in the idle time, and a component can lock a state to keep it out.
On real hardware. On an STM32 Nucleo-L476RG, enter Stop 2 with an RTC wake every 5 s and every 20 s. Measure the average over three minutes each. Then repeat with Standby. You should see the crossover near the one the chart predicts, shifted by your real wake charge.
c/* STM32L4 HAL: sleep in Stop 2 until the RTC alarm, then restore the clock. */ HAL_SuspendTick(); // stop SysTick so it cannot wake us HAL_PWREx_EnterSTOP2Mode(PWR_STOPENTRY_WFI); // WFI with SLEEPDEEP set; RTC alarm wakes us SystemClock_Config(); // after Stop the clock restarts slow: set it again HAL_ResumeTick();
Chapter 4
Count the wake-ups a sensor causes, then cut them with a FIFO, a DMA transfer and a motion threshold
A fitness band carries an accelerometer. The accelerometer measures 100 times a second. The simple firmware wakes on every sample, reads six bytes over I²C and goes back to sleep. A hundred wake-ups each second. The chip never gets to rest, and the coin cell lasts weeks.
The sensor itself uses almost nothing. The cost is in the wake-ups. Each one has a fixed price, and you pay it 100 times a second. This chapter moves that price from every sample to every batch.
When the processor wakes, it restores its clock, re-enables the bus and starts a transaction. We call the charge for all that the wake overhead Qw. Then it reads the data. Each sample costs bus time at the bus current: the read charge Qs. The first price does not depend on how much you read. The second grows with every sample.
A FIFO (first in, first out queue) is a small buffer inside the sensor. The sensor writes each new sample into it by itself. You set a watermark: the fill level at which the sensor raises an interrupt. Now the processor wakes only when N samples wait, and reads all N in one burst. The output data rate (ODR) is how many samples per second the sensor makes. Lowering it is the other lever.
Take illustrative numbers. A wake costs 2 µC (250 µs at 8 mA). Reading six bytes over a 400 kHz I²C bus takes about 135 µs at 3 mA, which is 0.405 µC, plus 45 µs of address overhead per transaction. The sensor draws 15 µA at 100 Hz.
With N = 1: each wake costs 2 + 0.135 + 0.405 = 2.54 µC, a hundred times a second. That is 254 µA. Add 15 and 1.5 and the node averages 270.5 µA. A CR2032 at 235 mAh lasts 869 h, or 36 days.
With N = 32: the wakes fall to 100 / 32 = 3.125 per second. Each costs 2 + 0.135 + 32 × 0.405 = 15.1 µC. That is 47.2 µA, down from 254. Now the read cost is the biggest part. Let the DMA controller do the reading: direct memory access moves bytes from the bus into memory without the core. The core sleeps, and the bus current falls to, say, 0.6 mA, so a sample costs 0.081 µC. Now each wake costs 4.6 µC and the node averages 30.9 µA: 317 days.
The bar splits the average current. Raise the batch size from 1 to 128. Then switch on DMA. Then switch on wake on motion.
Illustrative model: 2 µC per wake, 135 µs of 3 mA per sample over I²C (or 0.6 mA with DMA), 45 µs of overhead per read, a sensor current of 0.15 µA per Hz, and a 1.5 µA floor from the nRF52840 specification. Wake on motion models 20 events an hour, a 3 µA sensor in threshold mode, and one 32-sample read per event. A CR2032 is taken as 235 mAh.
Choose the output rate from the signal, not from habit. A walking step is about two per second, so a rate of 25 Hz already gives more than ten samples per step. A rate of 400 Hz makes 16 times as many samples, wakes 16 times as often at the same batch size, and raises the sensor’s own current, all for detail the step counter never uses. Set the lowest rate that still captures the fastest motion you care about, and let the batch size decide how often you wake.
Wake on motion goes further. The sensor compares each sample with a threshold you set, and raises an interrupt only when the threshold is crossed. The sensor runs in a low-rate mode, say 3 µA, and the processor wakes 20 times an hour. The node then averages about 4.5 µA. The price: you only have data around events, not a continuous stream. That is the right trade for “did the box move?” and the wrong one for step counting.
Symptom: the node lasts weeks instead of a year, and the sensor is idle on the bench. Measurement: count the sensor interrupts per second. On a Linux board, the debugfs file /sys/kernel/debug/wakeup_sources lists each wake source with an event count, so a noisy one shows a count that climbs by hundreds a second. On a microcontroller, increment a counter in the interrupt handler and print it every minute. Fix: raise the motion threshold, add the sensor’s duration or debounce setting, and move from one interrupt per sample to one per FIFO watermark.
The FIFO details, including timestamps and how to avoid losing samples, are in FIFO, watermark and timestamps. The always-on version of the same idea is the always-on sensor hub.
On real hardware. On a micro:bit v2, which has an accelerometer, count the interrupts for one minute with the watermark at 1 and at 32. On an nRF52840 DK, put the power profiler on the supply and compare the two traces. You should see 100 spikes a second shrink to about 3.
Chapter 5
Turn a radio schedule into an average current, and see who really chooses how often your device wakes
Your sensor now talks to a phone over Bluetooth Low Energy. You set a connection interval of 20 ms because you want snappy updates. The coin cell, which you planned to last a year, is flat after a month. Nothing is leaking. The radio is simply listening 50 times a second.
A radio is the biggest burst on most small devices. Its schedule is the period T in the hero. This chapter shows the schedules of three radios and the arithmetic that turns each into microamps.
Two Bluetooth devices that are connected meet at fixed times. The meeting is a connection event: the central (often a phone) sends a packet, and the peripheral (your sensor) answers. The time between two events is the connection interval. The Bluetooth Core Specification (Vol 6, Part B) allows 7.5 ms up to 4.0 s, in steps of 1.25 ms. Zephyr’s default connection parameters (BT_LE_CONN_PARAM_DEFAULT) ask for 30 to 50 ms, with a 4 s supervision timeout.
The peripheral can also skip events. Peripheral latency is the number of events it may ignore when it has nothing to send. With latency L, it needs to listen only every (L + 1)th event. If it has data, it can still answer at the next event, so it reaches the phone quickly. The price is for data going the other way: the phone may wait up to (L + 1) intervals to be heard.
An illustrative event: 800 µs of start-up and turnaround, plus the packet. A 20 byte payload with about 10 bytes of overhead is 30 bytes, which is 240 µs at 1 Mbps. At an average of 6 mA that is 1,040 µs × 6 mA = 6.2 µC.
20 ms interval: 6.2 µC ÷ 0.020 s = 312 µA, so with the floor 313.7 µA, and 235 mAh lasts 31 days
1 s interval: 6.2 µC ÷ 1 s = 6.2 µA, so 7.7 µA, and 235 mAh lasts 3.5 years
A 50 times longer interval means 50 times less current. The device below does that sum for you. It also checks one rule from the specification: the supervision timeout, the time after which the link is declared dead, must be longer than twice (L + 1) intervals. With the 4 s timeout, that bounds the product (L + 1) × interval to under 2 s.
The trace shows current against time on a log scale: events are the spikes. Drag the interval from 20 ms to 1 s. Then raise the latency at a short interval.
Illustrative model, not the Nordic profiler: an event is 800 µs of start-up plus (payload + 10 bytes) at 1 Mbps, at 6 mA, with a 1.5 µA floor. The interval slider counts in units of 1.25 ms (6 to 3,200 units, which is 7.5 ms to 4.0 s as in the Core Specification); the supervision timeout is fixed at 4 s. A CR2032 is taken as 235 mAh. Measure your own radio to replace Qevent.
A Wi-Fi access point sends a beacon about every 102.4 ms (100 time units of 1.024 ms). A sleeping station wakes for beacons. The access point flags buffered multicast traffic in a DTIM beacon, sent every k-th beacon, so a station that wants multicast wakes every k × 102.4 ms: 307.2 ms for k = 3. Target wake time (TWT), added in Wi-Fi 6 (802.11ax), lets a station and the access point agree on private wake times, often seconds apart. The ESP32-C6 datasheet (v1.5) lists TWT support and a deep-sleep current of 7 µA, but TWT only helps if the access point negotiates it. Without it, the station falls back to waking on DTIM beacons.
Cellular IoT has two naps. Power saving mode (PSM) lets the device turn its radio off for hours or days between reports; the network cannot reach it in that time. Extended discontinuous reception (eDRX) keeps the device reachable but lets it listen for pages only every few seconds or minutes. The timer limits are set in the 3GPP standards and by the operator, so read them for your module and network before you budget.
Symptom: you ask for a 1 s interval in firmware, and the battery drains as if it were 30 ms. Measurement: a Bluetooth sniffer shows the interval actually in use. It is the one the central chose. As Nordic’s academy puts it, the central has the final say: the peripheral can only request an update, and a phone’s operating system decides. Fix: send a connection parameter update request with a wide acceptable range and a good latency. Then log the parameters you actually got, and budget with those.
On real hardware. Use an nRF52840 DK with a power profiler on the supply. Connect to a phone, and record 60 s at the interval you get. Ask for a longer interval and record again. The floor between spikes should match the 1.5 µA class of figure, and the spikes should thin out by the ratio of the intervals. The related coin-cell lesson is the coin cell year.
Chapter 6
Follow the same budget on a bigger board, where the kernel decides when each part sleeps
You move the sensor project onto a small Linux board. The board sits idle on the bench, yet it draws half a watt more than the vendor says it should. Nobody is using the camera, but the camera is powered. The code that opened it is long gone. Something still holds it awake.
On a microcontroller you chose each sleep state. On Linux the kernel chooses, and drivers vote. To find a stuck vote you need to know how the votes are counted.
Runtime power management (runtime PM) lets the kernel suspend one device while the rest of the system runs. Each device has a usage counter. Code that needs the device calls pm_runtime_get_sync(). The kernel’s documentation says it bumps the counter and resumes the device synchronously. Code that is done calls pm_runtime_put(). That drops the counter and asks for an idle check. When the counter reaches zero, the kernel idles or suspends the device.
One detail matters. The documentation notes that pm_runtime_get_sync() leaves the counter raised even when it returns an error, and recommends pm_runtime_resume_and_get() when you check the return value. Every get needs its put, on every path.
Autosuspend adds a grace period. Suspending and resuming a device costs time and energy, so with autosuspend the kernel waits a set delay after the counter hits zero before it suspends. User space can set it through power/autosuspend_delay_ms and can forbid runtime PM for a device by writing on to power/control (writing auto allows it again). The same sysfs directory also exposes runtime_status and runtime_usage, the two files you read to see the vote count (see the kernel ABI notes for your version).
Press get, then put, then Wait 1 s a few times and watch the device suspend. Then press Leaky get and wait. The device never sleeps.
A simulation of the rules in the kernel runtime PM documentation. The 450 mW awake and 5 mW suspended power figures are illustrative. A put at count zero is shown as an underflow, which the kernel reports as a warning.
The counter is a vote, not a flag. Two clients get; one puts; the device stays on. A path that gets and then returns early on an error, without the put, leaves the vote up forever. That is the leak in the story above.
The whole board has sleep states too. The kernel documents four. Suspend-to-idle (s2idle, written freeze to /sys/power/state) is software only: it freezes user space, quiets devices and waits for an interrupt. Standby also takes the non-boot CPUs offline. Suspend-to-RAM (deep) powers everything down but memory, which stays in self-refresh. Hibernation saves memory to storage and powers off. The file /sys/power/mem_sleep picks which variant the string mem means. Deeper states save more and wake slower.
Between those, each CPU also has idle states managed by cpuidle. Each state lists an exit latency (the worst delay from wake-up to the first instruction) and a target residency (the minimum time the CPU must stay for the state to beat a shallower one). Both are in microseconds under /sys/devices/system/cpu/cpu<N>/cpuidle/state<M>/.
The residency has a derivation. A shallow state draws Ps. A deep state draws Pd but costs an entry and exit energy Ex. Staying for time t, the deep state wins when Ex + Pd t < Ps t, so t > Ex / (Ps − Pd). With Ps = 300 mW, Pd = 20 mW and Ex = 2.8 mJ (illustrative), the target residency is 2.8 mJ ÷ 280 mW = 10 ms. A governor predicts the next idle time and picks the deepest state that fits. The documented ones are menu, teo and ladder.
Frequency is the same idea. The energy model gives the scheduler a table of power at each clock, and its simple form computes power as C × V² × f, the formula from Chapter 1. The scheduler can then place work on the cheapest core that meets the need.
Symptom: the board idles at half a watt over spec. Measurement: list devices and read power/runtime_status and power/runtime_usage. A device that is active with a usage of 1 and no user is leaking a vote. Fix: find the get without a put, usually on an error path, and balance it. If a whole-system suspend fails or aborts, the kernel’s pm_test levels can stop the sequence at a chosen stage, which shows which stage fails.
On real hardware. On any Linux board, read runtime_status for each I²C and USB device while idle, and note which are active. Then read cpuidle state usage counts before and after ten idle seconds. The real-time side of such boards is in real-time Linux, and the privilege model underneath is in the pipeline and privilege levels.
pm_runtime_get_sync() at the start of a read, and on a bus error it returns without calling pm_runtime_put(). What do you see after the error?Chapter 7
See what a slow meter misses, and learn how a shunt and a fast converter catch every microsecond
You put a multimeter in series with the battery of the node from the hero. It sleeps at 10 µA and wakes for 5 ms every 10 s at 8 mA. The meter reads 10 µA. You plan for a 2.7 year life. The units last 1.9 years, a third short. The meter did not lie on purpose. It simply never saw the bursts.
A measurement has two limits: how fast it samples, and how wide a range it covers. A bench meter is built for steady currents. Firmware current is not steady. It is a flat floor with brief spikes that are a thousand times taller.
A typical bench meter measures for a short integration window, perhaps 100 ms, shows the mean of that window, then repeats a few times a second. If a burst falls inside a window, the reading jumps. If it does not, the burst is invisible. The bursts here fill 5 ms of every 10 s, so only about 1 window in 100 contains one.
When a window does catch the burst, it shows the burst diluted by the window: 10 µA + 7,990 µA × (5 ms ÷ 100 ms) = 410 µA. A true average is 14.0 µA. The meter shows 10 most of the time, 410 occasionally, and 14 almost never. Neither number is the truth.
The fix is to turn current into voltage and sample fast. A shunt resistor is a small resistor in series with the supply. By Ohm’s law the voltage across it is V = I × R. An analogue to digital converter (ADC) measures that voltage many thousand times a second. Adding up the samples gives the charge, and the mean gives the average current.
Choosing R is a trade-off. A 10 Ω shunt carrying 8 mA drops 80 mV, which starves the device under test. The same shunt carrying 10 µA gives only 100 µV, which is tiny to resolve. The ratio between the largest and smallest current is 8,000, about 13 bits just to see 1 µA steps at 8 mA. A tool that must span from nanoamps to amps therefore switches between several shunts. The Nordic Power Profiler Kit II (PPK2) guide lists a measurement range of 500 nA to 1 A, accurate down to about 200 nA, at 100 kS/s with a resolution down to 0.2 µA. The full range is a ratio of millions.
100 kS/s means one sample every 10 µs. A 5 ms burst is then 500 samples, and a 50 µs radio ramp is 5 samples. In one minute that is 6 million samples, or about 24 MB if each takes 4 bytes (an assumed size). Fast tools hold that stream and give you the integral over any window you select.
The node sleeps at 10 µA and bursts at 8 mA for 5 ms. Choose an instrument and press Take 20 readings. Then change the period.
A model, with random timing in your browser. The multimeter averages over a 100 ms window at a random moment. The profiler reading is the mean of every 10 µs sample over a 60 s capture, with a small random error of one burst at most. The node is the hero’s example: 10 µA floor, 8 mA bursts of 5 ms. Meter windows differ between models.
Where you put the meter matters as much as which meter. Measure the whole path from the battery to the board, and cut any other supply. A board that is also plugged into a USB debugger can draw current through the debug lines, and the meter never sees it. That is one more reason the floor looks lower on the bench than in the field. Power the board from the profiler alone, with the debugger unplugged, and the number you read is the number the cell will see.
On a laptop or server there is often no shunt to reach. Intel CPUs expose RAPL counters. In Linux they appear under powercap as energy_uj, an energy counter in microjoules, with its range in max_energy_range_uj. The kernel page lists package, core and uncore zones, and notes that the interface gives no instant power: you compute power as the change in energy divided by the change in time. If you read twice before the counter has updated, the change is zero, and your power reads zero. Read less often, and handle the counter wrapping at its maximum range.
Many boards have power-monitor chips on their supply rails, read by tools such as tegrastats on NVIDIA Jetson boards. These are the same idea as a shunt, with a fixed, usually slower, sample rate. Treat them as an average over their window, and check their rate before you trust a spike.
Symptom: units die three to ten times sooner than the bench figure. Measurement: capture a long trace at 100 kS/s or better, and integrate it. Compare to the meter. Fix: budget from the integral. Keep the debugger off during the capture, as Chapter 0 showed.
On real hardware. Take an nRF52840 DK and a PPK2 in ampere meter mode. Capture 60 s of your node. Read the average, then zoom to a single burst and count the samples in it. Repeat with a bench meter in series and note what it shows.
Chapter 8
Learn why the 235 mAh on the label is a best case, and which part of the supply quietly takes its own share
Your node lasts fourteen months on the desk. You mount a copy outdoors in winter and it dies in six. The firmware is identical. The battery is the same make. Only the weather changed.
So far we treated the battery as a bucket with a fixed size. That was the first approximation. A real cell gives less when it is cold, less when you pull hard, and it fails earlier than its capacity suggests because its voltage sags.
The label gives a capacity in mAh, measured under stated conditions: a particular load, a temperature and a final voltage. Typical datasheet ranges are about 220 to 240 mAh for a CR2032 coin cell, 2,000 to 3,000 mAh for an AA alkaline, and 2,500 to 3,500 mAh for a rechargeable 18650. These are mid-range typical values, so read the sheet for your exact cell and load.
The C-rate says how hard you draw: 1C is the current that would empty the label capacity in one hour. For a 235 mAh cell, 1C is 235 mA. The average of 14 µA in our example is far below 0.001C, which is gentle. The 8 mA bursts are about 0.03C, which is still modest, but a coin cell reacts to short pulses because of its internal resistance.
A cell behaves like an ideal source in series with a resistor, its internal resistance Rint. When you draw current I, the terminal voltage drops by I × Rint. The drop is small at 10 µA. At an 8 mA burst with 15 Ω it is 120 mV. As the cell empties and as it gets cold, Rint rises, and the drop grows.
The usable life ends at the first x where the inequality fails, not at x = 1. Worked with illustrative curves: at 25 °C, 8 mA bursts and a 2.0 V cutoff, the terminal voltage crosses 2.0 V at about 90% discharged, so about 212 mAh are usable and 14 µA lasts 1.7 years. At −20 °C the resistance is 2.5 times higher and the usable charge is also lower. The crossing comes near 73%, about 103 mAh remain usable, and the life falls to 0.8 years.
Warm is the cell voltage at rest, teal is the voltage at the peak of a burst. The cell is spent where teal crosses the cutoff. Drag the temperature down, then raise the burst current.
Illustrative model, not a cell datasheet: the open-circuit voltage falls from 2.95 V to 2.74 V at 85% discharged and then to 2.0 V; internal resistance is 15 Ω × (1 + 4x³) at 25 °C and 2.5 times that at −20 °C; capacity is 235 mAh at 25 °C and 60% of that at −20 °C. The node averages 14 µA at the rail. The regulator figures are example values: read the datasheet for the part you use.
Many parts need a steady rail, so a regulator sits between cell and chip. A regulator draws its own quiescent current (Iq) even when the load is idle. A linear regulator (LDO, low drop-out) passes the load current straight through, so it wastes the voltage difference as heat and adds Iq on top. A buck converter steps voltage down efficiently when the load is large, but its efficiency drops at microamp loads, and it too has Iq.
An LDO with a 25 µA quiescent current feeding a 14 µA load makes the cell see 39 µA. That is 2.8 times the work. Put it on a node whose design goal was a 2 µA floor and the regulator becomes the floor. An LDO also needs headroom above its output, the dropout. When the sagging cell falls below output plus dropout, the rail collapses before the cell is empty.
A small capacitor can protect the cell from the burst. If the burst takes 8 mA for 5 ms, it needs 8 mA × 5 ms = 40 µC of charge. A capacitor of size C that supplies it drops by ΔV = Q / C. To hold the droop to 0.1 V you need C = 40 µC ÷ 0.1 V = 400 µF. The cell then refills the capacitor slowly between bursts, at a gentle current, which keeps the voltage drop across Rint small. The catch: large capacitors leak. An electrolytic type can leak microamps, which would add to a 10 µA floor. Pick a low-leakage type and add its leakage to the budget.
Symptom: field units die months early in winter. Measurement: put a unit in a temperature chamber or a freezer with a logging supply, and log the rail during bursts. You see the burst valleys touch the brown-out level. Fix: lower the burst current or spread it with a bulk capacitor, pick a cell rated for the cold, lower the cutoff if the part allows, and test at the worst temperature.
On real hardware. Take an nRF52840 DK powered from a CR2032 through the coin cell holder (check the board manual for the supply switch). Log the rail with a profiler during a radio burst, once at room temperature and once after the board has cooled. Compare the valley depth.
Chapter 9
Keep the numbers, the checklist and the budget calculator you will use on the next board
One equation ran through every chapter: average current is the sleep floor plus the bursts weighted by how often they happen. Below about 1% duty the floor is most of the budget. Chapters 1 and 2 shaped the burst, Chapters 3 to 5 lowered the floor and thinned the wake-ups, Chapter 6 moved the same ideas to Linux, Chapter 7 showed how to see the result, and Chapter 8 showed how the cell and regulator change the answer.
| Quantity | Value | Source | What we did |
|---|---|---|---|
| Lifetime from a duty table | capacity ÷ (Isleep(1 − d) + Iactive d) | derived in Chapter 0 | arithmetic, run in Python |
| Hero lifetimes | 98 days and 2.7 years (floor only); 94 days and 1.9 years with the 5 ms bursts | derived, 235 mAh assumed | arithmetic |
| CR2032 capacity | 235 mAh used; typical 220 to 240 mAh | typical vendor figure | assumed. The vendor sheet did not load in this build: read yours |
| STM32L476 run current | about 100 µA/MHz with the LDO, so 8 mA at 80 MHz | STM32L476 datasheet | checked in the datasheet summary text |
| STM32L476 low-power modes | Stop 2 1.1 µA (1.4 with RTC); Standby 120 nA (420 nA with RTC); Shutdown 30 nA | STM32L476 datasheet | checked in the datasheet feature list. What each mode retains: read RM0351 |
| nRF52840 System ON / OFF | 1.5 µA at 3 V, no RAM retention, RTC wake / 0.4 µA at 3 V | nRF52840 product specification (online) | opened. The page does not state its revision: re-check against your PDF version |
| ESP32-C6 deep sleep | 7 µA; Wi-Fi 6 TWT supported | ESP32-C6 datasheet v1.5 | opened |
| Nordic PPK2 | 500 nA to 1 A range, accurate to about 200 nA, 100 kS/s, 0.2 µA resolution | PPK2 user guide | opened. The user guide gives 500 nA to 1 A and the product page gives 200 nA to 1 A; resolution 0.2 µA applies to the 200 nA to 50 µA range. The 100 kS/s rate was not on the pages we read. |
| BLE connection parameters | interval 7.5 ms to 4.0 s in 1.25 ms steps; supervision timeout > 2 (L + 1) intervals; Zephyr default 30 to 50 ms and 4 s | Core Spec Vol 6 Part B; Zephyr docs | units and defaults checked in Zephyr. The range and the timeout rule are from the Core Spec and were not re-opened |
| Wi-Fi beacon | 102.4 ms (100 time units of 1.024 ms) | IEEE 802.11 | not re-opened |
| Linux runtime PM, sleep, cpuidle, energy model, RAPL | usage counter, autosuspend_delay_ms, control; s2idle / standby / deep / disk; residency and latency; P = C V² f; energy_uj | kernel documentation | opened. The files runtime_status, runtime_usage and wakeup_sources, and the RAPL update rate, are not in the pages we read |
| Not printed here | LTE PSM and eDRX limits, Jetson power envelopes, process-node claims, BLE profiler outputs | planned spec | not opened, so left out |
python# budget.py : lifetime from a duty table, with cell and regulator effects. CAP_MAH = {"cr2032": 235, "aa": 2500, "18650": 3000} # typical, light load def avg_ua(states): """states: list of (current_uA, seconds in that state per period).""" total = sum(s for _, s in states) return sum(i * s for i, s in states) / total def life_hours(cap_mah, load_ua, temp_factor=1.0, usable=1.0, reg_iq_ua=0.0, reg_eff=1.0): cell_ua = load_ua / reg_eff + reg_iq_ua # what the cell really supplies return cap_mah * temp_factor * usable * 1000 / cell_ua def ble_avg_ua(interval_s, latency, payload_b, floor_ua=1.5): t_event = 800e-6 + (payload_b + 10) * 8 / 1e6 # seconds on air plus start-up (illustrative) q_uc = t_event * 6000 # 6 mA average, in microcoulombs return floor_ua + q_uc / (interval_s * (latency + 1)) node = [(10, 9.995), (8000, 0.005)] # 10 uA sleep, 8 mA for 5 ms, period 10 s a = avg_ua(node) # 13.995 uA print(a, life_hours(CAP_MAH["cr2032"], a) / 24 / 365.25) # about 1.92 years
Power is the budget that every firmware lesson spends. Vector table to main explains the reset that Standby wakes through. Embedded systems intro, embedded C and hardware interfacing give the ground floor. Embedded RTOS and real-time systems explain the tick you remove for tickless idle. Timers and sampling covers the low-power timers, Zephyr in practice shows its power policy, and debug, trace and observability shows how to see what a part is doing. The coin cell year goes deeper on Chapter 5. On bigger boards, read embedded Linux, real-time Linux, robot real-time performance and sensor and actuator integration. For models on small chips, see profile, budget and ship. The thermal side of this budget on edge devices gets its own lesson later in the series.
Sources used: the STM32L476 datasheet (STMicroelectronics); the nRF52840 product specification and the Power Profiler Kit II user guide (Nordic Semiconductor); the ESP32-C6 datasheet v1.5 (Espressif); the Zephyr documentation for system power management and Bluetooth connections; and the Linux kernel documentation for runtime PM, sleep states, cpuidle, the energy model and powercap.
Now press Present or Teach and explain, from memory, why the node lasted 1.9 years and not 2.7, and what you would change first. Then go back to the budget at the top, set the sleep current to 100 µA, and say why a faster CPU would not rescue it.