---
title: "Project: a thermostat in both languages"
heading: Sensing, deciding and switching a heater, on the board
eyebrow: C12 · Lesson 53 · Project
xp: 60
---

::: hook
A thermostat is the classic embedded control system: read a temperature, compare it with a setpoint, switch a heater, repeat, forever, unattended. Doing it well takes most of this course: an I²C sensor, signed fixed-point readings, **hysteresis** so the heater doesn't chatter, a steady sampling rate, a status report over the UART, and sleep between readings. This project builds it twice, in MicroPython and in C, against a simulated room that warms when the heater is on and cools toward the outside temperature when it's off.
:::

::: play
- The MicroPython thermostat reads the room's sensor every 500 ms and switches the heater on P5 (and its lamp on P0): on below 19.5 °C, off above 20.5 °C. Every 5 s it reports over the UART.
- Run it: the room starts at 16 °C, warms to the band, then cycles inside it. The temp lane shows the sawtooth, and P5 the heater's on and off times.
- Set `BAND` to 0 and run again: the heater now switches nearly every reading, chattering, which wears out relays and contactors. Hysteresis trades a slightly wider swing for far fewer switchings.
:::
:::

```sim board
lang: micropython
attach: room P5 | T0 16 | Tout 5 | C 2000 | P 1500
attach: tmp102 0x48 | temp room
attach: led P0 | orange
attach: terminal
scope: P5, temp
run: 40 s
code:
from machine import Pin, I2C, UART
import time

SETPOINT = 20.0
BAND = 0.5               # heat below 19.5 °C, stop above 20.5 °C

heater = Pin(5, Pin.OUT)
lamp = Pin(0, Pin.OUT)
i2c = I2C(0)
uart = UART(0, 115200)

def temperature():
    raw = i2c.readfrom_mem(0x48, 0, 2)
    count = (raw[0] << 4) | (raw[1] >> 4)
    if count & 0x800:
        count -= 4096
    return count / 16

on = False
last_report = time.ticks_ms()
while True:
    t = temperature()
    if t < SETPOINT - BAND:
        on = True
    elif t > SETPOINT + BAND:
        on = False
    heater.value(on)
    lamp.value(on)
    if time.ticks_diff(time.ticks_ms(), last_report) >= 5000:
        last_report = time.ticks_ms()
        uart.write('%.2f C, heater %s\n' % (t, 'on' if on else 'off'))
    time.sleep_ms(500)
```

::: predict
## The heater warms the room at 0.375 °C/s near 20 °C, and it cools at the same rate when off. With a band from 19.5 to 20.5 °C, about how long is one on-off cycle?

- [ ] 1 s
- [x] About 5.3 s
- [ ] 20 s
- [ ] It depends on the setpoint only

::: reveal
About 5.3 s: crossing the 1 °C band takes $1/0.375 = 2.7$ s each way. A wider band means longer, fewer cycles and a bigger temperature swing; the sampling interval adds a little overshoot at each end.
:::
:::

::: nameit
## The room

Heat flows in from the heater, P watts when on, and out through the walls, $(T - T_\text{out})/R$, into a heat capacity C:

$$C\frac{dT}{dt} = P\cdot\text{on} - \frac{T - T_\text{out}}{R}$$

Here C = 2000 J/°C, R = 0.02 °C/W, P = 1500 W and $T_\text{out}$ = 5 °C, so the room would settle at 35 °C with the heater always on and 5 °C with it off; the time constant is $RC$ = 40 s. (Real rooms are hundreds of times slower; this one is fast so a run takes seconds.)

## On-off control with hysteresis

$$\text{heater} = \begin{cases} \text{on} & T < T_\text{set} - b \\ \text{off} & T > T_\text{set} + b \\ \text{unchanged} & \text{otherwise} \end{cases}$$

The band 2b sets the swing and the cycle time; with heating and cooling rates $r_h$ and $r_c$, a cycle lasts about $2b/r_h + 2b/r_c$.

## The firmware's jobs

1. Sample the sensor at a steady rate (a timer, or a deadline loop).
2. Convert the reading, minding the sign.
3. Decide with hysteresis; drive the heater and a status light.
4. Report now and then.
5. Sleep in between, and fail safe: if the sensor stops answering, turn the heater off.
:::

::: example
## With the heater on at 20 °C, how fast does the room warm? And with it off?

