Hardware Interfacing

A receiver reads each bit once, at one instant, and the bit must have settled by then. A UART survives about 4.6% of clock mismatch between its two ends. An I²C line must rise before its clock falls again. SPI data must come back within half a clock.

Pick a link, then turn its knob until the receiver reads the wrong byte. Then we build, piece by piece, the voltage levels, the inputs, the loads, the ADC and each bus, up to a whole board bring-up.

You need Lesson 1's pins and buses, Ohm's law and binary numbers. We build the rest from zero.

Lesson 4 of the Embedded Systems series. Before: Lesson 3, Hardware Design. Next: Lesson 5, Embedded Linux. The hands-on track is Firmware from Zero.

Read the byte at the right instant

0.0%

Illustrative toys. UART: 8N1 frames sent back to back; the receiver finds the start edge within 1/16 of a bit and samples each bit once in its middle. I²C: fast mode on a 200 pF bus, a controller that releases SCL for 1.2 µs without waiting for it. SPI: a 12 ns device output delay, 1 ns of wire each way and a 5 ns setup time. The 300 ns rise limit and the 0.7 VDD threshold are NXP UM10204's.

Chapter 0

A Bit Is Read at One Instant

Watch a receiver turn a voltage into a bit, and find the two things that must be true at that instant

You wire a GPS module to the board, and the console prints garbage. A flash chip on SPI returns an ID that is almost right. An I²C sensor answers on the bench and fails inside the box. Three buses fail in three ways, for one reason.

A wire carries a voltage, not a bit. The receiver looks at the voltage at one instant, called the sampling instant, and compares it with its thresholds. Above the high threshold it reads 1; below the low threshold it reads 0. Between the two, the reading is not defined.

Sample one byte off a wire

The blue trace is the byte 0x41 on a wire with rounded edges. In the grey band the input reads neither 0 nor 1. Slide the sampling instant, then slow the edges.

50% of a bit
20% of a bit

Illustrative wire: each edge is an RC curve. The thresholds are the STM32F103's guaranteed input levels at 3.3 V (1.16 V and 1.83 V, datasheet).

So every link has two contracts. The electrical contract: a high must be above the receiver's high threshold, and a low below its low threshold. The timing contract: the sampling instant must land after the edge has settled and before the next edge starts.

The device shows both. With edges at 20% of a bit, any instant from 21% to the end of the bit reads 0x41. Slow the edges to 60% and the window shrinks to the last 37% of each bit. Every chapter of this lesson is one of these two contracts on one kind of wire.

Symptom: one bus works at low speed and fails at high speed.

Measure: put a scope on the wire and look at one bit. Check its levels against the thresholds, then check where the edges end.

Fix: fix the contract that breaks: the levels (Chapter 1) or the timing (Chapters 5 to 7).

The road

  1. Levels: what counts as high, and 5 V into a 3.3 V pin.
  2. Debounce: a button bounces; an RC or a counter waits it out.
  3. Loads: switch a motor with a MOSFET, and catch the coil's kick.
  4. ADC: the sampling capacitor must settle; slow sampling folds frequencies.
  5. UART: two clocks must agree. The hero's first link.
  6. I²C: address, acknowledge, stretch. The hero's second link.
  7. SPI: four modes and a round trip. The hero's third link.
  8. USB and radio: leave the board.
  9. Showcase: bring up a sensor board, fault by fault.
  10. Field guide: the numbers, the bug table and the code.
A link reads correct bytes when it samples in the middle of each bit, and wrong bytes when it samples early. What is wrong?

Chapter 1

Agree on What Counts as High

Compare a driver's guaranteed levels with a receiver's thresholds, and find the margin, or the damage

Every datasheet gives two pairs of numbers. The driver guarantees its output: at least VOH when high, at most VOL when low, at a stated current. The receiver promises to read 1 above VIH and 0 below VIL. A link works when the guarantees clear the promises with room to spare.

That room is the noise margin: how much noise the wire can pick up before a bit flips. Call the high margin NMH:

Say it aloud

N-M-H equals V-O-H minus V-I-H.

