---
title: "Solar sensor node: firmware that sleeps"
heading: Writing the node's firmware so it spends nearly all its time in deep sleep, waking on a timer interrupt, reading a TMP102 temperature sensor over I²C, reporting, and going back to sleep, with the average current measured on the board
eyebrow: D13 · Lesson 3 · Solar sensor node
xp: 40
---

::: hook
The energy budget in lesson 2 assumed the node sleeps almost all the time. The firmware has to make that true. A loop that waits by spinning on a clock keeps the processor running at full current between readings; a node that sleeps deeply and lets a timer wake it uses a few percent of that. The structure is the one from C12: a timer interrupt sets a flag, the main loop does the work when the flag is set, and then the processor sleeps until the next interrupt.
:::

::: play
- The node's firmware on the C12 board: every 100 ms (a minute, in a real node, scaled down so the run is short) the timer wakes the processor, which reads the TMP102 over I²C and prints the temperature in hundredths of a degree, then sleeps.
- The power panel shows the average current and the life of a 2000 mAh battery. Change `MODE` to 0 (busy waiting) or 1 (light sleep) and run again to compare.
- Move the sensor's temperature slider: the readings follow it, in steps of 1/16 °C, the sensor's resolution.
:::

```sim board
lang: c
attach: tmp102 0x48 | temp 23.5
scope: SDA, SCL | 0.099..0.1006 s
run: 1 s
show: power
battery: 2000 mAh
code:
#include "board.h"

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

volatile int due = 0;

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

void cmd(int c) {
    I2C_CMD = c;
    while (I2C_STATUS & I2C_BUSY) ;
}

int read_reg(int addr, int reg) {
    I2C_ADDR = addr;
    cmd(I2C_START_WRITE);
    I2C_DATA = reg;
    cmd(I2C_WRITE);
    cmd(I2C_START_READ);
    cmd(I2C_READ_ACK);
    int hi = I2C_DATA;
    cmd(I2C_READ_NACK);
    int lo = I2C_DATA;
    cmd(I2C_STOP);
    return (hi << 8) | lo;
}

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;
            int raw = read_reg(0x48, 0) >> 4;   // 12 bits of 1/16 degree
            if (raw & 0x800) raw -= 4096;       // negative temperatures
            print(raw * 100 / 16);              // hundredths of a degree
        }
        if (MODE) __wfi();
    }
}
```

::: predict
## Awake, the node draws 2.05 mA; in deep sleep, 0.052 mA. If it's awake 0.5% of the time, how much longer does a battery last than if it never slept?

- [ ] Twice as long
- [ ] Ten times as long
- [x] About 33 times as long
- [ ] About 200 times as long

::: reveal
The average is 0.005 × 2.05 + 0.995 × 0.052 = 0.062 mA against 2.05 mA, a factor of 33. It isn't 200 because the sleep current itself, mostly the wake-up timer, now dominates: 0.052 mA is 84% of the average. That's the next thing to attack (C12).
:::
:::

::: nameit
## The loop

1. Set up a timer to interrupt at the reporting interval and enable deep sleep.
2. In the interrupt handler, clear the timer's flag and set a `volatile` flag; nothing slow belongs there (C12).
3. In the main loop, when the flag is set, read the sensor and report; then execute `wfi` to sleep until the next interrupt.

## Reading the TMP102

The temperature register holds a 12-bit two's-complement value in its top 12 bits, in units of 1/16 °C. A register read on I²C is a write of the register number, a repeated start, and a read of two bytes: five bytes of 9 clocks each, 45 clocks, 450 µs at 100 kHz.

## Measuring, not guessing

The budget's numbers come from the datasheet; the board's power panel measures what the firmware actually does. A forgotten busy loop, a peripheral left on or a sleep that never happens shows up at once as an average current far above the budget.
:::

::: example
## The TMP102 reads 0x1780. What temperature is that?

::: solution
1. **Shift right by 4.** 0x1780 becomes
   $$\text{0x178} = 376\ \text{sixteenths}$$
