---
title: I²C and a temperature sensor
heading: Two wires, many devices, and a conversation for each read
eyebrow: C12 · Lesson 30 · I²C and a temperature sensor
xp: 40
---

::: hook
A board with a temperature sensor, an accelerometer, a clock chip and a memory would run out of pins if each had its own wires. **I²C** connects them all to the same two: a data line (SDA) and a clock line (SCL). Every device has an address, and every exchange is a short conversation the controller starts: a start signal, an address, a direction, then bytes, each acknowledged by whoever received it. Reading one register of a sensor takes about half a millisecond at the standard 100 kHz, and the waveforms are simple enough to read by eye on a logic analyzer.
:::

::: play
- The program reads the temperature sensor at address 0x48 every 100 ms and prints its reading in hundredths of a degree. Run it, then look at the SDA and SCL lanes (zoomed to the first read).
- Find the pieces: SDA falling while SCL is high (start), 9 clocks for the address byte with its write bit and the sensor's acknowledgment, 9 for the register number, a repeated start, 9 for the address with the read bit, then two data bytes, and SDA rising while SCL is high (stop).
- Change the sensor's temperature slider and run again: the printed value follows it.
:::
:::

```sim board
lang: c
attach: tmp102 0x48 | temp 23.5
scope: SDA, SCL | 0..0.55 ms
run: 0.35 s
code:
#include "board.h"

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

// Read a 16-bit register: write its number, then read two bytes.
int read_reg(int addr, int reg) {
    I2C_ADDR = addr;
    cmd(I2C_START_WRITE);
    I2C_DATA = reg;
    cmd(I2C_WRITE);
    cmd(I2C_START_READ);           // a repeated start, now reading
    cmd(I2C_READ_ACK);
    int hi = I2C_DATA;
    cmd(I2C_READ_NACK);            // NACK: that's the last byte
    int lo = I2C_DATA;
    cmd(I2C_STOP);
    return (hi << 8) | lo;
}

int main(void) {
    for (int i = 0; i < 3; i++) {
        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
        uint32_t t = SYS_CYCLES;
        while (SYS_CYCLES - t < 1000000) ;  // wait 100 ms
    }
    return 0;
}
```

::: predict
## A device's 7-bit address is 0x48. What byte does the controller send to start reading from it?

- [ ] 0x48
- [x] 0x91
- [ ] 0x90
- [ ] 0x49

::: reveal
0x91: the address goes in the top 7 bits and the direction in bit 0 (1 for read), so $(\text{0x48} \ll 1)\ |\ 1 = \text{0x90} + 1$. Writing would send 0x90. Datasheets sometimes quote these 8-bit forms, a frequent source of confusion.
:::
:::

::: nameit
## The bus

SDA and SCL are **open-drain**: devices only pull them low, and pull-up resistors bring them high. The controller drives SCL; data changes only while SCL is low, except for two special events:

- **start**: SDA falls while SCL is high;
- **stop**: SDA rises while SCL is high.

Each byte is 8 bits, most significant first, followed by a ninth clock in which the receiver pulls SDA low to **acknowledge** (ACK) or leaves it high (NACK). A controller reading NACKs the last byte to say it's done.

## Addresses and transactions

Every device has a 7-bit address; the first byte after a start is the address shifted left with the direction in bit 0 (0 write, 1 read). If no device answers, the address byte is NACKed. Reading a register is a write then a read:

start, address+W, register, **repeated start**, address+R, data..., stop

Standard mode is 100 kHz; fast mode 400 kHz. Each byte takes 9 clocks.

## Pull-ups and speed

The bus's capacitance C (devices plus wiring) charges through the pull-up R. From 30% to 70% of the supply takes $0.8473\,RC$, and the standard allows at most 1000 ns at 100 kHz and 300 ns at 400 kHz, so

$$R \le \frac{t_r}{0.8473\,C}$$

## This sensor

A TMP102-style sensor returns two bytes: a 12-bit two's-complement temperature, left-justified, in units of 1/16 °C (0.0625 °C).
:::

::: example
## The sensor returns 0x19 then 0x80. What's the temperature?

::: solution
1. **Join the bytes.** Together they make 0x1980.
2. **Shift right by 4.**
   $$\begin{aligned} \text{0x1980} \gg 4 &= \text{0x198} \\ &= 408 \end{aligned}$$