NMH
N-M-H the high noise margin, in volts. Below zero, a guaranteed high can read as low or as nothing.
VOH
V-O-H the lowest voltage the driver promises when it outputs a 1, at its rated current.
VIH
V-I-H the lowest voltage the receiver promises to read as a 1.
In plain words

Take the driver's weakest high, V-O-H. Subtract the receiver's highest threshold, V-I-H. What is left, N-M-H, is the room for noise. The low margin is the mirror: V-I-L minus V-O-L.

With numbers

An STM32F103 pin promises V-O-H = 2.4 V at 8 mA. An STM32 input needs V-I-H = 1.83 V: N-M-H = +0.57 V. A 74HC input at 4.5 V needs 3.15 V: N-M-H = 2.4 − 3.15 = −0.75 V. That link has no margin at all.

Connect a driver to a receiver

Left ladder: where the driver promises its high and low. Right ladder: what the receiver reads. Pick a pair and look at the gaps, and at the red line.

STM32F103x8 datasheet, Tables 5, 34 and 35: VOH ≥ 2.4 V and VOL ≤ 0.4 V at 8 mA; at most 3.6 V on a standard pin and 5.5 V on a 5 V tolerant one. TI SN74HC04 and SN74HCT04 datasheets at 4.5 V and 25 °C: VOH 3.98 V at 4 mA.

Two fixes cover most mismatches. Going up, from 3.3 V to 5 V, use a receiver with TTL levels. A 74HCT gate on 5 V reads 1 above 2.0 V. Going down, from 5 V to 3.3 V, use a 5 V tolerant pin (marked FT in the pin table), or shift the level first.

For shared lines, use open-drain outputs. A push-pull output drives the line high or low. An open-drain output can only pull it low, or let go. A pull-up resistor makes the high, so the high is whatever supply the resistor goes to. One small MOSFET with a pull-up on each side then shifts a line both ways between 3.3 V and 5 V.

Symptom: a 5 V module on a standard pin works for weeks, then the pin dies.

Measure: compare the module's high with the pin's absolute maximum: 3.98 V against VDD + 0.3 = 3.6 V. The protection diode conducts the excess, and the datasheet caps that current at 5 mA.

Fix: move the signal to a 5 V tolerant pin, or shift it down before the pin.

An STM32 output (VOH 2.4 V) drives a 74HCT input (VIH 2.0 V). What is the high noise margin?

Chapter 2

Let the Contacts Stop Bouncing

Size an RC filter from the longest bounce gap, or count samples in firmware, so one press counts once

A button is two metal contacts. When they hit, they bounce apart and together several times over a few milliseconds. A pin with a pull-up sees each bounce as a separate press. Lesson 1 gave the pull-up; here we make one press count once.

Count one press as one

Pink is the contact, closed or open. Blue is the pin. Purple is what the firmware sees. Pick a method, then turn its knob until the count is 1.

1.0 ms
2, at 1 ms

Illustrative bounce: the longest open gap while pressed is 0.9 ms; real switches differ, so measure yours. This toy chip switches up at 1.5 V and down at 1.3 V (dashed), inside the STM32F103's guaranteed band of 1.16 to 1.83 V (grey). The sizing rule in the text uses 1.16 V, so it holds for every chip. The press shorts the capacitor at once.

The hardware fix is a capacitor across the button. When the contacts open, the pull-up must charge the capacitor before the pin reads 1. A short gap lifts the voltage only a little. How long does the charge take to reach a threshold? Call the pull-up R, the capacitor C, the supply VDD and the threshold Vth. The time is t:

Say it aloud

t equals R C times the natural log of V-D-D over V-D-D minus V-t-h.

t
t the time for the pin to climb from 0 V to the threshold, in seconds.
R C
R C the time constant: resistance in ohms times capacitance in farads gives seconds.
ln
the natural log it undoes the exponential curve of a charging capacitor.
VDD
V-D-D the supply the pull-up goes to: 3.3 V.
Vth
V-t-h the threshold voltage the pin must reach.
In plain words

The capacitor charges along 1 minus e to the minus t over R C. Set that equal to V-t-h over V-D-D and solve for t. A bounce gap shorter than t never reaches V-t-h, so it never counts.

With numbers

