Serial Buses: UART, I2C, and SPI
Three buses, three philosophies: UART trusts the clock, SPI trusts the chip select, I2C trusts everyone — which is why I2C hangs.
🎯 By the end you'll understand
Why a UART works with no shared clock at all, and the arithmetic that says how far apart two baud rates may drift before the last bit of every byte lands in the wrong place. What CPOL and CPHA actually describe, and why a chip select is a state machine reset rather than a mere enable. How I2C's wired-AND bus makes acknowledgement, clock stretching, arbitration, and repeated start possible with two wires and one resistor pair — and how the same design lets a single confused slave hold the bus for everyone, forever. You will size Beacon's 4.7 kΩ pull-ups from the specification's rise-time limit and its 3 mA sink current, read a real transaction off a waveform, and implement the nine-clock recovery that unsticks a bus without a power cycle.
KEY INSIGHTA bus is a shared assumption
The tag wakes, reads the sensors, advertises, sleeps. Thirty thousand times it works. Then a brown-out resets the chip halfway through a six-byte read, and the tag never reports again. The battery is fine, the firmware boots, the log even says SAMPLE — and then nothing, forever, until someone disconnects the battery. On the analyser, SDA is a flat line at zero volts and SCL is idle high. The humidity sensor is patiently waiting to send bit 3 of a byte nobody asked for.
Every serial bus is a set of assumptions that both ends hold in their heads at the same time — where the byte started, whose turn it is, which register is selected, how fast the clock ticks. The wires carry only levels; the assumptions are software, and software gets reset. UART, SPI, and I2C differ mainly in how much shared assumption they require and what happens when the two ends disagree. UART requires the least: two independent clocks that merely agree on a rate. SPI requires a little more but gives the master a hard reset in the form of the chip select. I2C requires the most — a shared, bidirectional, wired-AND line where every participant must play by the rules — and pays for its two-wire elegance with the one failure mode this lesson exists to teach: a slave that is mid-byte when the master reboots holds the data line low and no amount of master-side software will fix it, because the master's problem is that it is now the only one who thinks the transaction is over.
Ask of any bus: who drives, when, and how does either end resynchronise after a reset? UART resynchronises every byte at the start bit. SPI resynchronises every transaction at the falling edge of the chip select. I2C has no resynchronisation primitive at all — a START is only recognised by a slave that is not currently in the middle of shifting out a byte — which is why the recovery procedure is not a message but a physical act: nine clock pulses to walk the stuck slave to the end of its byte, then a STOP.
COMPARISONThree philosophies, three wire counts
| UART | SPI | I2C | |
|---|---|---|---|
| Wires for 2 sensors | 4 (a pair each) | 5 (3 shared + 2 CS) | 2 |
| Clock | None on the wire; both ends generate their own | Master drives SCLK | Master drives SCL, but a slave may hold it low |
| Typical rate | 115.2 kbaud – 3 Mbaud | 1 – 80 MHz | 100 / 400 kHz (1 MHz and 3.4 MHz modes exist) |
| Addressing | None — the wire is the address | A chip-select pin per device | 7-bit address in the first byte |
| Error detection built in | Framing + optional parity | None whatsoever | Per-byte acknowledgement |
| Resynchronisation | Every byte, at the start bit | Every transaction, at CS falling | None. Hence the recovery procedure. |
| Fails by | Baud mismatch, missing common ground | Mode mismatch, CS glitch, no error signalling at all | Weak pull-ups, address clash, a slave stuck mid-byte |
| Use it for | Consoles, GPS, cellular and Wi-Fi co-processors, anything that talks in streams | Displays, flash, ADCs, radios — anything fast | Sensors, EEPROMs, PMICs — anything slow, small, and numerous |
The interesting column is the second-to-last. SPI's total absence of error detection is not an oversight; it is the price of speed and simplicity, and it means an SPI driver must verify a device by reading back a known register — the "who am I" byte exists for exactly this reason. I2C's per-byte acknowledgement is genuinely useful: a NACK on the address byte is a definitive "nobody at that address answered", which is the single most useful diagnostic in bring-up (6.1). UART's framing error tells you the baud rate is wrong or the ground is bad, which is nearly always what has happened.
CORE CONCEPTUART: trusting a clock you cannot see
A UART sends a byte as a start bit (a low), the data bits (usually eight, least significant first), an optional parity bit, and one or two stop bits (high). There is no clock on the wire. The receiver watches for the falling edge of the start bit, then samples each subsequent bit in the middle of its expected bit period, using its own locally generated clock. The whole protocol rests on both ends agreeing on the bit period to within a fraction of a bit — and the agreement only has to last for one frame, because the next start bit resynchronises everything.
In an 8N1 frame the receiver samples the start bit at 0.5 bit times and the stop bit at 9.5 bit times after the falling edge. If the receiver's bit period is off by a fraction e, the accumulated error at the stop bit is 9.5 e bit times, and sampling lands outside the correct bit when that exceeds 0.5. So |e| < 5.3 % in the ideal case — and that budget is shared between the two ends, must absorb the transmitter's own error, and shrinks further with slow edges on a capacitive line. The practical rule that engineers use is ±2 % per end, ±3 % if you like living dangerously, and it explains why an 8 MHz crystal cannot cleanly produce 115200 baud with an integer divider while 11.0592 MHz can.
The ESP32-C3's UART divides the 80 MHz APB clock (or, for use in light sleep, a slower always-on source) by a divisor that has an integer and a fractional part, so baud error is not usually your problem on this chip: 80 MHz ÷ 115200 = 694.44, and the fractional divider gets close enough that the error is a rounding artefact. Your problem is the device at the other end, which may be a GPS module with a 16 MHz oscillator, or a cheap USB-serial adapter. When a link produces occasional garbage bytes rather than complete nonsense, suspect the rate; when it produces complete nonsense, suspect the wiring; when it produces nothing, suspect the ground.
Three practical points that matter more than the framing details:
- Flow control is not optional above a few hundred kilobaud. Hardware RTS/CTS gives the receiver a wire with which to say "stop, my buffer is full". Without it, a 3 Mbaud stream into a receiver that was busy servicing an interrupt (3.4) loses bytes, and the loss looks exactly like a baud error. Software XON/XOFF exists and is fine for text; it is useless for binary data, which will eventually contain the flow-control bytes.
- The ESP32-C3's console is not necessarily a UART. Beacon's build sets
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG(3.2), soprintfgoes to the native USB peripheral on GPIO18/19 and no UART is involved. The ROM's boot banner, however, is emitted on UART0 at 115200 baud regardless — which is why a board with nothing connected to GPIO20/21 still pulses those pins at every reset (3.3), and why a "silent" board can be debugged with a USB-serial adapter clipped onto the test points. - A UART with a hardware FIFO changes your ISR design. The peripheral interrupts when the receive FIFO passes a threshold or when the line has been idle for a configured time. That means your handler is not per-byte — it drains a block — which is the difference between an interrupt every 87 µs and one every few milliseconds.
HOW IT WORKSSPI: trusting the chip select
SPI is a shift register stretched across a cable. The master drives a clock; on each clock edge a bit leaves the master on MOSI and a bit leaves the slave on MISO. It is inherently full duplex — every transaction sends and receives the same number of bits, and a "read" is a write of dummy bytes whose returned bits you happen to care about. There is no addressing, no acknowledgement, no error detection and no defined maximum speed; the datasheet of the slowest device on the bus sets the clock.
| Mode | CPOL (idle clock) | CPHA | Data is sampled on | Common users |
|---|---|---|---|---|
| 0 | 0 — idles low | 0 | The leading (rising) edge | The overwhelming default: most sensors, SD cards, SPI flash |
| 1 | 0 — idles low | 1 | The trailing (falling) edge | Some ADCs and DACs |
| 2 | 1 — idles high | 0 | The leading (falling) edge | Rare |
| 3 | 1 — idles high | 1 | The trailing (rising) edge | Some displays, some IMUs (the LIS2DH12 in SPI mode among them) |
CPHA is the field that causes the trouble, because its definition is about which clock edge samples, and it is easy to read a datasheet timing diagram and pick the wrong one. The symptom is characteristic and worth memorising: a mode-mismatched SPI link returns your data shifted by one bit, so a WHO_AM_I of 0x33 reads back as 0x66 or 0x19. If your first SPI read returns a value that is exactly double or exactly half the expected one, stop debugging the wiring and change CPHA.
The chip select deserves more respect than it usually gets. It is not an enable line; it is the slave's transaction boundary. The falling edge tells the slave "a new command starts now, discard whatever bit position you were in", and the rising edge tells it "commit". Three consequences follow. A CS line that floats at reset — before the MCU has configured its pins (3.3) — can be interpreted as a transaction, so every CS gets an external pull-up to its idle level. A CS that is toggled by software between bytes when the device expects one continuous frame will reset the device's internal address pointer, so the driver must keep CS asserted across a multi-byte read; in ESP-IDF this is the difference between one spi_device_transmit() of six bytes and six of one byte. And a glitch on CS — from a long unterminated trace or a nearby switching node — desynchronises the shift register with no error indication at all, which is why SPI on a cable is a bad idea and SPI on a PCB is a good one.
On the ESP32-C3, an SPI master routed through the IO_MUX pins reaches the highest documented clock; routing the same signals through the GPIO matrix (3.3) adds propagation delay and the datasheet's tables cap the usable frequency lower. For Beacon it is moot — there is no SPI device on the board — but the general rule stands: when a bus is fast, its pins are not free choices. That is a schematic decision made in Stage 5, forced by a firmware constraint you learn here.
Prefer I2C when the part is slow (a few kilobytes per second), when board area and pin count matter, and when you might add a second identical part later (many sensors have a selectable address pin). Prefer SPI when the data rate is above roughly 400 kbit/s, when you need deterministic timing without clock stretching, or when the part is a display or a memory. Beacon's sensors produce six bytes a minute; I2C is not a compromise here, it is the correct answer, and the two-wire saving is a real one on a 35 × 25 mm four-layer board (R8).
CORE CONCEPTI2C: trusting everyone
I2C's whole design follows from one electrical decision: no device ever drives the bus high. Every device connects to SDA and SCL through an open-drain output that can only pull low, and a pair of pull-up resistors supplies the high level. The bus is a wired-AND: the line is high only if every device lets go of it. That single property buys four features that would otherwise need extra wires.
| Feature | How wired-AND provides it | What it means for your driver |
|---|---|---|
| Acknowledgement | After eight bits the master releases SDA and clocks a ninth time; the addressed slave pulls SDA low to say "got it" | A NACK on the address byte means nobody answered — the most valuable single diagnostic on the bus. A NACK on a data byte can mean "busy" and is not always fatal. |
| Clock stretching | A slave that needs time holds SCL low; the master, which can only release SCL and watch, must wait | Your master's timeout must be longer than the slowest legitimate stretch. Some devices stretch for milliseconds after a write. |
| Arbitration | Two masters starting together both write; the one that writes a 1 but reads a 0 has been outvoted and withdraws, mid-byte, without corrupting the winner's message | Multi-master works but is rare and worth avoiding. If your design has two masters, it probably wants two buses. |
| Repeated START | A START without an intervening STOP keeps the bus owned, so a write-then-read is atomic against other masters | Register reads on most sensors are "write the register pointer, repeated START, read" — one call, not two. |
Addressing. The first byte after START is seven address bits followed by a read/write bit, so the SHT40's documented address of 0x44 appears on the wire as 0x88 for a write and 0x89 for a read. Analysers and datasheets disagree constantly about whether an address is quoted 7-bit or 8-bit ("0x44" versus "0x88"), and a factor-of-two confusion here is the most common bring-up error there is. Beacon's two devices are 0x44 (SHT40) and 0x19 (LIS2DH12, with its SA0 pin high), which do not collide — a check you must do on paper before the schematic, because two parts with the same fixed address on one bus is a board respin.
Two constraints bracket the resistor. Minimum: the specification requires a device to sink 3 mA while holding the line below 0.4 V, so R ≥ (3.3 V − 0.4 V) ÷ 3 mA ≈ 967 Ω. Maximum: the line rises as an RC, and the 10–90 % rise time is tr ≈ 0.847 × R × C. Fast-mode (400 kHz) allows 300 ns, and the specification caps total bus capacitance at 400 pF. With Beacon's short traces and two small parts, budget C ≈ 50 pF: R ≤ 300 ns ÷ (0.847 × 50 pF) ≈ 7.1 kΩ. Anything from about 1 kΩ to 7 kΩ is legal; 4.7 kΩ sits comfortably in the middle, giving tr ≈ 0.847 × 4700 × 50 pF ≈ 199 ns and a sink current of only 0.62 mA. That is the number chosen in Lesson 2.1 and fixed in the canon.
Now the number that ends arguments: the ESP32-C3's internal pull-ups are roughly 45 kΩ. Put them in the same formula and tr ≈ 0.847 × 45,000 × 50 pF ≈ 1.9 µs. At 100 kHz a bit is 10 µs long and a 1.9 µs rise, while illegal, often works. At 400 kHz a bit is 2.5 µs and the line has barely left the ground before it is sampled. This is the precise mechanism behind the most common I2C story on the forums — "it works at 100 kHz but not at 400 kHz" — and the fix is never in software. Set .flags.enable_internal_pullup = false and put real resistors on the board.
#include "driver/i2c_master.h" static const char *TAG = "beacon"; static i2c_master_bus_handle_t bus; i2c_master_dev_handle_t sht40, accel; esp_err_t bus_init(void) { i2c_master_bus_config_t bcfg = { .i2c_port = I2C_NUM_0, .sda_io_num = 6, .scl_io_num = 7, .clk_source = I2C_CLK_SRC_DEFAULT, .glitch_ignore_cnt = 7, // ignore pulses shorter than 7 source-clock cycles .flags.enable_internal_pullup = false, // 45 kΩ gives t_r ≈ 1.9 µs — illegal at 400 kHz }; ESP_RETURN_ON_ERROR(i2c_new_master_bus(&bcfg, &bus), TAG, "bus"); i2c_device_config_t d = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .scl_speed_hz = 400000 }; d.device_address = 0x44; ESP_RETURN_ON_ERROR(i2c_master_bus_add_device(bus, &d, &sht40), TAG, "sht"); d.device_address = 0x19; ESP_RETURN_ON_ERROR(i2c_master_bus_add_device(bus, &d, &accel), TAG, "acc"); // Bring-up habit: probe before you trust. ESP_ERR_NOT_FOUND == nobody ACKed. ESP_RETURN_ON_ERROR(i2c_master_probe(bus, 0x44, 50), TAG, "no SHT40"); return i2c_master_probe(bus, 0x19, 50); } // Two devices, two transaction SHAPES — because the parts differ, not the bus. esp_err_t accel_read_regs(uint8_t reg, uint8_t *out, size_t n) { uint8_t ptr = reg | (n > 1 ? 0x80 : 0); // ST parts: bit 7 = auto-increment return i2c_master_transmit_receive(accel, &ptr, 1, out, n, 20); // repeated START } esp_err_t sht40_start_measure(void) { uint8_t cmd = 0xFD; // high-precision T + RH return i2c_master_transmit(sht40, &cmd, 1, 20); // STOP, then wait 8.5 ms (3.6) }
The comment on the last block is the lesson inside the lesson. The accelerometer supports a repeated START, so a register read is one atomic transaction. The SHT40 does not work that way: it takes a command, releases the bus, spends up to 8.2 ms converting, and NACKs anything addressed to it in the meantime. Two devices on the same two wires need two different transaction shapes, and a driver that assumes all sensors read alike will produce exactly one working sensor.
SEE ITI2C transaction decoder: read the trace before you write the driver
Build a transaction against one of Beacon's two devices, inject a fault, and read what the analyser would show. The waveform is drawn from the bytes you selected, with the acknowledgement bits marked by who drives them. Every fault here is one somebody has spent a day on: an address that nobody answers, a read issued before the sensor finished measuring, a slave that stretches the clock past your timeout, weak pull-ups that turn a 400 kHz bus into noise, and the reset-mid-byte that leaves SDA held low forever.
Two experiments are worth doing in order. First, SHT40 with a read and no delay: the sensor is still converting, it NACKs its own address, and the driver returns an error rather than data — which is the good outcome, because the alternative is a driver that pretends. Second, the reset-mid-byte, then press Recover: the nine clocks walk the slave through the rest of its byte until it releases SDA, and the STOP puts everyone back at the start. Notice that recovery does not need the slave to be well-behaved or even to understand what happened. It only needs clocks.
IN PRACTICEThe stuck bus and the nine clocks
Here is the failure in full, because it is the one that will bite you. A slave has been addressed for a read and is shifting out a byte. Between two clock pulses the master resets — a brown-out, a watchdog, a debugger, a battery jolt. The master comes back and knows nothing. The slave still holds SDA low for whichever bit of its byte it was presenting. The master issues a START, but a START is defined as SDA falling while SCL is high, and SDA is already low: the condition cannot be generated. Every subsequent transaction fails, and the driver's timeout fires forever. A power cycle fixes it, which is why the bug is so often "solved" by adding a reset button.
Detect it
At start-up, before the first transaction, read the two pins as inputs. SCL high and SDA low means a slave is mid-byte. SDA and SCL both low means something is holding the whole bus — usually a short or an unpowered device clamping through its protection diodes.
Clock nine times
Configure SCL as an open-drain output and toggle it nine times at a legal rate. Each pulse advances the stuck slave one bit. Nine is the number because eight bits plus the acknowledgement slot is the longest it can still owe you. Most slaves release after fewer.
Generate a STOP
With SCL high, take SDA low — strictly that falling edge is a START, which is harmless on an idle bus — then release SDA. It is the rising edge of SDA while SCL is high that is the STOP; every device on the bus now considers itself idle and is listening for a START again.
Verify, then reinitialise
Read the pins again. If SDA is still low after nine clocks, the problem is not a mid-byte slave — it is hardware, and no amount of clocking will fix a short. Otherwise hand the pins back to the I2C peripheral and re-run the probe.
#define PIN_SDA 6 #define PIN_SCL 7 bool i2c_bus_is_stuck(void) { return gpio_get_level(PIN_SDA) == 0 && gpio_get_level(PIN_SCL) == 1; } esp_err_t i2c_bus_recover(void) { // Take the pins back from the peripheral as open-drain outputs (never push-pull: // driving SDA high against a slave that is pulling it low is a short, 3.3 V through // two transistors, and the pad is what gives up first.) gpio_config_t io = { .pin_bit_mask = (1ULL << PIN_SDA) | (1ULL << PIN_SCL), .mode = GPIO_MODE_INPUT_OUTPUT_OD, .pull_up_en = GPIO_PULLUP_ENABLE }; ESP_ERROR_CHECK(gpio_config(&io)); gpio_set_level(PIN_SDA, 1); // release SDA: let the slave own it for (int i = 0; i < 9; i++) { // 8 data bits + the ack slot gpio_set_level(PIN_SCL, 0); esp_rom_delay_us(5); // ~100 kHz: gentle and legal gpio_set_level(PIN_SCL, 1); esp_rom_delay_us(5); if (gpio_get_level(PIN_SDA)) break; // it let go — stop early } gpio_set_level(PIN_SDA, 0); esp_rom_delay_us(5); // STOP: SDA low… gpio_set_level(PIN_SCL, 1); esp_rom_delay_us(5); gpio_set_level(PIN_SDA, 1); // …released while SCL is high if (!gpio_get_level(PIN_SDA)) return ESP_FAIL; // still low: it is hardware return bus_init(); // hand the pins back, re-probe }
ESP-IDF 5.x also offers i2c_master_bus_reset(), which asks the peripheral to do the equivalent, and you should try it first because it is one line. Keep the bit-banged version anyway: it works when the peripheral itself is confused, it is the same code on every MCU you will ever use, and writing it once teaches you what the nine means. The important design decision is not which function you call — it is where you call it from. Beacon runs the stuck check once at every boot, before the first probe, and treats a recovery event as a fact worth recording in the buglog partition (3.9). A bus that needed recovery is a symptom of something else, and the count of recoveries per unit over the 30-day pilot is one of the numbers Stage 6 will actually look at.
The tempting mistake is to configure SDA as a push-pull output and drive it high to "un-stick" it. The slave is holding it low with a transistor to ground. Your pad would be sourcing current into that transistor with nothing but the two devices' on-resistances between 3.3 V and ground — tens of milliamps through a pad rated for a few, for as long as the standoff lasts. It sometimes appears to work, which is the worst outcome, because the device that got weakened is now a field failure with no story. Open-drain, always: on this bus, "high" means "let go".
BEACONBeacon's bus, sized and instrumented
Everything above lands on one two-wire bus with two devices. The specification is short, which is the point — a bus you can describe completely is a bus you can debug.
| Parameter | Value | Where it came from |
|---|---|---|
| Pins | SDA = GPIO6, SCL = GPIO7 | Non-strapping, non-RTC, free on the MINI-1 module (3.3) |
| Devices | SHT40 at 0x44, LIS2DH12 at 0x19 | Canon. No collision; checked on paper before the schematic. |
| Pull-ups | 2 × 4.7 kΩ to 3V3 | Between the 967 Ω sink limit and the 7.1 kΩ rise-time limit; tr ≈ 199 ns at an estimated 50 pF |
| Speed | 400 kHz | Six bytes per minute does not need it; the reason is energy. A transaction that takes 175 µs instead of 700 µs is 525 µs less awake time at 40 mA, every wake, against R1. |
| Transfer timeout | 20 ms per call | Longer than any legitimate stretch by these two parts, short enough that a stuck bus is detected inside one active window (3.4) |
| Recovery | Stuck-check + nine clocks at every boot | This lesson. Recoveries are counted and stored. |
The milestone artefact. Stage 3's Beacon milestone requires a logic-analyser trace of each bus, and it is worth being specific about what a good trace is. Sample at least four times the bus clock — 2 MS/s for a 400 kHz bus is comfortable, and cheap eight-channel analysers do 24 MS/s — and capture SDA, SCL, and one spare channel that your firmware toggles at the start and end of the transaction (3.4's GPIO instrumentation trick). That third channel converts a picture of the bus into a picture of your code's relationship with the bus: you can see the software overhead between the driver call and the first START, the gap where the 8.5 ms measurement wait sits, and whether the transaction really ended where you think it did. Save the capture. When the same read fails on unit 17 of the pilot, the known-good trace is what turns a mystery into a comparison.
(1) One I2C master bus at 400 kHz on GPIO6/7, internal pull-ups explicitly disabled, external 4.7 kΩ fitted. (2) Both devices added as handles with 7-bit addresses and a 20 ms per-transfer timeout. (3) Every boot runs a stuck-bus check and, if needed, the nine-clock recovery, and records the event. (4) i2c_master_probe() on both addresses before any driver runs, so "sensor missing" is distinguished from "sensor misbehaving" from the very first log line. (5) A saved analyser capture of a healthy wake window, checked into the repository next to the firmware.
WEAKNESSWhere this bites
It is almost always the pull-ups, and the arithmetic is unforgiving: with the ESP32-C3's internal ~45 kΩ and a modest 50 pF of bus capacitance, the line takes about 1.9 µs to rise. At 100 kHz that is a fifth of a bit and often survives; at 400 kHz the bit is 2.5 µs long and the receiver samples a line that is still climbing. The forum answer — lower the speed — hides the defect and leaves you with a bus that has no margin for a longer trace, a third device, or a cold day. Fit 4.7 kΩ resistors, disable the internal pull-ups explicitly in the bus config, and look at the edges on a scope: a healthy 400 kHz I2C rising edge is a visibly exponential curve that reaches the rail well before the clock's rising edge, and a sick one is a lazy ramp that never quite gets there.
A NACK is information, and its meaning depends entirely on where in the transaction it appeared. NACK on the address byte: nobody at that address is powered, present, and awake — check the schematic, the address pin, and the supply before touching the code. NACK on a data byte during a write: the device is busy or rejects the command; an EEPROM does this for its entire write cycle, and the correct response is to poll until it acknowledges. NACK from the master on the last byte of a read: that one is mandatory and correct — it is how the master says "stop sending". Drivers that lump all three into "I2C error" throw away the diagnosis, and drivers that ignore NACKs entirely return whatever was left in the buffer, which is how a dead sensor reports −45.00 °C for six weeks (3.6).
I2C was designed to connect chips on one board — the "IC" in the name is not decoration. Capacitance is roughly 1 pF per centimetre of ribbon cable per conductor, so a metre of cable is on the order of 100 pF and blows the rise-time budget before you have added the devices; the spec's 400 pF ceiling arrives faster than anyone expects. Cables also pick up noise on a bus with no differential signalling, no error detection beyond the acknowledgement, and a stuck-low failure mode that requires a physical recovery. If a sensor must live at the end of a cable, use a bus designed for it (RS-485, CAN, or a UART at a modest rate), or put a small MCU next to the sensor and send it messages. Beacon's I2C runs a few centimetres on a 35 × 25 mm board, which is exactly the environment the bus was invented for.
KEY INSIGHTHow this connects
- Resistors in Anger: Dividers, Pull-Ups, and Current Limits (2.1) — the 4.7 kΩ pull-ups were sized there from rise time and sink current; here you see the bit they are trying to keep square.
- Interrupts, Polling, and the Latency Budget (3.4) — a long interrupt handler stalls the transaction you just learned to read, and the driver's 20 ms timeout is what turns that stall into an error code instead of a hang.
- Writing Drivers and Hardware Abstraction (3.6) — next: these transactions become a driver with initialisation sequences, timing requirements, CRC checks, bounded retries, and an error path that does not lie.
- Debugging Firmware (3.9) — the logic analyser is promoted from a lesson prop to the ground truth you reach for when logs and intuition disagree.
- Routing for Signal Integrity (5.7) — bus capacitance stops being an estimate and becomes a consequence of trace length, layer stack, and where you put the pull-ups.
The transferable habit: before writing a line of driver code for a new part, draw the transaction on paper — START, address, R/W, which bytes, who acknowledges each one, repeated START or STOP — and then capture the real thing on an analyser and compare. Ninety per cent of "the sensor doesn't work" is a mismatch between those two pictures, and the mismatch is always visible.
GLOSSARYKey terms introduced
- Open-drain / wired-AND
- An output that can only pull a line low, with a pull-up resistor supplying the high level. The line is high only if every device releases it, which is what makes acknowledgement, clock stretching, and arbitration possible on two wires.
- ACK / NACK
- The ninth clock of every I2C byte, during which the receiver pulls SDA low to acknowledge. Its meaning depends on position: on an address it means "present"; on a write data byte it may mean "busy"; from the master on the last read byte it means "done".
- Clock stretching
- A slave holding SCL low to make the master wait. Legal, common after writes, and the reason a master's timeout must exceed the slowest device's stretch.
- Repeated START
- A second START without an intervening STOP, keeping ownership of the bus so a write-then-read pair cannot be interleaved by another master. The normal shape of a register read.
- Bus recovery
- Nine clock pulses on SCL followed by a STOP, used to walk a slave that is stuck mid-byte to the end of its transfer and release SDA. Must be done with open-drain pins.
- Rise time (tr)
- The 10–90 % time for a pulled-up line to reach the rail, ≈ 0.847 × R × C. Capped at 300 ns in fast mode, which sets the maximum pull-up resistance for a given bus capacitance.
- CPOL / CPHA
- The two bits that define the four SPI modes: the clock's idle level, and whether data is sampled on the leading or trailing edge. A mismatch shifts every byte by one bit.
- Baud-rate error
- The fractional difference between two UART bit periods. It accumulates over a frame; sampling the stop bit at 9.5 bit times means the total budget is about 5 %, shared between both ends.
ACTIVE RECALLCheck your understanding
Answer in your own words first, then reveal.
1A prototype talks to the SHT40 reliably at 100 kHz. Raised to 400 kHz, roughly one transaction in three fails. The board has no external pull-up resistors and the driver enables the internal ones. Diagnose it with numbers, and say why lowering the speed is the wrong fix.›
The internal pull-ups are about 45 kΩ. With an estimated 50 pF of bus capacitance the rise time is tr ≈ 0.847 × 45,000 × 50 pF ≈ 1.9 µs. At 100 kHz a bit lasts 10 µs, so a 1.9 µs ramp still settles before the line is sampled — illegal against the 300 ns fast-mode limit, but survivable. At 400 kHz a bit is 2.5 µs, so the line is sampled while it is still rising and the value read depends on noise, temperature, and how many devices are listening. Lowering the speed hides the defect: the bus then has no margin for a longer trace, an extra device, or a unit at the high end of the capacitance distribution, and the failures come back in the field. The fix is 4.7 kΩ external resistors and .flags.enable_internal_pullup = false, which brings tr to about 199 ns, inside spec with margin.
2After a brown-out during a sensor read, a tag never talks to its sensors again until the battery is pulled. On the analyser SDA is low and SCL is high. Explain the mechanism and the fix, and say why driving SDA high would be a mistake.›
The slave was shifting out a byte when the master reset. It is still holding SDA low for the bit it was presenting, waiting for clocks that never come. The master cannot issue a START, because a START is SDA falling while SCL is high and SDA is already low, so every transaction times out. The fix is bus recovery: take the pins as open-drain outputs, release SDA, clock SCL nine times (eight data bits plus the acknowledgement slot — the most the slave can still owe), then generate a STOP by taking SDA low and releasing it while SCL is high. Driving SDA high with a push-pull output would fight the slave's low-side transistor: 3.3 V through two on-resistances, tens of milliamps through pads rated for a few, potentially damaging a part in a way that shows up later as an unexplained field failure. On this bus, "high" only ever means "let go".
3Why does Beacon read the LIS2DH12 with a single write-then-repeated-START-then-read transaction, but read the SHT40 as a write, a delay, and a separate read?›
Because the parts differ, not the bus. The accelerometer is a register file: you write the register pointer, issue a repeated START to turn the bus around without releasing it, and read as many bytes as you want (with bit 7 of the pointer set for auto-increment). The repeated START makes the pair atomic against any other master and is the standard shape for register-based devices. The SHT40 is a converter: the 0xFD command starts a measurement that takes up to 8.2 ms, during which the sensor NACKs anything addressed to it. Holding the bus for that time with a repeated START would be legal but wasteful, and reading immediately gets a NACK. So the driver sends the command, releases the bus with a STOP, waits 8.5 ms with a one-shot timer (3.3) rather than a busy-wait, and then reads six bytes: temperature, humidity, and a CRC after each. A driver that assumes one shape for both parts works with exactly one of them.
4A new sensor connects over SPI. The first read of its WHO_AM_I register returns 0x66; the datasheet says 0x33. What is almost certainly wrong, and what would you check next if fixing it did not help?›
0x66 is 0x33 shifted left by one bit, which is the signature of a clock-phase mismatch: the master is sampling on the wrong edge, so every bit arrives one position out. Change CPHA — try mode 3 if you configured mode 0, or vice versa. If that does not fix it, work down the list of SPI's silent failures. Is the chip select actually reaching the device, and is it staying low for the whole two-byte transaction rather than toggling between bytes? Is MISO connected to MISO (some datasheets label the pins SDO/SDI, and the two conventions have opposite meanings)? Is the clock within the part's maximum? Remember that SPI has no acknowledgement and no error detection, so it will happily return 0xFF or 0x00 forever without complaining — reading a known constant like WHO_AM_I is the only way to know the link works at all, which is why every driver in this course starts with that read.