::: solution
1. **Heater on.**
   $$\begin{aligned} \text{rate} &= \frac{1500 - (20 - 5)/0.02}{2000} \\ &= \frac{1500 - 750}{2000} \\ &= 0.375\ \text{°C/s} \end{aligned}$$
2. **Heater off.**
   $$\frac{-750}{2000} = -0.375\ \text{°C/s}$$
3. **Why they match.** The setpoint was chosen where they're equal, so the cycle is symmetric.

**Answer:** it warms at 0.375 °C/s with the heater on and cools at 0.375 °C/s with it off.
:::
:::

::: example
## The sensor stops answering (its I²C reads return NACK). What should the thermostat do?

::: solution
1. **Act safely.** Turn the heater off and report the fault.
2. **Why off.** A heater left on because the controller can't see the temperature is the dangerous failure; a heater off is merely uncomfortable.
3. **A second line of defense.** Real thermostats also have an independent over-temperature cutout, so a firmware bug can't cause a fire either.

**Answer:** turn the heater off and report the fault.
:::
:::

::: check
given: P = 1000 | 1500 | 2000; T = 18 | 20 | 22; To = 0 | 5; R = 0.02; C = 2000
answer: (P - (T - To)/R)/C
unit: °C/s
tolerance: 0.5%

## The room ({C} J/°C, R = {R} °C/W, outside {To} °C) is at {T} °C with a {P} W heater on. How fast is it warming?

::: right
Right. $(P - (T - T_\text{out})/R)/C$ = {answer} °C/s.
:::

::: misses
- [P/C] Heat also leaks out through the walls.
- [any] Not yet. Heat in minus heat out, over the heat capacity.
:::
:::

::: check
given: P = 1000 | 1500 | 3000; To = 0 | 5 | 10; R = 0.02 | 0.01
answer: To + P*R
unit: °C
tolerance: 0.5%

## A room with R = {R} °C/W, outside temperature {To} °C, and a {P} W heater always on: where does it settle?

::: right
Right. $T_\text{out} + PR$ = {answer} °C.
:::

::: misses
- [any] Not yet. Settled means heat in equals heat out.
:::
:::

::: check
given: b = 0.25 | 0.5 | 1; rh = 0.2 | 0.375; rc = 0.25 | 0.375
answer: 2*b/rh + 2*b/rc
unit: s
tolerance: 0.5%

## A thermostat's band is ±{b} °C; the room warms at {rh} °C/s with the heater on and cools at {rc} °C/s with it off. How long is one cycle?

::: right
Right. $2b/r_h + 2b/r_c$ = {answer} s.
:::

::: misses
- [b/rh + b/rc] The band is ±{b}: it spans 2 × {b} degrees.
- [any] Not yet. Time to warm across the band plus time to cool back.
:::
:::

::: check
given: R = 0.01 | 0.02 | 0.05; C = 2000 | 50000
answer: R*C
unit: s
tolerance: 0.5%

## What's the time constant of a room with R = {R} °C/W and C = {C} J/°C?

::: right
Right. $RC$ = {answer} s.
:::

::: misses
- [any] Not yet. R times C.
:::
:::

::: check
given: T = 40 | 300; c = 5.3 | 12
answer: floor(T/c)
tolerance: 0

## A heater cycles every {c} s. About how many times does it switch on in {T} s, once the room is in its band?

::: right
Right. About {answer} times.
:::

::: misses
- [any] Not yet. Run time over the cycle time.
:::
:::

::: check
kind: choice

## The thermostat's sensor stops answering. What's the safest thing for the firmware to do?

- [ ] Keep the heater in whatever state it was in
- [ ] Turn the heater on, so the room doesn't get cold
- [x] Turn the heater off and report a fault
- [ ] Reset the board repeatedly until the sensor answers

::: misses
- [1] If it was on, the room heats without limit.
- [2] That's the dangerous failure.
- [4] Resets alone don't make the heater safe meanwhile.
:::
:::

::: check
kind: c
attach: room P5 | T0 16 | Tout 5 | C 2000 | P 1500; tmp102 0x48 | temp room
run: 40
expect: temp = 20 ± 1; rises(P5) >= 3; rises(P5) <= 10

## Write the thermostat in C: read the sensor every 500 ms, heat below 19.5 °C, stop above 20.5 °C (heater on P5).

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

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