To hide a gap, keep the pin under V-I-L = 1.16 V: t = R C × ln(3.3 / 2.14) = 0.435 R C. A 0.9 ms gap needs R C ≥ 0.9 / 0.435 = 2.07 ms: 22 kΩ and 100 nF give 2.2 ms. The release then reads 1 after 0.811 R C = 1.78 ms.

The firmware fix needs no parts. Sample the pin every millisecond, and accept a new level only after it reads the same k times in a row. With k = 5, a level must hold for 5 ms. Any bounce gap shorter than that resets the count.

Symptom: one press counts twice, now and then.

Measure: scope the pin, trigger on the first edge, and read the longest gap in the chatter.

Fix: make R C at least 2.3 times that gap, or count equal samples over a time longer than it.

An old design uses 10 kΩ and 100 nF (R C = 1 ms) and claims it hides 1 ms bounces. Which gap does it hide for sure?

Chapter 3

Switch Power You Cannot Source

Drive a motor through a MOSFET, then catch the voltage the coil makes when you switch it off

A pin is a weak switch. On the STM32F103 each pin may carry 25 mA at most, and all pins together 150 mA. At 20 mA its low level already rises to 1.3 V. A 12 V motor that draws 0.5 A needs a switch the pin can drive.

Use an N-channel MOSFET as a low-side switch, between the load and ground. The pin drives its gate. Pick a logic-level part: its datasheet gives the on-resistance RDS(on) at a gate voltage of 2.5 V or 3.3 V. With an illustrative 0.05 Ω, the MOSFET heats by I²R = 0.5² × 0.05 = 12.5 mW. A part rated only at a 10 V gate may sit half on at 3.3 V, at an illustrative 5 Ω: 1.25 W.

The trouble starts at switch-off. A motor winding is an inductor, and an inductor resists any change in its current. Call its inductance L and the rate the current changes di/dt. The coil makes a voltage VL:

Say it aloud

V-L equals L times d-i over d-t.

VL
V-L the voltage across the coil, in volts. At switch-off it adds to the supply at the drain.
L
L the inductance, in henries: 2 mH for this illustrative motor.
di/dt
d-i over d-t how fast the current changes, in amperes per second.
In plain words

Divide the change in current by the time it takes. Multiply by L. A fast switch-off makes d-i over d-t huge, so V-L is huge too.

With numbers

With made-up values: 0.5 A stopped in 100 ns through 2 mH gives V-L = 0.002 × 0.5 / 0.0000001 = 10,000 V. The MOSFET breaks down long before, near its rating, and absorbs at least the coil's stored energy, ½ L I² = 0.25 mJ, every time.

Switch the motor off

The left sketch is the circuit. The plot shows the drain voltage (blue) and the coil current (pink) after the gate goes low. Remove the diode, then press the switch.

20 kHz

Illustrative values: 12 V supply, 24 Ω and 2 mH winding (0.5 A), a 30 V MOSFET, a diode drop of 0.7 V. Without the diode the drain clamps at the MOSFET's breakdown, drawn at 30 V.

The cure is a flyback diode across the coil, cathode to +12 V. While the motor runs, the diode is reverse-biased and carries nothing. At switch-off, the coil current flows round through the diode and dies away with time constant L/R = 2 mH / 24 Ω = 83 µs. The drain stops at 12.7 V. Under PWM speed control (Lesson 1), the diode carries the coil current in the off part of every period.

Symptom: the MOSFET runs hot and dies after an hour of PWM, or the MCU resets each time the motor stops.

Measure: scope the drain at switch-off. A flat top at the MOSFET's rating names the missing diode: at 20 kHz, at least 5 W.

Fix: fit the flyback diode close to the coil. Add a gate pull-down, because a reset pin floats.

Why does switching a motor off without a diode make a spike far above 12 V?

Chapter 4

The ADC Samples a Capacitor

Give the sampling capacitor time to charge, then sample fast enough that no tone folds down

Lessons 1 and 3 turned a code into a voltage and filled the ADC's range. Here is what happens inside one sample. A switch connects the pin to a small capacitor for the sampling time, then opens. The ADC converts whatever voltage the capacitor holds. If the capacitor has not finished charging, the code is wrong.

The capacitor charges through the source's resistance plus the switch. To be within a quarter of a step at the end, the charging curve must close to 2−(N+2) of its gap. That gives the largest source resistance RAIN:

Say it aloud

R-A-I-N is at most T-S over f-A-D-C times C-A-D-C times the log of two to the N plus two, minus R-A-D-C.

RAIN
R-A-I-N the resistance of whatever drives the pin, in ohms.
TS
T-S the sampling time, in ADC clock cycles: 1.5, 7.5, 13.5 and up.
fADC
f-A-D-C the ADC clock: 14 MHz at most here.
CADC
C-A-D-C the sampling capacitor: 8 pF.
ln 2N+2
the log of two to the N plus two the number of time constants needed to get within a quarter step. N = 12 gives 9.70.
RADC
R-A-D-C the switch's own resistance: 1 kΩ.
In plain words

Turn T-S into seconds by dividing by f-A-D-C. Divide by the 9.70 time constants the capacitor needs. That is the largest total R allowed. Subtract the switch's R-A-D-C; the rest is what the source may have.

With numbers

STM32F103 values (datasheet, Equation 1): at 7.5 cycles, 7.5 / (14,000,000 × 8 pF × 9.70) − 1 kΩ = 5.9 kΩ. Lesson 3's divider of 10 kΩ over 20 kΩ looks like 6.67 kΩ: too much. At 13.5 cycles the limit is 11.4 kΩ, so it fits.

Sample a voltage, then a tone

Settle: the curve is the capacitor's error in steps, on a log scale; the switch opens at the yellow line. Alias: pink is the true tone, blue dots are the samples, purple is what the samples look like.

6.7 kΩ
950 Hz

Settle uses the STM32F103 datasheet's model (8 pF, 1 kΩ, 14 MHz, a full-scale step). Alias samples at an illustrative 1,000 samples per second.

The second limit is the rate. A tone at frequency f, sampled fs times a second, gives the same samples as a tone at fa, the alias:

Say it aloud

f-a equals the size of f minus k times f-s.

fa
f-a the frequency the samples seem to show, between 0 and f-s / 2.
f
f the true frequency at the pin, in hertz.
k
k the whole number that puts k times f-s nearest to f.
fs
f-s the sample rate, in samples per second.
In plain words

Find the multiple of f-s closest to f. The distance between them is f-a. Below f-s / 2, k is 0 and the samples show the tone as it is.

With numbers

At f-s = 1,000 per second, a 950 Hz whine gives k = 1 and f-a = |950 − 1,000| = 50 Hz. The firmware sees a 50 Hz wobble that is not there.

Filter before you sample. The old version of this page used 10 kΩ and 39 nF, a cutoff of 408 Hz, for a 1,000 per second ADC. That one-pole filter still passes 40% of the 950 Hz whine. Sample faster, or use a steeper filter (Timers, PWM and Sampling works through both).

Symptom: a channel's reading depends on which channel was read just before it.

Measure: read the same channel twice in a row. If the first reading differs, the capacitor still holds the last channel's charge.

Fix: lengthen the sampling time, buffer the source, or lower its resistance.

A 10 kΩ source feeds the STM32F103's ADC at 7.5 cycles, where the limit is 5.9 kΩ. What happens?

Chapter 5

Two Clocks Must Agree

Compute a UART's baud error from its divider, and derive how much error the receiver survives

A UART has no clock wire. Each end times bits from its own clock. The receiver waits for the falling edge of the start bit, then samples each bit at its middle, timed with 16 ticks of its own clock per bit.

The baud rate comes from dividing a clock, and dividers round. Call the clock fclk, the divider D and the baud you asked for b. The baud you get is breal, and the error e is how far it misses:

Say it aloud

b-real equals f-clock over sixteen D, and e equals b-real over b, minus one.

breal
b-real the baud rate the hardware makes, in bits per second.
fclk
f-clock the clock feeding the UART, in hertz.
D
D the divider. An AVR takes whole numbers; an STM32F103 takes steps of 1/16.
e
e the baud error, as a fraction; times 100 gives a percentage.
b
b the baud rate you asked for.
In plain words

Divide f-clock by 16 times b to get the ideal D. Round it to a step the hardware allows. Put the rounded D back in to get b-real, and compare it with b.

With numbers

