---
title: Power budgets and sleep
heading: Making a battery last months instead of days
eyebrow: C12 · Lesson 42 · Power budgets and sleep
xp: 40
---

::: hook
A sensor that reports every few seconds spends almost all its life waiting. If the processor waits by running a loop, it burns its full current the whole time, and a coin cell is flat in days. If it sleeps between readings, the same battery lasts months; in deep sleep, years. Battery-powered firmware is designed around that fact: do the work in short bursts, then sleep until a timer or a pin wakes you. The arithmetic is simple, an average weighted by time, and it shows at once which part of the design is eating the battery.
:::

::: play
- The program reads a sensor every 100 ms. Between readings it either waits busily (`MODE 0`), sleeps with `__wfi()` (`MODE 1`), or deep-sleeps (`MODE 2`). The power panel shows the average current and how long a 220 mAh coin cell would last.
- Run all three: about 2.05 mA (4.5 days), 0.55 mA (17 days) and 0.052 mA (175 days). The work itself, a 10 µs conversion ten times a second, barely registers.
- In deep sleep the timer's own 50 µA is now most of the total: the next saving would come from a lower-power timer, not from the code.
:::
:::

```sim board
lang: c
attach: pot ADC0 = 1.2 V
run: 1 s
show: power
battery: 220 mAh
code:
#include "board.h"

#define MODE 0     // 0: wait busily; 1: sleep (wfi); 2: deep sleep

volatile int due = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    due = 1;
}

int read_adc(int ch) {
    ADC_CTRL = ch | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    return ADC_DATA;
}

int main(void) {
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;                     // every 100 ms
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    if (MODE == 2) SYS_SLEEP = 1;       // make wfi a deep sleep
    while (1) {
        if (due) {
            due = 0;
            print(read_adc(0));         // the sensor reading
        }
        if (MODE) __wfi();              // nothing to do until the next tick
    }
}
```

::: predict
## A device draws 2 mA while awake and 0.002 mA asleep, and it's awake 1% of the time. What's its average current?

- [ ] 2 mA
- [ ] 1 mA
- [x] About 0.022 mA
- [ ] 0.002 mA

::: reveal
About 0.022 mA: $0.01 \times 2 + 0.99 \times 0.002 = 0.020 + 0.00198$. The 1% awake still dominates, ten times the sleep current, so shortening the awake time, or waking less often, is where the next saving lies.
:::
:::

::: nameit
## Average current

Each state contributes its current times the fraction of time spent in it:

$$\bar I = \sum_k I_k \frac{t_k}{T}$$

counting the processor's mode, every peripheral that's running, and the loads: an LED lit at 3.9 mA can outweigh the whole chip. A battery of capacity Q (in mAh) lasts

$$t = \frac{Q}{\bar I}$$

in hours (in practice somewhat less, because capacity falls at low temperatures and high currents).

## This board

| State | Current |
|---|---|
| CPU running | 2 mA |
| CPU asleep (`wfi`) | 0.5 mA |
| deep sleep (`SYS_SLEEP = 1`, then `wfi`) | 0.002 mA |
| timer running | +0.05 mA |
| ADC converting | +0.6 mA for its 10 µs |
| UART, I²C or SPI transferring | +0.1 to 0.15 mA while busy |
| an LED lit | +3.9 mA |

## Designing for it

- Sleep whenever there's nothing to do; let interrupts (a timer, a pin, a byte) wake the processor.
- Wake as seldom as the job allows, and finish quickly.
- Turn off peripherals when not in use; light LEDs briefly, or not at all.
- Batch work: one wake-up that does three things beats three wake-ups.
- In MicroPython, `time.sleep_ms()` and `machine.lightsleep()` let the processor sleep; a loop that spins checking the clock never does.
:::

::: example
## How long does a 220 mAh coin cell last at 0.55 mA, and at 0.052 mA?

::: solution
1. **At 0.55 mA.**
   $$\begin{aligned} \frac{220\ \text{mAh}}{0.55\ \text{mA}} &= 400\ \text{h} \\ &\approx 17\ \text{days} \end{aligned}$$
2. **At 0.052 mA.**
   $$\begin{aligned} \frac{220\ \text{mAh}}{0.052\ \text{mA}} &= 4230\ \text{h} \\ &\approx 176\ \text{days} \end{aligned}$$

**Answer:** about 17 days at 0.55 mA, and about 176 days at 0.052 mA.
:::
:::

::: example
## The device flashes a 3.9 mA LED for 20 ms every 2 s as a heartbeat. What does that add to the average?