2. **Convert to degrees.**
   $$\begin{aligned} T &= \frac{376}{16}\ ^\circ\text{C} \\ &= 23.5\ ^\circ\text{C} \end{aligned}$$
3. **A negative reading.** −5.25 °C is −84 sixteenths, stored as
   $$\begin{aligned} 4096 - 84 &= 4012 \\ &= \text{0xFAC} \end{aligned}$$
   so the register reads 0xFAC0.
4. **Decoding the sign.** The code subtracts 4096 when bit 11 is set.

**Answer:** 23.5 °C.
:::
:::

::: example
## How long is the processor awake per reading if an I²C register read at 100 kHz dominates, and what does that do to the average?

::: solution
1. **Awake time.** About 45 clocks at 10 µs, plus a little code:
   $$45 \times 10\ \mu\text{s} = 0.45\ \text{ms}$$
2. **A reading every 100 ms.** That's 0.45% awake:
   $$\begin{aligned} \bar I &= 0.0045 \times 2.05 \\ &\quad + 0.9955 \times 0.052 \\ &= 0.061\ \text{mA} \end{aligned}$$
3. **A reading a minute.** The awake share falls to under 0.001%, and the average is the sleep current, 0.052 mA.

**Answer:** about 0.45 ms awake per reading, which makes the average 0.061 mA at a reading every 100 ms and leaves it at the 0.052 mA sleep current at one a minute.
:::
:::

::: check
kind: c
given: T = 23.5 | -5.25 | 41 | 18.75
attach: tmp102 0x48 | temp {T}
run: 0.35
expect: current < 0.3 mA; print = 100*T, 100*T, 100*T

## This node reads the TMP102 every 100 ms but waits busily in between. Make it read from a 100 ms timer interrupt and deep-sleep in between, printing the same hundredths of a degree ({T} °C here).

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

void cmd(int c) {
    I2C_CMD = c;
    while (I2C_STATUS & I2C_BUSY) ;
}

int read_reg(int addr, int reg) {
    I2C_ADDR = addr;
    cmd(I2C_START_WRITE);
    I2C_DATA = reg;
    cmd(I2C_WRITE);
    cmd(I2C_START_READ);
    cmd(I2C_READ_ACK);
    int hi = I2C_DATA;
    cmd(I2C_READ_NACK);
    int lo = I2C_DATA;
    cmd(I2C_STOP);
    return (hi << 8) | lo;
}

int read_hundredths(void) {
    int raw = read_reg(0x48, 0) >> 4;
    if (raw & 0x800) raw -= 4096;
    return raw * 100 / 16;
}

int main(void) {
    while (1) {
        print(read_hundredths());
        uint32_t t = SYS_CYCLES;
        while (SYS_CYCLES - t < 1000000) ;     // wait 100 ms, busily
    }
}
```

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

volatile int due = 0;

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

void cmd(int c) {
    I2C_CMD = c;
    while (I2C_STATUS & I2C_BUSY) ;
}

int read_reg(int addr, int reg) {
    I2C_ADDR = addr;
    cmd(I2C_START_WRITE);
    I2C_DATA = reg;
    cmd(I2C_WRITE);
    cmd(I2C_START_READ);
    cmd(I2C_READ_ACK);
    int hi = I2C_DATA;
    cmd(I2C_READ_NACK);
    int lo = I2C_DATA;
    cmd(I2C_STOP);
    return (hi << 8) | lo;
}

int read_hundredths(void) {
    int raw = read_reg(0x48, 0) >> 4;
    if (raw & 0x800) raw -= 4096;
    return raw * 100 / 16;
}

int main(void) {
    set_trap_handler(on_timer);
    TIMER_PRESCALE = 9999;
    TIMER_TOP = 99;
    TIMER_CTRL = TIMER_RUN | TIMER_IRQ;
    enable_external_interrupt();
    enable_interrupts();
    SYS_SLEEP = 1;
    while (1) {
        if (due) {
            due = 0;
            print(read_hundredths());
        }
        __wfi();
    }
}
```