3. **Check the sign.** Bit 11 is 0, so it's positive.
4. **Scale to degrees.**
   $$\frac{408}{16} = 25.5\ \text{°C}$$

**Answer:** 25.5 °C.
:::
:::

::: example
## A 400 kHz bus has 100 pF of capacitance. What's the largest pull-up that meets the 300 ns rise time?

::: solution
1. **Solve the rise time for R.**
   $$\begin{aligned} R &= \frac{300\ \text{ns}}{0.8473 \times 100\ \text{pF}} \\ &= 3.54\ \text{k}\Omega \end{aligned}$$
2. **Pick a standard value.** A standard 3.3 kΩ works.
3. **A bigger pull-up.** A 10 kΩ pull-up would only manage about 100 kHz on that bus.

**Answer:** 3.54 kΩ, so a standard 3.3 kΩ.
:::
:::

::: example
## Reading a 2-byte register from an I²C sensor at 100 kHz takes an address byte, a register byte, a repeated start with the address again, and two data bytes. About how long?

::: solution
1. **Count the byte bits.** Five bytes of 9 bits each (8 data plus acknowledge):
   $$5 \times 9 = 45\ \text{bit-times}$$
2. **Add the bus conditions.** About 3 more for the start, repeated start and stop make 48 bit-times.
3. **Time at 100 kHz.** Each bit-time is 10 µs:
   $$48 \times 10\ \mu\text{s} = 480\ \mu\text{s}$$
4. **At 400 kHz.** It's 120 µs.
5. **What it means.** Reading many sensors over I²C at 100 kHz adds up quickly.

**Answer:** about 480 µs at 100 kHz, and 120 µs at 400 kHz.
:::
:::

::: check
given: a = 0x1D | 0x48 | 0x50 | 0x68; d = 0 | 1
base: 16
answer: 2*a + d

## A device's address is {a:hex2}. What's the first byte after start to {d}? (0 write, 1 read)

::: right
Right. Address shifted left, direction in bit 0: {answer:hex2}.
:::

::: misses
- [a] The address shifts left one place to make room for the direction bit.
- [any] Not yet. $(\text{address} \ll 1)\ |\ \text{direction}$.
:::
:::

::: check
given: hi = 0x0C | 0x19 | 0x32 | 0x7F; lo = 0x00 | 0x80 | 0xF0
answer: floor((hi*256 + lo)/16)/16
unit: °C
tolerance: 0.01%

## A positive reading arrives as {hi:hex2}, {lo:hex2}. What's the temperature?

::: right
Right. The top 12 bits, in sixteenths: {answer} °C.
:::

::: misses
- [(hi*256 + lo)/16] Shift right by 4 first: the four low bits aren't part of the reading.
- [any] Not yet. $((hi \ll 8\ |\ lo) \gg 4)/16$.
:::
:::

::: check
given: T = -40 | -10 | -0.25 | -5.5
answer: round(T/0.0625) + 4096
tolerance: 0

## In 12-bit two's complement at 0.0625 °C per count, what raw value does {T} °C produce?

::: right
Right. {answer}: a negative count, plus 4096.
:::

::: misses
- [round(T/0.0625)] Negative values are stored as $2^{12}$ plus the value.
- [any] Not yet. Count = T/0.0625; negative counts are stored as 4096 + count.
:::
:::

::: check
given: f = 100 | 400; n = 2 | 4 | 6
answer: (9*n + 1)*1000/f
unit: µs
tolerance: 1%

## At {f} kHz, a transaction sends {n} bytes (each 9 clocks) plus about one clock for the start and stop. How long does it take?

::: right
Right. About {answer} µs.
:::

::: misses
- [8*n*1000/f] Each byte also has an acknowledgment clock: 9 clocks.
- [any] Not yet. Clocks over the clock rate.
:::
:::

::: check
given: t = 300 | 1000; C = 50 | 100 | 400
answer: t*1e-9/(0.8473*C*1e-12)/1000
unit: kΩ
tolerance: 1%

## The bus has {C} pF and must rise in {t} ns. What's the largest pull-up?

::: right
Right. $t_r/(0.8473 C)$ = {answer} kΩ.
:::

::: misses
- [t*1e-9/(C*1e-12)/1000] From 30% to 70% takes 0.8473 time constants.
- [any] Not yet. $R \le t_r/(0.8473 C)$.
:::
:::

::: check
kind: choice

## A read ends with the controller sending NACK after the last byte. Why?