::: solution
1. **Average the flash over its period.**
   $$\frac{3.9\ \text{mA} \times 0.02\ \text{s}}{2\ \text{s}} = 0.039\ \text{mA}$$
2. **Compare.** That's almost as much as the whole deep-sleep design.
3. **A lighter heartbeat.** A 5 ms flash every 10 s would add 0.002 mA.

**Answer:** 0.039 mA.
:::
:::

::: example
## Each measurement wakes the board for 5 ms at 2.05 mA from 3.3 V. How much energy does it cost?

::: solution
1. **Energy per measurement.**
   $$\begin{aligned} E &= VIt \\ &= (3.3\ \text{V})(2.05\ \text{mA})(5\ \text{ms}) \\ &= 33.8\ \mu\text{J} \end{aligned}$$
2. **What a coin cell holds.** A 220 mAh coin cell holds about 2.6 kJ at 3.3 V, enough for some 77 million such measurements, if sleeping cost nothing.
3. **In practice.** The sleep current between measurements usually dominates.

**Answer:** 33.8 µJ per measurement.
:::
:::

::: check
given: Ia = 2 | 5; Is = 0.05 | 0.5; d = 0.1 | 1 | 10
answer: d/100*Ia + (1 - d/100)*Is
unit: mA
tolerance: 0.5%

## A device draws {Ia} mA awake and {Is} mA asleep, and it's awake {d}% of the time. What's its average current?

::: right
Right. {answer} mA.
:::

::: misses
- [d/100*Ia] Asleep isn't zero: add the sleep current for the rest of the time.
- [any] Not yet. Weight each current by its share of the time.
:::
:::

::: check
given: Q = 220 | 1000 | 2500; I = 0.05 | 0.5 | 2
answer: Q/I/24
unit: days
tolerance: 0.5%

## A {Q} mAh battery supplies an average of {I} mA. How many days does it last?

::: right
Right. $Q/\bar I$ = {answer} days.
:::

::: misses
- [Q/I] That's hours: divide by 24.
- [any] Not yet. Capacity over current, in hours, then days.
:::
:::

::: check
given: I = 3.9 | 8; t = 5 | 20 | 50; T = 1 | 5 | 10
answer: I*t/1000/T
unit: mA
tolerance: 0.5%

## An LED drawing {I} mA flashes for {t} ms every {T} s. What does it add to the average current?

::: right
Right. {answer} mA.
:::

::: misses
- [I*t/T] The flash is in ms and the period in s: convert.
- [any] Not yet. Current times its share of the time.
:::
:::

::: check
given: Iadc = 0.6; n = 10 | 100 | 1000; tc = 10
answer: Iadc*n*tc*1e-6
unit: mA
tolerance: 0.5%

## The ADC draws an extra {Iadc} mA for each {tc} µs conversion, and the program converts {n} times a second. What does that add to the average current?

::: right
Right. {answer} mA.
:::

::: misses
- [any] Not yet. Its current times the fraction of time it's converting.
:::
:::

::: check
given: f = 1 | 10 | 100; t = 0.5 | 2
answer: 100*f*t/1000
unit: %
tolerance: 0.5%

## A device wakes {f} times a second and is awake {t} ms each time. What fraction of the time is it awake?

::: right
Right. {answer}%.
:::

::: misses
- [any] Not yet. Wake-ups per second times time awake.
:::
:::

::: check
kind: choice

## A battery sensor in deep sleep draws 0.052 mA, of which 0.05 mA is its wake-up timer. What would most extend the battery's life?

- [ ] Rewriting the code to run faster
- [x] A lower-power timer for the wake-up
- [ ] Reading the sensor twice as often
- [ ] A bigger stack

::: misses
- [1] The code's awake time is already a tiny part of the total.
- [3] That adds awake time.
- [4] Memory doesn't draw current here.
:::
:::

::: check
kind: c
attach: pot ADC0 = 2 V
run: 1
expect: current < 0.6 mA; print = 2482, 2482, 2482, 2482, 2482, 2482, 2482, 2482, 2482

## This logger reads the sensor every 100 ms but waits busily in between, drawing over 2 mA. Make it sleep between readings, keeping the readings the same.

```c starter
#include "board.h"

#define MODE 0     // 0: wait busily; 1: sleep (wfi); 2: deep sleep

volatile int due = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    due = 1;
}

int read_adc(int ch) {
    ADC_CTRL = ch | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    return ADC_DATA;
}

int main(void) {
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;                     // every 100 ms
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    if (MODE == 2) SYS_SLEEP = 1;       // make wfi a deep sleep
    while (1) {
        if (due) {
            due = 0;
            print(read_adc(0));         // the sensor reading
        }
        if (MODE) __wfi();              // nothing to do until the next tick
    }
}
```