An AVR at 16 MHz and 115,200 baud: ideal D = 8.68, rounded to 9, so b-real = 111,111 and e = −3.5%. An STM32F103 at 72 MHz: D = 39.0625 exactly, so e = 0. An 11.0592 MHz crystal gives D = 6: no error.

Find the baud error and the drift

Top: the total error between both ends against the ±4.6% limit. Bottom: two frames back to back, and where the receiver samples. Pick a clock, then add the other end's error.

0.0%

Dividers as in the ATmega328P (whole numbers, normal speed) and the STM32F103 (steps of 1/16). The receiver model is the simple one derived below; real receivers lose a little more margin.

How much error survives? The receiver finds the start edge within one tick, 1/16 of a bit. The last sample, the middle of the stop bit, comes 9.5 bit times later. Each bit adds the error once, so the drift there is 9.5 e. It must stay under half a bit less that first tick:

Say it aloud

The size of e-total is less than one half minus one sixteenth, all over nine point five.

|etot|
the size of e-total the error between the two ends: one end's error minus the other's.
1/2
one half a centre sample may drift half a bit before it crosses an edge.
1/16
one sixteenth the receiver finds the start edge up to one tick late, at 16 ticks per bit.
9.5
nine point five bit times from the start edge to the middle of the stop bit.
In plain words

The drift grows by e-total every bit. After 9.5 bits it must still be under 1/2 − 1/16 of a bit. Divide that room by 9.5 to get the largest e-total.

With numbers

0.4375 / 9.5 = 4.6%. A brute-force run of back-to-back 0x55 frames first fails at 4.61% when the receiver is slow, and at 5.27% when it is fast and finds the edge at once. The AVR's −3.5% passes this model, with little room.

Real receivers take three samples near the middle and check that they agree. That costs margin, and vendor manuals give under 4% for this frame. The STM32F103's internal RC clock, HSI, is −1.1 to +1.8% at 25 °C and −2 to +2.5% over −40 to 105 °C (datasheet). Two such boards at opposite ends of their range can disagree by 4.5%. A crystal is off by only tens of parts per million.

Symptom: the console prints garbage only on long messages, or only when the board is hot.

Measure: time ten bits on a scope. At 115,200 baud they take 86.8 µs; compare both ends.

Fix: pick a clock that divides cleanly, or a crystal instead of the RC clock.

Why does the stop bit, not the start bit, decide a UART's clock tolerance?

Chapter 6

Address, Acknowledge, Stretch

Walk one I²C register read bit by bit, and see where fast mode's 1.3 µs low period comes from

I²C has two open-drain lines with pull-ups: SCL, the clock, and SDA, the data. Any chip can pull a line low; nobody drives it high (Chapter 1). Lesson 3 sized the pull-ups. Here is what travels on the lines.

Data changes only while SCL is low. So the bus keeps two changes while SCL is high as markers: SDA falling is START, SDA rising is STOP. After each byte, the controller sends a ninth clock and lets go of SDA. The receiver pulls SDA low to acknowledge (ACK). If SDA stays high, that is a NACK: for example, no chip has that address. The spec reserves two groups of 8 addresses, so 112 of the 128 seven-bit addresses are free.

Read one register over I²C

The controller reads register 0xD0 of a BME280 at address 0x76. Press Send to play it. Then give a wrong address, or let the sensor stretch the clock.

BME280 address 0x76 (SDO to ground) and chip-ID register 0xD0, value 0x60, from Bosch's datasheet. Timing counts SCL clocks only; START, STOP and bus-free times add a few microseconds.

Why is fast mode's clock low for at least 1.3 µs? The low half is a budget with three parts. The sender has a data valid time, tVD;DAT, to put its bit out. The line has a rise time, tr, to climb. The reader needs a setup time, tSU;DAT, before SCL rises:

Say it aloud

t-low is at least t-V-D-data plus t-r plus t-setup-data.

tLOW
t-low how long SCL stays low each clock.
tVD;DAT
t-V-D-data the longest a sender may take, after SCL falls, to put its bit on SDA.
tr
t-r the longest rise time the pull-up may need, from 30% to 70% of V-D-D.
tSU;DAT
t-setup-data how long SDA must hold still before SCL rises.
In plain words