- [ ] The data was wrong
- [x] To tell the device it's done reading, so it stops driving SDA
- [ ] Because the device didn't answer
- [ ] It's required only at 400 kHz

::: misses
- [1] NACK here isn't an error.
- [3] A missing device NACKs the address, the other way round.
- [4] It's part of every read.
:::
:::

::: check
kind: c
given: A = 0x18 | 0x29 | 0x4B | 0x6A
attach: tmp102 {A}
run: 0.05
expect: print = A

## A temperature sensor sits somewhere on the I²C bus. Scan every address from 0x08 to 0x77 and print the one that acknowledges.

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

int main(void) {
    print(0x48);
    return 0;
}
```

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

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

int main(void) {
    for (int a = 0x08; a < 0x78; a++) {
        I2C_ADDR = a;
        cmd(I2C_START_WRITE);
        int found = !(I2C_STATUS & I2C_NACK);
        cmd(I2C_STOP);
        if (found) print(a);
    }
    return 0;
}
```

::: right
Right. A device acknowledges its own address; everyone else stays quiet, and the controller sees a NACK.
:::
:::

::: check
kind: micropython
given: T = -12.5 | -0.75 | -20 | -3.25
attach: tmp102 0x48 | temp {T}
run: 0.05
expect: print = T

## The sensor at 0x48 is below freezing. Read it and print its temperature in °C, handling negative values.

```micropython starter
from machine import I2C

i2c = I2C(0)
raw = i2c.readfrom_mem(0x48, 0, 2)
print(((raw[0] << 4) | (raw[1] >> 4)) / 16)
```

```micropython solution
from machine import I2C

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

::: right
Right. Bit 11 is the sign; subtracting 4096 turns the 12-bit pattern into a negative count.
:::
:::

::: check
kind: parts
given: t = 300 | 1000; C = 50 | 200 | 400

## An I²C bus has {C} pF and must rise in {t} ns.

::: part
answer: t/(0.8473*C)
unit: kΩ
tolerance: 0.5%

### What is the largest pull-up?

::: misses
- [any] $t_r/(0.8473C)$.
:::
:::

::: part
answer: 3.3/(t/(0.8473*C))
unit: mA
tolerance: 0.5%

### What current does a device sink pulling it low?

::: misses
- [any] 3.3 V over the pull-up.
:::
:::
:::

::: check
kind: parts
given: hi = 25 | 50 | 6; lo = 128 | 16 | 0

## A temperature sensor returns bytes {hi} then {lo}; the reading is the 16-bit value shifted right by 4, in sixteenths of a degree, and positive here.

::: part
answer: floor((hi*256 + lo)/16)
tolerance: 0

### What is the 12-bit reading?

::: misses
- [any] (hi · 256 + lo) >> 4.
:::
:::

::: part
answer: floor((hi*256 + lo)/16)/16
unit: °C
tolerance: 0.5%

### What temperature?

::: misses
- [any] Divide by 16.
:::
:::
:::

::: explain
## How can many devices share one SDA wire without fighting over it?

::: model
SDA is open-drain: no device ever drives it high, they can only pull it low or let go, and a pull-up resistor raises it when everyone has let go. If two devices disagree, the one pulling low simply wins, and no current fights between outputs. That's what makes acknowledgment work: the receiver pulls the line low during the ninth clock while the sender lets go. It also lets several controllers detect each other: one that sends a 1 but sees a 0 knows another is talking, and backs off. Only the device whose address was sent takes part in a transaction, so the others ignore the bus until the next start.
:::
:::

::: practice

::: check
given: a = 0x20 | 0x76; d = 0 | 1
base: 16
answer: 2*a + d

## First byte to address {a:hex2}, direction {d}?

::: misses
- [any] $(a \ll 1)\ |\ d$.
:::
:::

::: check
given: hi = 0x0A | 0x2D; lo = 0x40 | 0xC0
answer: floor((hi*256 + lo)/16)/16
unit: °C
tolerance: 0.01%

## Temperature from {hi:hex2}, {lo:hex2}?

::: misses
- [any] Top 12 bits over 16.
:::
:::

::: check
given: t = 1000; C = 50 | 100 | 150 | 200 | 300 | 400
answer: t*1e-9/(0.8473*C*1e-12)/1000
unit: kΩ
tolerance: 1%

## Largest pull-up for {C} pF at 100 kHz?

::: misses
- [any] $t_r/(0.8473 C)$.
:::
:::
:::