int read_sixteenths(void) {
    I2C_ADDR = 0x48; I2C_DATA = 0;
    cmd(I2C_START_WRITE); 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);
    int raw = ((hi << 8) | lo) >> 4;
    if (raw & 0x800) raw -= 4096;
    return raw;
}

int main(void) {
    GPIO_DIR = 1 << 5;
    while (1) {
        if (read_sixteenths() < 20 * 16) GPIO_SET = 1 << 5;
        else GPIO_CLR = 1 << 5;
        uint32_t t = SYS_CYCLES;
        while (SYS_CYCLES - t < 5000000) ;
    }
}
```

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

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

int read_sixteenths(void) {
    I2C_ADDR = 0x48; I2C_DATA = 0;
    cmd(I2C_START_WRITE); 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);
    int raw = ((hi << 8) | lo) >> 4;
    if (raw & 0x800) raw -= 4096;
    return raw;
}

int main(void) {
    GPIO_DIR = 1 << 5;
    int on = 0;
    while (1) {
        int t16 = read_sixteenths();          // sixteenths of a degree
        if (t16 < 19 * 16 + 8) on = 1;        // below 19.5 °C
        else if (t16 > 20 * 16 + 8) on = 0;   // above 20.5 °C
        if (on) GPIO_SET = 1 << 5;
        else GPIO_CLR = 1 << 5;
        uint32_t t = SYS_CYCLES;
        while (SYS_CYCLES - t < 5000000) ;    // 500 ms
    }
}
```

::: right
Right. The band keeps the heater from switching on every reading; in sixteenths, 19.5 °C is 312.
:::
:::

::: check
kind: micropython
given: SP = 17 | 19 | 22
attach: room P5 | T0 14 | Tout 5 | C 2000 | P 1500; tmp102 0x48 | temp room
run: 40
expect: temp = SP ± 1; rises(P5) <= 12

## The thermostat in MicroPython with the setpoint `SP` ({SP} °C) and a ±0.5 °C band; sample every 500 ms.

```micropython starter
from machine import Pin, I2C
import time

heater = Pin(5, Pin.OUT)
heater.on()
while True:
    time.sleep_ms(500)
```

```micropython solution
from machine import Pin, I2C
import time

heater = Pin(5, Pin.OUT)
i2c = I2C(0)

def temperature():
    raw = i2c.readfrom_mem(0x48, 0, 2)
    count = (raw[0] << 4) | (raw[1] >> 4)
    if count & 0x800:
        count -= 4096
    return count / 16

on = False
while True:
    t = temperature()
    if t < SP - 0.5:
        on = True
    elif t > SP + 0.5:
        on = False
    heater.value(on)
    time.sleep_ms(500)
```

::: right
Right. The same logic as the C version, a third the length.
:::
:::

::: explain
## Why does an on-off thermostat need hysteresis?

::: model
With a single threshold, the heater turns off the moment the temperature crosses the setpoint, the room cools a hair, and it turns back on at the next reading; near the setpoint the temperature hovers and the heater switches on and off every sample. That chattering wears out relays and contactors, which are rated for a limited number of operations, and can make noise and electrical interference. Two thresholds, on below the band and off above it, mean the room must travel across the whole band between switchings, so the heater cycles slowly, a few times a minute here, at the cost of a swing of about the band's width.
:::
:::

::: practice

::: check
given: P = 1200 | 2500; T = 19 | 21; To = 3 | 8; R = 0.02; C = 2000
answer: (P - (T - To)/R)/C
unit: °C/s
tolerance: 0.5%

## Warming rate: {P} W, {T} °C inside, {To} °C outside, R {R}, C {C}?

::: misses
- [any] $(P - (T - T_\text{out})/R)/C$.
:::
:::

::: check
given: P = 800 | 2000; To = 2 | 12; R = 0.015 | 0.03
answer: To + P*R
unit: °C
tolerance: 0.5%

## Settled temperature with {P} W always on, R {R}, outside {To} °C?

::: misses
- [any] $T_\text{out} + PR$.
:::
:::

::: check
given: b = 0.3 | 0.75; rh = 0.3; rc = 0.2 | 0.4
answer: 2*b/rh + 2*b/rc
unit: s
tolerance: 0.5%

## Cycle time: band ±{b}, warming {rh}, cooling {rc} °C/s?

::: misses
- [any] $2b/r_h + 2b/r_c$.
:::
:::
:::