Add the time to output the bit, the time for the line to rise, and the time the reader needs to see it. SCL must stay low at least that long.

With numbers

From NXP UM10204, Table 11. Fast mode: 0.9 + 0.3 + 0.1 = 1.3 µs, exactly its t-low. Standard mode: 3.45 + 1.0 + 0.25 = 4.7 µs, exactly its t-low too.

A target that needs more time can hold SCL low after the controller lets go. That is clock stretching, and the controller must wait for SCL to rise. The spec notes that most targets cannot do it, and some controllers do not wait.

Symptom: after a reset in the middle of a read, the bus is dead: SDA stays low.

Measure: SCL idles high while SDA is low. A target is still waiting to send the rest of its byte.

Fix: clock SCL nine times as a plain GPIO, then send a STOP. UM10204 §3.1.16 gives this bus clear.

The controller sends address 0x77, and SDA stays high on the ninth clock. What does that mean?

Chapter 7

Sample on One Edge, Change on the Other

Match the SPI mode to the device, then find the fastest clock its round trip allows

SPI sends a clock, so the two ends cannot disagree on speed. They can disagree on edges. Two bits set the mode. CPOL is the clock's idle level. CPHA says whether the receiver samples on the first edge after idle or the second. Whoever samples on one edge must have the other side change its output on the opposite edge.

ModeCPOLCPHASample onChange on
00, idles low0rising edgefalling edge
10, idles low1falling edgerising edge
21, idles high0falling edgerising edge
31, idles high1rising edgefalling edge

Modes 0 and 3 use the same edges, and only the idle level differs. That is why a Winbond W25Q flash works in either. Send it command 0x9F and it returns its JEDEC ID: EF 40 18 for the W25Q128. To read, the master must clock out dummy bytes, because each clock moves one bit each way.

Read the flash ID

Yellow is SCK with the master's sample edges marked. Blue is MISO, late by the round trip. Pick the master's mode, then raise the clock.

8 MHz

Illustrative timing: 12 ns output delay, 1 ns of wire each way, 5 ns setup. If the master samples on the edge where the flash changes, this toy gives it the old bit. On a real bus that race can go either way.

Speed has a limit too. In mode 0 the flash changes MISO on a falling edge, and the master samples on the next rising edge, half a period later.

In that half period, four things happen. The clock edge travels to the flash. The flash takes its output delay tV. The bit travels back. The master needs its setup time. Call one wire's delay tw. The fastest clock is fmax:

Say it aloud

f-max equals one over two times the sum of two t-w, t-V and t-S-U.

fmax
f-max the fastest SCK that still reads correct bits, in hertz.
tw
t-w one wire's delay. It counts twice: SCK out, MISO back.
tV
t-V the device's output delay: from its clock edge to a valid bit.
tSU
t-S-U the master's setup time before its sample edge.
In plain words

Add up the round trip: two wire delays, the output delay and the setup. That must fit in half a clock period. Double it to get the period, and invert it for f-max.

With numbers

With made-up values: 2 × 1 + 12 + 5 = 19 ns, so f-max = 1 / 38 ns = 26.3 MHz. A long cable at 2 ns each way gives 21 ns and 23.8 MHz. Above f-max the master reads EF 40 18 as F7 A0 0C: every bit one place late.

Each SPI device has its own chip-select wire, so N devices need N + 3 wires. An SD card in SPI mode at 25 MHz moves at most 25 / 8 = 3.125 MB/s, before command overhead. The old page's "over 3 MB/s" cannot happen.

Symptom: the ID reads correctly at 8 MHz and as F7 A0 0C at 32 MHz.

Measure: halve the clock. If the bytes come right, the round trip is too long for the half period.

Fix: lower SCK, or shorten the wires to the device.

A flash works in modes 0 and 3. Why do both work?

Chapter 8

Leave the Board: USB and Radio

Give USB the clock it demands, then price a radio link in decibels

USB also has no clock wire, and it is far stricter than a UART. Full speed runs at 12 Mbit/s ±0.25%; low speed allows ±1.5%. The STM32F103's RC clock is −1.1 to +1.8% at room temperature, seven times too wide. So a full-speed USB board uses a crystal.