::: right
Right: three readings at 100, 200 and 300 ms, and the processor asleep in between.
:::
:::

::: check
given: T = 23.5 | -5.25 | 41 | 100 | -40
answer: 16*T
tolerance: 0.4

## The TMP102 counts in sixteenths of a degree. What signed 12-bit value does it report at {T} °C?

::: right
Right. {T} × 16 = {answer}.
:::

::: misses
- [256*T] That's the whole 16-bit register; the value is its top 12 bits.
- [any] Not yet. Sixteenths of a degree.
:::
:::

::: check
given: f = 100 | 400 | 1000
answer: 45/f*1000
unit: µs
tolerance: 0.5%

## A TMP102 register read takes 45 I²C clocks. How long is that at {f} kHz?

::: right
Right. 45 clocks at {f} kHz: {answer} µs.
:::

::: misses
- [any] Not yet. Clocks over the clock rate.
:::
:::

::: check
given: a = 0.1 | 0.5 | 2; s = 0.052 | 0.55
answer: a/100*2.05 + (1 - a/100)*s
unit: mA
tolerance: 0.5%

## A node is awake {a}% of the time at 2.05 mA and sleeps the rest at {s} mA. What's its average current?

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

::: misses
- [a/100*2.05] The sleep current flows the rest of the time.
- [any] Not yet. Weight each current by its share of the time.
:::
:::

::: check
kind: parts
given: Ia = 2 | 5 | 10; ta = 5 | 20 | 100; T = 10 | 60 | 600; Is = 2 | 5

## Firmware wakes every {T} s for {ta} ms at {Ia} mA and sleeps at {Is} µA otherwise.

::: part
answer: ta*1e-3/T*100
tolerance: 0.5%

### What fraction of the time is it awake, in percent?

::: misses
- [ta/T*100] Put the awake time in seconds.
- [any] Not yet. Awake time ÷ period.
:::
:::

::: part
answer: (Ia*1e3*ta*1e-3/T + Is*(1 - ta*1e-3/T))
unit: µA
tolerance: 0.5%

### What is the average current?

::: misses
- [Ia*1e3*ta*1e-3/T] Add the sleep current, which flows the rest of the time.
- [any] Not yet. Weight each current by its share of time.
:::
:::

::: right
Right. With long sleeps, the sleep current often dominates: that's where low-power firmware wins or loses.
:::
:::

::: check
given: Ia = 3 | 8; ta = 10 | 50; Is = 1 | 3
answer: Ia*1e3*ta*1e-3/Is
unit: s
tolerance: 0.5%

## A node wakes for {ta} ms at {Ia} mA and sleeps at {Is} µA. At what wake interval do the awake and sleep charge per cycle become equal (so the sleep current makes up half the budget)?

::: right
Right. Setting $I_at_a = I_sT$ gives $T$ = {answer}.
:::

::: misses
- [any] Not yet. Solve $I_at_a = I_sT$.
:::
:::

::: explain
## Why does the interrupt handler only set a flag instead of reading the sensor itself?

::: model
An interrupt handler runs with other interrupts held off, so anything slow inside it delays everything else that might need attention, such as a byte arriving on the UART or the next timer tick. An I²C read takes about half a millisecond of waiting on the bus, and printing or radio work takes longer. Setting a flag takes a few instructions; the main loop then does the slow work with interrupts enabled and goes back to sleep when it's done. This keeps the handler's timing predictable and the structure the same however much work each reading grows into.
:::
:::

::: practice

::: check
given: T = 0.0625 | -0.5 | 85 | -25
answer: 16*T
tolerance: 0.4

## TMP102 value at {T} °C?

::: misses
- [any] $16T$.
:::
:::

::: check
given: a = 0.01 | 5; s = 0.002 | 0.052 | 0.55
answer: a/100*2.05 + (1 - a/100)*s
unit: mA
tolerance: 0.5%

## Average: awake {a}% at 2.05 mA, {s} mA asleep?

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