```c solution
#include "board.h"

#define MODE 1     // 0: wait busily; 1: sleep (wfi); 2: deep sleep

volatile int due = 0;

void __attribute__((interrupt)) on_timer(void) {
    TIMER_FLAGS = 1;
    due = 1;
}

int read_adc(int ch) {
    ADC_CTRL = ch | ADC_START;
    while (!(ADC_STATUS & ADC_DONE)) ;
    ADC_STATUS = ADC_DONE;
    return ADC_DATA;
}

int main(void) {
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;                     // every 100 ms
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    if (MODE == 2) SYS_SLEEP = 1;       // make wfi a deep sleep
    while (1) {
        if (due) {
            due = 0;
            print(read_adc(0));         // the sensor reading
        }
        if (MODE) __wfi();              // nothing to do until the next tick
    }
}
```

::: right
Right. One `__wfi()` and the average current falls to about a quarter.
:::
:::

::: check
kind: micropython
attach: led P0
run: 1
expect: current < 1 mA; period(P0) = 200 ms ± 2%

## This blinker waits by spinning on the clock, keeping the processor awake. Make it sleep instead, keeping the blink the same.

```micropython starter
from machine import Pin
import time

led = Pin(0, Pin.OUT)
while True:
    led.on()
    start = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start) < 10:
        pass
    led.off()
    start = time.ticks_ms()
    while time.ticks_diff(time.ticks_ms(), start) < 190:
        pass
```

```micropython solution
from machine import Pin
import time

led = Pin(0, Pin.OUT)
while True:
    led.on()
    time.sleep_ms(10)
    led.off()
    time.sleep_ms(190)
```

::: right
Right. The same blink, with the processor asleep between edges.
:::
:::

::: check
kind: parts
given: C = 220 | 1000 | 2400; I = 0.052 | 0.55 | 2.05

## A {C} mAh battery powers a load averaging {I} mA.

::: part
answer: C/I
unit: h
tolerance: 0.5%

### How long does it last?

::: misses
- [any] Capacity ÷ current.
:::
:::

::: part
answer: C/I/24
unit: days
tolerance: 0.5%

### In days?

::: misses
- [any] Hours ÷ 24.
:::
:::
:::

::: check
kind: parts
given: Is = 0.052 | 0.55; Ia = 2.05 | 6; t = 5 | 50; T = 1 | 10

## A device sleeps at {Is} mA and wakes to {Ia} mA for {t} ms every {T} s.

::: part
answer: Is + (Ia - Is)*t/1000/T
unit: mA
tolerance: 0.5%

### What is its average current?

::: misses
- [any] Sleep current plus the extra while awake, times the duty.
:::
:::

::: part
answer: (Ia - Is)*t/1000/T/(Is + (Ia - Is)*t/1000/T)*100
unit: %
tolerance: 0.5%

### What share of the average comes from waking?

::: misses
- [any] The awake extra over the average.
:::
:::
:::

::: explain
## Why does a battery-powered device's lifetime depend far more on how it waits than on how fast its code runs?

::: model
A typical sensor device is idle almost all the time: it does a few milliseconds of work every second or every minute. Its average current is each state's current weighted by the time spent in it, so the waiting state's current, multiplied by nearly all the time, dominates. Waiting in a loop keeps the processor at full current; sleeping cuts that by four times here, and deep sleep by a thousand. Making the code twice as fast only halves a term that was already tiny. Only once the sleep current is minimized do the awake time, the wake-up rate and the peripherals' standby currents become worth optimizing.
:::
:::

::: practice

::: check
given: Ia = 3 | 8; Is = 0.01 | 0.2; d = 0.5 | 5
answer: d/100*Ia + (1 - d/100)*Is
unit: mA
tolerance: 0.5%

## Average of {Ia} mA awake {d}% of the time and {Is} mA asleep?

::: misses
- [any] Weight by time.
:::
:::

::: check
given: Q = 600 | 3000; I = 0.1 | 4
answer: Q/I/24
unit: days
tolerance: 0.5%

## Days from {Q} mAh at {I} mA?

::: misses
- [any] Q / I / 24.
:::
:::

::: check
given: I = 2 | 10; t = 10 | 100; T = 2 | 60
answer: I*t/1000/T
unit: mA
tolerance: 0.5%

## Added by a {I} mA, {t} ms flash every {T} s?

::: misses
- [any] I × t / T.
:::
:::
:::