When you plug a device in, the host and device go through enumeration:

  1. Attach: the device's 1.5 kΩ pull-up on D+ tells the host "full speed".
  2. Reset: the host drives both lines low for at least 10 ms.
  3. Address: the host gives the device a number from 1 to 127.
  4. Descriptors: the host reads who the device is and what it offers.
  5. Driver: the class code picks a driver, and the host configures the device.

Standard classes need no custom driver. CDC appears as a serial port, HID as a keyboard or mouse, MSC as a drive. A stack such as TinyUSB or the vendor's library handles the protocol; you write the descriptors and callbacks.

Price a radio link in decibels. Call the transmit power Ptx and the path loss over distance d L(d). Call the loss through walls Lw, and the receiver's sensitivity, the weakest signal it decodes, S. The margin M is what is left:

Say it aloud

M equals P-t-x minus L of d, minus L-w, minus S; L of d is twenty log ten of four pi d over lambda.

M
M the link margin, in decibels. Below zero, packets are lost.
Ptx
P-t-x the transmit power, in dBm: decibels above one milliwatt.
L(d)
L of d the free-space path loss over d metres, in dB.
Lw
L-w the extra loss through walls and bodies, in dB.
S
S the sensitivity, in dBm; a more negative number is better.
λ
lambda the wavelength: 0.123 m at 2.44 GHz.
In plain words

Start from P-t-x. Subtract each loss on the way. Compare what arrives with S. The gap is M. Each doubling of d adds 6 dB of path loss.

With numbers

With made-up walls of 8 dB: an nRF52840 at +8 dBm over 20 m and 3 walls: 8 − 66.2 − 24 − (−95) = +12.8 dB. The link holds.

Reach the gateway

The staircase is the signal: transmit power, then path loss, then each wall. The yellow line is the sensitivity. Add walls, then switch to the slower coded mode.

30 m
4

Sensitivities and the +8 dBm maximum are Nordic's nRF52840 product specification. The 8 dB per wall is illustrative. Free space is the best case; real rooms lose more.

Slower bits buy range. The receiver's noise grows with its bandwidth, so each halving of the bit rate gains about 3 dB. The nRF52840 gains 8 dB going from 1 Mbit/s to 125 kbit/s, eight times slower. In free space that is 108/20 = 2.5 times the range. The old page's rule "range × bandwidth × power is constant" is not a law; this budget is. Lesson 3 priced radios by charge per report, and BLE from Radio to GATT covers notifications and services.

Symptom: USB enumerates on one PC and fails on another, or only when warm.

Measure: measure the USB clock. Off by more than 0.25% breaks full speed.

Fix: run the USB clock from a crystal.

At 30 m through 4 walls (8 dB each), 0 dBm at 1 Mbit/s leaves a margin of −6.7 dB. What does the 125 kbit/s coded mode (−103 dBm) give?

Chapter 9

Bring Up the Sensor Board

Run the bring-up checks on a board with planted faults, and name each fault from its symptom

A new board carries an STM32F103, a BME280 sensor on I²C, a W25Q128 flash on SPI and a GPS module on a UART. We planted five faults. Each one breaks one contract from this lesson, and each has its own symptom. Run the checks, read the symptoms, and fix the faults one at a time.

Run the bring-up checks

Each lit button is a planted fault. Press Run to check every bus in order, read the log, then press a fault to fix it and run again.

Illustrative board. Facts used: BME280 at 0x76 with ID 0x60 (Bosch), W25Q128 ID EF 40 18 in modes 0 and 3 (Winbond), the GPS at 9,600 baud, and 3.6 V on a standard pin (ST). The 5 V GPS board is made up.

FaultContractSymptomChapter
No I²C pull-upselectrical: nothing makes a highboth lines stay low; the bus reads busy6
Address 0x77protocolNACK on the ninth clock6
SPI mode 2timing: wrong edgeID F7 A0 0C7
UART at 115,200timing: 12 times the GPS rategarbage and framing errors5
5 V on a standard pinelectrical: over 3.6 Vworks, until the pin fails1

Fix them in the order the checks find them. The last fault is the dangerous one: every check passes while the pin is over its rating. Only reading the levels against the datasheet finds it.

Chapter 10

Field Guide

