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.
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
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.
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.
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).
Chapter 1
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:
N-M-H equals V-O-H minus V-I-H.
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.
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.
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.
Chapter 2
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.
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.
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:
t equals R C times the natural log of V-D-D over V-D-D minus V-t-h.
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.
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.
Chapter 3
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:
V-L equals L times d-i over d-t.
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 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.
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.
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.
Chapter 4
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:
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.
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.
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.
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.
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:
f-a equals the size of f minus k times f-s.
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.
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.
Chapter 5
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:
b-real equals f-clock over sixteen D, and e equals b-real over b, minus one.
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.
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.
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.
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:
The size of e-total is less than one half minus one sixteenth, all over nine point five.
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.
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.
Chapter 6
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.
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:
t-low is at least t-V-D-data plus t-r plus t-setup-data.
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.
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.
Chapter 7
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.
| Mode | CPOL | CPHA | Sample on | Change on |
|---|---|---|---|---|
| 0 | 0, idles low | 0 | rising edge | falling edge |
| 1 | 0, idles low | 1 | falling edge | rising edge |
| 2 | 1, idles high | 0 | falling edge | rising edge |
| 3 | 1, idles high | 1 | rising edge | falling 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.
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.
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:
f-max equals one over two times the sum of two t-w, t-V and t-S-U.
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 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.
Chapter 8
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:
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:
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.
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 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.
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.
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.
Chapter 9
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.
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.
| Fault | Contract | Symptom | Chapter |
|---|---|---|---|
| No I²C pull-ups | electrical: nothing makes a high | both lines stay low; the bus reads busy | 6 |
| Address 0x77 | protocol | NACK on the ninth clock | 6 |
| SPI mode 2 | timing: wrong edge | ID F7 A0 0C | 7 |
| UART at 115,200 | timing: 12 times the GPS rate | garbage and framing errors | 5 |
| 5 V on a standard pin | electrical: over 3.6 V | works, until the pin fails | 1 |
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
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.
| Quantity | Rule | Example |
|---|---|---|
| Noise margin | VOH − VIH | 2.4 − 3.15 = −0.75 V |
| RC to a threshold | R C ln(VDD / (VDD − Vth)) | 0.435 R C to 1.16 V |
| Coil kick | L di/dt | 2 mH, 0.5 A in 100 ns: 10 kV |
| ADC source limit | TS / (f C ln 2N+2) − RADC | 7.5 cycles: 5.9 kΩ |
| Alias | |f − k fs| | 950 Hz at 1 kHz: 50 Hz |
| Baud error | f / (16 D b) − 1 | 16 MHz, 115,200: −3.5% |
| UART tolerance | (1/2 − 1/16) / 9.5 | 4.6% |
| I²C low period | tVD + tr + tSU | 0.9 + 0.3 + 0.1 = 1.3 µs |
| SPI clock limit | 1 / (2 (2 tw + tV + tSU)) | 19 ns: 26.3 MHz |
| Link margin | Ptx − L(d) − Lw − S | +12.8 dB at 20 m |
| Bug | Symptom | What names it |
|---|---|---|
| 5 V on a 3.3 V pin | works, then the pin dies | high level above 3.6 V |
| Bounce | one press counts twice | gaps in the chatter on a scope |
| No flyback diode | hot MOSFET, resets | flat-top spike on the drain |
| High source R | channels leak into each other | first of two reads differs |
| Baud error | garbage on long messages | ten bits timed on a scope |
| Wrong I²C address | NACK, no data | SDA high on the ninth clock |
| Stuck I²C bus | dead after a reset | SDA low while SCL idles high |
| SPI too fast | bytes one bit late | correct again at half the clock |
| USB on the RC clock | enumerates on some PCs only | clock 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.
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.