Keep the numbers, the bug table and the next steps in one place

Every interface is two contracts. The electrical one: the driver's guaranteed levels clear the receiver's thresholds and stay under its maximum. The timing one: the receiver samples each bit after it settles and before it changes. Check the levels with the datasheets, and the timing with a budget: bounce gaps, capacitor charge, baud drift, low periods and round trips.

QuantityRuleExample
Noise marginVOH − VIH2.4 − 3.15 = −0.75 V
RC to a thresholdR C ln(VDD / (VDD − Vth))0.435 R C to 1.16 V
Coil kickL di/dt2 mH, 0.5 A in 100 ns: 10 kV
ADC source limitTS / (f C ln 2N+2) − RADC7.5 cycles: 5.9 kΩ
Alias|f − k fs|950 Hz at 1 kHz: 50 Hz
Baud errorf / (16 D b) − 116 MHz, 115,200: −3.5%
UART tolerance(1/2 − 1/16) / 9.54.6%
I²C low periodtVD + tr + tSU0.9 + 0.3 + 0.1 = 1.3 µs
SPI clock limit1 / (2 (2 tw + tV + tSU))19 ns: 26.3 MHz
Link marginPtx − L(d) − Lw − S+12.8 dB at 20 m
BugSymptomWhat names it
5 V on a 3.3 V pinworks, then the pin dieshigh level above 3.6 V
Bounceone press counts twicegaps in the chatter on a scope
No flyback diodehot MOSFET, resetsflat-top spike on the drain
High source Rchannels leak into each otherfirst of two reads differs
Baud errorgarbage on long messagesten bits timed on a scope
Wrong I²C addressNACK, no dataSDA high on the ninth clock
Stuck I²C busdead after a resetSDA low while SCL idles high
SPI too fastbytes one bit latecorrect again at half the clock
USB on the RC clockenumerates on some PCs onlyclock more than 0.25% off
python
import math

def noise_margin_high(v_oh, v_ih):
    return v_oh - v_ih

def rc_time_to(v_th, r, c, vdd=3.3):
    return r * c * math.log(vdd / (vdd - v_th))

def adc_max_source(ts_cycles, f_adc=14e6, c_adc=8e-12, r_adc=1e3, bits=12):
    return ts_cycles / (f_adc * c_adc * math.log(2 ** (bits + 2))) - r_adc

def alias(f, fs):
    return abs(f - round(f / fs) * fs)

def baud_error(f_clk, baud, step=1):
    """step=1 for whole-number dividers (AVR), 1/16 for the STM32F103."""
    d = round(f_clk / (16 * baud) / step) * step
    return f_clk / (16 * d) / baud - 1

def spi_fmax(t_wire, t_v, t_su):
    return 1 / (2 * (2 * t_wire + t_v + t_su))

def link_margin(p_tx, d, walls_db, sens, f=2.44e9):
    lam = 3e8 / f
    return p_tx - 20 * math.log10(4 * math.pi * d / lam) - walls_db - sens

We ran each function. noise_margin_high(2.4, 3.15) gives −0.75. rc_time_to(1.164, 22e3, 100e-9) gives 0.957 ms. adc_max_source(7.5) gives 5,901 Ω. alias(950, 1000) gives 50. baud_error(16e6, 115200) gives −0.0355. spi_fmax(1e-9, 12e-9, 5e-9) gives 26.3 MHz. link_margin(8, 20, 24, −95) gives 12.8.

Where it sits. Lesson 1 named the pins and buses; Lesson 3 put them on a board. This lesson is the contract on each wire. Beyond it come CAN for long noisy cables, Ethernet, and signal integrity for edges that outrun their traces.

Keep going

Read next

The habit. Before you blame the code, ask which contract broke. Read the levels against the datasheet, then find the sampling instant and check that the bit has settled there.
Which two things must be true for a receiver to read a bit correctly?

Now teach it: press Present or Teach and explain why a UART survives about 4.6% of clock error and where fast mode's 1.3 µs comes from. Then go back to the three links and predict each break point before you turn the knob.

Embedded Systems · Lesson 4: Hardware Interfacing, from Pins to Protocols
Previous: Hardware Design · Next: Embedded Linux · Back to Gleams