Nine clock pulses free an I2C bus that a reset could not, because the peripheral is still waiting to finish its byte. Break the bus below, then fix it.
Pick Reset mid-byte and slide the reset point. Watch the data line stick low, then press 9 clocks + STOP. Then raise the bus capacitance and watch the edges slow down. After that we build every bus from zero: the pin, the pull-up, the clock, the frame, the cable.
You need to know that a wire carries a high or a low voltage and a little C. We build the rest from zero, on an Arm Cortex-M part such as an STM32.
Built from primary sources: the NXP I2C-bus specification UM10204 (Rev. 7), the Linux kernel I2C core, MIPI and USB-IF pages, Winbond and Analog Devices documents. Every source is listed in the Field Guide. Follows From Vector Table to main.
A model, not a measurement. The wave is built from the I2C rules at 400 kHz (a 2.5 µs clock period). Rise time is 0.8473 × Rp × Cb, the UM10204 definition between 30% and 70% of VDD. An edge counts as missed when the data line needs more than 1.15 µs to reach 70%, which is the 1.25 µs low half-period minus the 100 ns Fast-mode data set-up time. Target data 0x5A, address 0x48.
Chapter 0
See why a microcontroller reset cannot free a stuck I2C line, and why nine clock pulses can
A robot arm has an accelerometer on a two-wire bus. One day a brownout hits the board. The microcontroller restarts and runs its start-up code. The accelerometer never answers again. Every read times out.
You press reset. Nothing changes. You reflash the firmware. Nothing changes. You pull the power for a moment, and everything works. The firmware was fine. The bus was stuck, and only a power cycle cleared it.
That story has a happy ending, because we can explain it. To do that we need to look at the two wires.
I2C (pronounced "eye squared see") connects chips with two wires. SCL is the clock. SDA is the data. Many chips share the same two wires. The chip that starts a transfer is the controller. The chip that answers is a target. (Older documents say master and slave. The current NXP specification, UM10204 Rev. 7, says controller and target.)
Think of the two wires as a hallway with a spring that pulls a door shut. Each chip holds a rope that can pull the door open. Nobody pushes the door shut. When all ropes go slack, the spring closes it. That is the whole electrical idea.
The real parts are these. Each chip has a switch to ground on the wire. A pull-up resistor connects the wire to the supply voltage VDD. When every switch is off, the resistor pulls the wire to a 1. When any switch is on, the wire drops to a 0. We call this open-drain, after the transistor that does the pulling. Because one 0 beats any number of 1s, the wire shows the AND of what every chip wants. Engineers call this wired-AND.
Try it. Pull the line down with each chip in turn, then try the "reset" button.
Each chip can switch on its pull-down. The line is low if any switch is on. Turn on the target, then press Reset the controller.
A model of the wired-AND rule, not a circuit simulation. A reset only changes the controller's own switch. It cannot reach into another chip.
A transfer has a fixed shape. The controller makes a START: SDA falls while SCL is high. Then it sends 7 address bits, one per clock pulse, and one more bit that says read or write. Then comes one acknowledge slot. The target that owns the address pulls SDA low to say "yes, I am here". That is an ACK. If SDA stays high, nobody answered. That is a NACK. After that, bytes of data follow, each followed by its own ACK slot. The controller ends the transfer with a STOP: SDA rises while SCL is high.
Seven address bits give 128 codes. The specification reserves two groups of eight, 0000 XXX and 1111 XXX, for special jobs. So 128 codes minus 16 reserved leaves 112 usable addresses. Two chips with the same address on one bus will fight, and we meet that fault in Chapter 2.
128 codes − 16 reserved = 112 usable 7-bit addresses (UM10204 section 3.1.12)
Now watch what happens in a read. The controller asks, and the target sends a byte. The target has an 8-bit shift register. It puts out the next bit each time it sees SCL fall. It does not move until the controller sends a clock. The data bit that it shows stays on SDA until then.
Suppose the controller resets after a few bits. It forgets everything. It releases both wires. But the target did not reset. It still shows a bit on SDA, and it still waits for a clock. If that bit is a 0, SDA stays low. A low SDA looks like a busy bus. The controller waits for a free bus that never comes.
In the hero, the reset point matters. The data byte is 0x5A, bits 0 1 0 1 1 0 1 0. After the reset, the target holds the last bit it showed. If that was a 1, the pull-up wins and the bus is free. If it was a 0, the bus is stuck. With the slider at 3 data bits, the last bit shown was a 0, so the target needs 6 more clocks to finish. At 0 data bits, the target still holds the ACK, so it needs the full 9.
The specification gives the fix in section 3.1.16, Bus clear. If SDA is stuck low, the controller should send nine clock pulses. The target that holds SDA low should let go sometime within those nine clocks. If SCL itself is stuck low, the clock cannot help. The specification then says to use a hardware reset pin or to cycle power.
Nine is the longest possible wait. A byte has 8 bits, and the ACK slot is the ninth clock. After that, the target is done and releases SDA. Then the controller sends a STOP so that every chip goes back to idle. The Linux kernel does exactly this in its generic bus recovery code: it sets RECOVERY_CLK_CNT to 9 and creates a STOP.
To do this in firmware you must take the pins away from the I2C hardware block. You switch them to plain GPIO, toggle SCL nine times by hand, check SDA after each pulse, send the STOP, and give the pins back to the block. Chapter 9 shows the code.
Every bus in this lesson works the same way. Each fault has a waveform that names it, and each waveform has one measurement that proves it. Here is the road.
Chapter 1
Open one pin and see the switches, resistors and settings that decide what a 1 and a 0 really are
You wire a new sensor to a Nucleo board. The code looks right. The sensor never answers. You put a scope probe on SCL and see a flat line. The clock never moves. The bus is fine, and the sensor is fine. The pin is not connected to the I2C block.
To find a fault like this you need a picture of what is inside one pin. In earlier lessons, a pin was a bit in a register. Now we open it up. (Our GPIO, clocks and bring-up lesson covers the registers. Hardware interfacing covers the wiring.)
A GPIO (general-purpose input/output) pin has a few parts. An output driver can connect the pin to VDD or to ground. An input buffer reads the voltage. Two optional pull resistors can tie the pin weakly to VDD or to ground. A multiplexer chooses who controls the pin: the GPIO register, or one of the chip's peripheral blocks such as I2C, SPI or UART.
On an STM32F4 part, the reference manual (RM0090) names these settings per pin. MODER picks input, output, alternate function or analog. OTYPER picks push-pull or open-drain. OSPEEDR picks the output speed. PUPDR picks pull-up, pull-down or none. AFRL and AFRH pick which peripheral owns the pin when the mode is alternate function.
A push-pull output has two transistors. One connects the pin up to VDD. The other connects it down to ground. The output actively drives both a 1 and a 0. It is fast, and it is what you want for a clock or an LED.
An open-drain output keeps only the lower transistor. It can pull the pin to 0. It can only release it for a 1. Something outside must pull the pin up. That is the pull-up resistor from Chapter 0.
Why would anyone choose the weaker design? Because it is safe to share. If two push-pull outputs share a wire and one says 1 while the other says 0, the two transistors connect VDD straight to ground through each other. A large current flows and the wire has no clear voltage. Two open-drain outputs can disagree with no harm. The wire is simply 0.
Play with the pin below. Set up a shared wire and cause a fight.
Choose the output type and write a 0 or a 1. Add a pull-up. Let another chip pull the wire low. See what the wire becomes.
Illustrative: each transistor is given 25 Ω when on, so a fight draws VDD ÷ 50 Ω. Real on-resistance depends on the part and its speed setting. The minimum pull-up uses the UM10204 rule: Rp(min) = (VDD − 0.4 V) ÷ 3 mA.
A pull-up resistor sets two limits. If it is too large, the wire rises too slowly (Chapter 2). If it is too small, the target cannot pull the wire low. The target's output can sink only a limited current. In Standard-mode and Fast-mode I2C that current is 3 mA, and the low level must stay under 0.4 V.
So the smallest allowed resistor is the one that drops the whole supply, minus 0.4 V, at 3 mA. Here are the steps for a 3.3 V system.
The UM10204 example uses a 5 V supply with 10% tolerance, so VDD is 5.5 V. Then Rp(min) = (5.5 − 0.4) ÷ 0.003 = 1.7 kΩ. Drag the supply in the device and read the same sum.
Drive strength and slew rate control how fast an output edge moves. A fast edge is good for timing and bad for noise. Fast edges ring and radiate (Chapter 7). Choose the slowest setting that still meets the bus timing.
An input buffer with hysteresis (a Schmitt trigger) has two thresholds: a higher one to call a rising signal "high" and a lower one to call a falling signal "low". Noise that wiggles between the two thresholds does not toggle the result. UM10204 builds this in: the noise margin figures count the hysteresis of each connected device.
A mechanical button is the classic noisy input. The contacts chatter for a short time when they close, so one press can look like many. Debouncing fixes this. A common recipe is to read the pin on a timer tick and accept a new level only after several reads in a row agree. Measure your own button on a scope to pick the time.
The multiplexer is the part people forget. You enable the I2C block and its clock. You write the driver. But the pin still points at the GPIO register, because nobody set its alternate function. The I2C block drives a signal that goes nowhere.
The symptom is a sensor that never ACKs. The measurement is a scope on SCL: the line stays flat at its idle level while your code runs. The fix is to set the mode to alternate function, pick the right AFR number from the datasheet's alternate function table, and give the pin open-drain with a pull-up. On Linux, the pin control debug files show which function owns each pin. Toggle Pin mux routes the block in the device to see the cut.
Rp(min) = (VDD − VOL) ÷ IOL = (3.3 V − 0.4 V) ÷ 3 mA = 967 Ω
Chapter 2
Compute the window of legal pull-up values and see it close as the bus gets longer
A board works well at 100 kHz. You raise the clock to 400 kHz to read the sensor faster. Now one read in twenty returns a wrong value. The code did not change. The wires did not change. Only the speed did.
Put a scope on SDA. At 100 kHz the rising edge is a lazy curve that still reaches the top before the clock needs it. At 400 kHz the curve is cut off. The chip reads the line before the voltage has climbed far enough. The edge is too slow for the speed.
Every wire, pin and pad has a little capacitance, a tiny bucket that stores charge. We call the total on the bus Cb. When no chip pulls the line down, the pull-up resistor Rp fills that bucket with charge. A bigger bucket or a thinner pipe takes longer to fill.
Physics gives the shape. The voltage after time t is V(t) = VDD × (1 − e−t/RC), where RC is the resistance times the capacitance. I2C defines the rise time tr as the time between two thresholds: 30% of VDD and 70% of VDD. We solve for each time.
This is the constant that UM10204 prints in section 7.1. Now flip it round. The specification gives a maximum rise time for each speed class. So it also gives a maximum pull-up:
Chapter 1 gave a floor: Rp(min) = (VDD − 0.4 V) ÷ IOL. This chapter gives a ceiling: Rp(max). A legal pull-up lies between the two. As capacitance grows, the ceiling falls, and one day it meets the floor. Then no resistor is legal. Drag the capacitance in the device below to find that day.
The shaded band is every legal Rp. The dot is your choice. Raise Cb until the band shuts, then try a different speed class.
Numbers from UM10204 Rev. 7: maximum rise time 1000, 300 and 120 ns; maximum Cb 400, 400 and 550 pF; sink current 3, 3 and 20 mA; low level 0.4 V. The Rp slider is logarithmic. 5.0 V is shown without the 10% tolerance.
So Fast-mode at 3.3 V runs out of room at 366 pF, even though the specification allows 400 pF. The 5 V example in UM10204 closes near 200 pF. Standard-mode is gentler: with 1000 ns allowed, 400 pF gives a ceiling of 2.95 kΩ, so its window is still open.
| Class | Bit rate | Max rise time | Max Cb | Sink current | Min clock low |
|---|---|---|---|---|---|
| Standard-mode | 100 kbit/s | 1000 ns | 400 pF | 3 mA | 4.7 µs |
| Fast-mode | 400 kbit/s | 300 ns | 400 pF | 3 mA | 1.3 µs |
| Fast-mode Plus | 1 Mbit/s | 120 ns | 550 pF | 20 mA | 0.5 µs |
| High-speed mode | 3.4 Mbit/s | own table | own table | own table | own table |
The specification also lists Ultra Fast-mode, a one-way mode up to 5 Mbit/s. Fast-mode Plus needs 20 mA sinks, so its floor is far lower: (3.3 − 0.4) ÷ 20 mA = 145 Ω, and its ceiling at 550 pF is 120 ns ÷ (0.8473 × 550 pF) = 257 Ω. The window is narrow but real.
Clock stretching. A target may hold SCL low to ask for more time (UM10204 section 3.1.9). The controller must wait for SCL to rise before it goes on. A controller that ignores this runs ahead of a slow target and reads garbage. Check that your driver supports stretching, and set a timeout so that a stuck SCL does not freeze the firmware.
NACK. If SDA stays high in the answer slot, no chip owns that address. Check the address (many data sheets quote the 8-bit form with the read/write bit included), the address pins, the power, and whether the chip is held in reset.
Two devices, one address. Two chips at the same address both answer. The tool i2cdetect shows one address, but the data is corrupt because both drive SDA. Change an address pin, or put one chip behind an I2C multiplexer.
Chapter 3
Decode a flash chip's ID under all four clock modes and see why only the matching ones read it right
You connect a Winbond W25Q128JV flash chip to a microcontroller. You send the command 9Fh, "read JEDEC ID". The chip should reply EFh, 40h, 18h. Your code prints DFh, 80h, 30h. The values are close to right but wrong. Something shifted by one bit.
Nothing is broken. The microcontroller and the flash disagree about when to look at the data wire. SPI has no start bit, no address and no acknowledge to warn you. If the timing disagrees, you just get wrong bits.
SPI (Serial Peripheral Interface) uses four wires. SCK is the clock, driven by the controller. MOSI carries data from controller to peripheral. MISO carries data from peripheral to controller. CS (chip select, active low) says "you are the one I am talking to". Each peripheral gets its own CS wire. The other wires are shared.
Inside, each side has a shift register. Picture two rows of eight buckets joined in a ring. On every clock pulse, each side pushes one bit out and takes one bit in. After eight pulses the two bytes have swapped places. That is why SPI is full duplex: data flows both ways at the same time. To read a byte you must send a byte, even if it is only a dummy.
SPI has no ACK. If you talk to an empty socket, MISO floats or reads all ones, and your code carries on with junk. Your protocol layer must check the data, for example with a known ID.
A clock pulse has two edges. In SPI, one edge makes the data change and the other edge says "read it now". The data has the whole half cycle between the two to settle. Two settings decide which edge does which job.
CPOL (clock polarity) is the resting level of SCK. CPOL = 0 means SCK rests low. CPOL = 1 means it rests high. CPHA (clock phase) says whether the first edge of a pulse reads the data (CPHA = 0) or changes it (CPHA = 1). Two bits make four modes.
| Mode | CPOL | CPHA | SCK rests | Data read on | Data changes on |
|---|---|---|---|---|---|
| Mode 0 | 0 | 0 | low | rising edge | falling edge |
| Mode 1 | 0 | 1 | low | falling edge | rising edge |
| Mode 2 | 1 | 0 | high | falling edge | rising edge |
| Mode 3 | 1 | 1 | high | rising edge | falling edge |
The Winbond datasheet says "SPI bus operation Mode 0 (0,0) and 3 (1,1) are supported". Look at the table: both of those read on the rising edge and change on the falling edge. They differ only in where SCK rests. That is why a chip can support both.
Now try it. The flash sends EFh. Pick the mode the controller uses and the mode the peripheral expects. The device draws SCK, the data wire, the moments the controller reads, and the bits it ends up with.
The peripheral shifts out the byte 1110 1111 (EFh) following its own mode. The controller reads at its own sample edge. Match the modes to read EFh. Then raise CS in the middle.
A model with an output delay of 5% of a clock period after each data change. A read within 10% of a data change is marked marginal: it works only if the hold time happens to be enough. The EFh manufacturer ID and the support for modes 0 and 3 are from the W25Q128JV datasheet.
That is 4 bytes × 8 bits = 32 clocks. At 10 MHz the transfer takes 32 ÷ 10 MHz = 3.2 µs. (Your MCU's datasheet gives its SPI speed limit in its timing table. The limit comes from the bus clock and a divider.)
CS does more than choose a chip. It marks the start and the end of one command. The flash treats a falling CS as "a new command begins". If your driver raises CS between the command byte and the data bytes, the flash sees a command alone, then a new command that starts with junk. The symptom is that only the first byte makes sense.
Turn on Raise CS after bit 4 to see it. Everything after the notch is lost. The fix is to hold CS low for the whole transaction. In DMA-driven code, check that the driver does not toggle CS per byte.
Plain SPI moves one bit per clock. Quad SPI (QSPI) uses four data wires, so one clock moves four bits. Octal SPI (OSPI) uses eight. Memory chips use these to run code straight from flash. The W25Q128JV supports a 133 MHz clock at 3.0 V to 3.6 V, and the datasheet gives an equivalent rate of 532 MHz in quad mode: 133 MHz × 4 bits = 532 Mbit/s, which is 66.5 MB/s.
Chapter 4
Work out how much baud mismatch a receiver can take, and see which bit fails first
You open a serial terminal to read your board's boot log. Instead of text you see a stream of odd symbols. You check the baud rate: 115200 on both sides. The settings match. Yet the characters are wrong.
The cause is a clock that is not what the code thinks it is. The board runs from a slower internal oscillator at start-up, so a "115200" divider gives a different real rate. To see why that breaks the text, we need to look at how a UART (universal asynchronous receiver-transmitter) works with no clock wire at all.
A UART link has a TX wire and an RX wire, crossed between the two chips. There is no clock wire. Instead, both sides promise to use the same speed, the baud rate, which counts symbols per second. For a plain UART one symbol is one bit.
The line rests at 1 (idle). To send a byte, the sender uses a frame. First comes a start bit, a 0, which signals "a byte begins now". Then 8 data bits come, least significant first. Then a stop bit, a 1, puts the line back to idle. This common layout is called 8N1: 8 data bits, no parity, 1 stop bit. A frame has 10 bits.
115200 baud: 1 ÷ 115200 = 8.68 µs per bit. One 10-bit frame takes 86.8 µs, so 115200 ÷ 10 = 11,520 bytes per second.
The receiver has its own clock. It runs the clock 16 times faster than the baud rate. This is 16× oversampling. It waits for the line to fall, which is the start of the start bit. Then it counts. After 8 ticks it is in the middle of the start bit. After each further 16 ticks it is in the middle of the next bit, and it reads the line there. Reading in the middle gives the most room for error on both sides.
The receiver counts from one single edge. Its error piles up with every bit. That is the problem. A tiny rate error that is harmless at bit 1 can ruin bit 9.
Slide the mismatch in the device below. The first bit to fail is not the first bit sent. It is the bit with the most time behind it.
The top wave is the frame for the letter U (0x55). The marks are where the receiver reads. Slide the receiver's rate error and watch the marks walk away from the bit centres.
A model. A positive number means the receiver's bits are longer than the sender's (a slow receiver). The receiver finds the start edge 1/16 of a bit late, as with a 16× sample clock, and reads at the middle tick of each bit. The device shows one-sided error, so a clean frame holds out to about 5%. The 2% to 3% budget keeps room for the other end, edge jitter and oscillator drift. The 5.26%, 3.3% and 2% figures are the derivation above (the last two from the Analog Devices note on UART clock accuracy).
A UART makes its baud rate by dividing a clock. With a 16 MHz clock and 16× oversampling the rule is baud = fclk ÷ (16 × divisor). We want 115200.
Many STM32 USARTs have such a fractional divider. The drift slider has a chip for the integer case so you can see it at the edge. Then the other end's error adds on top of that 3.55%.
Mismatched baud gives framing errors: the receiver reads a 0 where the stop bit should be a 1, and flags it. It also gives wrong characters. The measurement is simple. Probe TX and measure one bit width on a scope. At 115200 it should be 8.68 µs. If it is 9.1 µs, the sender runs 4.8% slow. Then find the cause: a wrong clock source, a wrong divisor, or an oscillator that is not the one the code assumes.
The UART frame is only a rule about time. The voltages come from another layer. A microcontroller pin gives 0 V and VDD, which is "TTL level". RS-232 swings the line on both sides of zero and inverts it, so a negative voltage is a 1. A driver chip converts between the two. RS-485 sends the same frames over a twisted pair as a difference between two wires. It reaches farther, shrugs off common noise, and lets many nodes share one pair, as long as only one node sends at a time. A transceiver chip with a direction pin does the switching.
Chapter 5
Compare the time of one sensor read on I2C and on I3C, and see which rules a legacy device adds
A phone holds a dozen sensors: motion, light, pressure, touch. Each needs a bus. Each also needs an extra interrupt wire to say "I have data", because an I2C target cannot speak first. The wires add up, and so does the pull-up current that every open-drain line wastes.
I3C is the bus designed to fix this. It keeps the same two wires, SCL and SDA, so the board does not change. It changes what happens on them.
1. Push-pull data. I2C keeps both lines open-drain, which limits speed to the rise time of a resistor and a capacitor (Chapter 2). I3C uses open-drain only when it needs compatibility, for example during arbitration. It "switches to push-pull outputs whenever possible". A push-pull edge is fast and sharp, so the clock can be much quicker. The default SDR (single data rate) mode runs up to 12.5 Mbit/s.
2. Dynamic addresses. In I2C each chip has a fixed address that the maker chose. Two chips of the same type clash. In I3C every device has a 48-bit unique ID. At start-up the controller runs a dynamic address assignment: devices announce their ID, and the controller gives each one a short bus address. Clashes cannot happen.
3. In-band interrupts. A target can pull SDA low to request attention, with no extra wire. The controller sees the request, reads who sent it, and services it. This is an in-band interrupt (IBI). Polling is no longer needed.
4. Faster modes. On top of SDR, I3C has HDR (high data rate) modes. HDR-DDR sends data on both clock edges: a 12.5 MHz clock carries 25 Mbit/s raw, about 20 Mbit/s effective after overhead. HDR-TSP, the ternary mode, sends symbols with three levels and reaches about 33.3 Mbit/s effective.
Think of the address change as a classroom. In I2C each student wears a name tag printed at the factory, and two students with the same tag cause a mix-up. In I3C each student has a unique serial number and the teacher hands out short tags on the first day. The data flow is the same: the controller sends a frame with a tag, and one target answers. Only the way the tag is chosen has changed.
Real boards still have I2C-only chips. I3C allows them on the bus, with rules. An old chip sees the same SCL. If I3C used fast pulses, the old chip could mistake them for clocks. So the I3C controller keeps SCL high pulses short, under 50 ns, because Fast-mode I2C chips are required to ignore spikes under 50 ns with an input filter (UM10204 Table 10: tSP, up to 50 ns). Known I3C targets drive SCL high for at most 40 ns.
The word "required" matters. UM10204 requires the filter for Fast-mode and Fast-mode Plus devices. Not every old chip in the field has one. A chip without the filter can see a false clock and misbehave under I3C timing. The HDR-TSP mode breaks the 50 ns limit, so it can only be used on a bus with no legacy I2C devices at all.
Use the device below to read 6 bytes from a sensor on each bus type. Then add a legacy chip.
Choose a mode. The bars show how long one read takes on a log scale. Add a legacy I2C chip to the bus and see which modes it allows.
Illustrative: every row uses the same frame, 27 + 9 × N bits (address and write, register byte, address and read, N data bytes, each with a ninth bit). The HDR rows use the effective rates quoted for those modes, which already count their overhead. Real I3C frames have their own headers. Rates: I2C from UM10204, I3C from the public MIPI I3C summary (HDR-TSP 33.3 Mbit/s effective).
Why does it matter? A fusion filter that reads an IMU at 1 kHz spends 203 µs of every millisecond, about 20%, on the bus at Fast-mode. On I3C SDR the same read uses 0.65%. The CPU and the bus both get time back. See robot real-time performance for why that budget matters in a control loop.
The in-band interrupt helps in another way. A sensor that polls every 10 ms finds an event 5 ms late on average, and it costs 100 reads per second. An IBI delivers the event within the time of one short transfer, and costs no idle reads.
Chapter 6
Step through what happens in the first second after you plug in, then count the bytes a camera needs per microframe
You plug a camera into a Linux board. Nothing appears. The kernel log says device descriptor read/64, error -71. You try another cable and it works. You plug in a second camera, and now the second one is refused with a message about not enough bandwidth.
Both faults make sense once you know the order of events at plug-in, and what a camera asks the bus to carry. This chapter covers both.
USB is not a peer-to-peer bus. One host controls everything. A device cannot send anything until the host asks. The host asks often, in a fixed schedule. At full speed (12 Mbit/s) time is cut into 1 ms frames. At high speed (480 Mbit/s) it is cut into 125 µs microframes, eight per frame.
The host and the device exchange data on endpoints, numbered mailboxes on the device. USB has four kinds of transfer:
A device that has just arrived knows nothing about the host, and the host knows nothing about the device. Enumeration is the routine that fixes this. The host talks to the device through endpoint 0, at address 0, and asks for descriptors. A descriptor is a small table in the device's memory that describes it. The device descriptor is 18 bytes and holds the vendor ID, product ID, device class and the packet size of endpoint 0 (8, 16, 32 or 64 bytes). The configuration descriptor lists the interfaces and endpoints, and its field wTotalLength tells the host how many bytes to read in all.
Step through it below. Then switch on the fault and see where the log stops.
Press Next step to walk the host and the device through enumeration. Turn on the fault and watch the second step.
A model of the standard sequence. The reset is a long SE0 signal (the USB 2.0 specification requires at least 10 ms; the exact time varies by host). The log lines are written in the style of the Linux kernel but are illustrative, not captured. The 64-byte first read and the message text come from the Linux hub driver.
Look at step 2 again. The host does not know the packet size of endpoint 0 yet, so it asks for up to 64 bytes. The device must reply. If it does not, the host retries, and then gives up. That is the device descriptor read/64 message, and -71 is the Linux code EPROTO, a protocol error on the wire. Suspects: a bad cable, a noisy connector, a device that boots too slowly, or edges that are too ringy (Chapter 7). The tools are lsusb -v to see what did arrive, and usbmon to capture the traffic.
A camera uses an isochronous endpoint. Each microframe it may send one packet of up to 1024 bytes. A high-bandwidth endpoint may send up to three packets in the same microframe (USB 2.0 spec, chapter 5). At 8,000 microframes per second, the most one endpoint can move is:
3 × 1024 B × 8,000 = 24,576,000 B/s = 24.6 MB/s ≈ 197 Mbit/s
The bus as a whole has a limit too. The standard allows at most 80% of a microframe for periodic traffic (interrupt and isochronous), so that control and bulk can still run. Each packet also carries overhead: a token, handshakes and gaps.
A raw video format called YUY2 uses 2 bytes per pixel. Here are three cameras.
That is why webcams compress. A camera that sends MJPEG video (each frame a JPEG) uses a fraction of the bytes. Count them below. The bus limit in the device is a model with an assumed 40 byte-times of overhead per packet.
Pick a camera format and add cameras. The bar shows the bytes per microframe against the periodic limit. Find the first count that does not fit.
The 10 MB/s MJPEG rate is an assumption for illustration. The limits: 1024 bytes per packet and up to 3 packets per microframe per endpoint; at most 80% of a 125 µs microframe for periodic traffic, which at 480 Mbit/s is 100 µs, or 6,000 byte-times. Packet overhead of 40 byte-times is assumed. A real host controller reserves time per endpoint and may be stricter.
When the sum is too large, Linux refuses the new device. The kernel function usb_hcd_alloc_bandwidth checks whether a new configuration fits, and returns an error if it does not. The fix is to lower the frame rate, pick a compressed format, or put each camera on its own controller. The tool to check it is the sum: add each endpoint's bytes per microframe.
Chapter 7
Put one fast edge in front of a logic analyser and a scope, and see why only one of them shows the ringing
A board works on your bench with a short jumper. In the product, the same SPI link runs over a six-inch trace and the flash read fails once an hour. You clip on a logic analyser. It shows perfect ones and zeros, and the decoded bytes are right. The analyser says the bus is clean. The chip says it is not.
Both are telling the truth. The analyser answers a different question. To see why, we need to treat a wire as a wire, and not as an idea.
A 10 MHz clock looks slow. But its edges are not slow. If an edge rises in 1 ns, it holds fast changes, and fast changes mean high frequencies. A good rule ties the two. The bandwidth of an edge, the highest frequency that matters, is about 0.35 divided by the rise time.
Here is why. Model the wire as one resistor and one capacitor. The rise from 10% to 90% takes 2.2 × RC. The signal passes frequencies up to f = 1 ÷ (2π × RC). Multiply the two:
tr × f = 2.2 ÷ (2π) = 0.35, so BW ≈ 0.35 ÷ tr. A 1 ns edge needs about 350 MHz.
The clock rate does not matter here. The edge speed does. A new chip with a faster output driver can ruin an old board without changing the clock. Chapter 1 told you to choose the slowest slew rate that works. This is the reason.
A short wire is a plain connection: the voltage is the same everywhere. A long wire is a transmission line: the edge needs time to travel, and it behaves like a wave. When the wave reaches the end, a mismatch bounces part of it back. This is a reflection. The bounce travels back, meets the driver, and bounces again. The result on the pin is ringing: the voltage overshoots, dips, and settles over several trips.
How long does a trip take? Light moves 11.8 inches per nanosecond in air, which is 84.7 ps per inch. In a circuit board the wave is slower by the square root of the effective dielectric constant. For FR4 that constant is roughly 3 to 4.2, an assumption that depends on the board. So the delay is:
84.7 ps/in × √3 ≈ 147 ps/in, and 84.7 ps/in × √4.2 ≈ 174 ps/in: about 150 to 180 ps per inch
A six-inch trace takes about 1 ns one way. That is as long as our fast edge. The wire is now "electrically long", and it rings.
The cure is termination: make the end of the wire absorb the wave. The cheap form is a series resistor near the driver, often 22 to 33 Ω. It adds to the driver's own output resistance so that the total is close to the trace impedance. Then the first reflection returns and finds no reason to bounce again. The edge also gets a little slower, which lowers its bandwidth. Shorter wires and slower slew help in the same way.
Neighbouring wires add crosstalk: a fast edge on one trace couples a small spike into the next. Keep clocks away from data and keep return paths short.
A logic analyser does one thing: at each sample time it asks "is the voltage above or below a threshold?" and records a 1 or a 0. It never records the in-between. If the ringing dips under the threshold for 0.5 ns between two samples, the analyser misses it. A real chip with a fast input will see that dip as a second clock edge.
A scope records the voltage itself, but only up to its own bandwidth. A scope that is too slow rounds off the very ringing you hunt. The rule of thumb is to use a scope with at least 5 times the bandwidth of the signal. Here is the sum behind it. The scope has its own rise time, 0.35 ÷ BW. The measured rise time is the root of the sum of squares. If the scope is 5 times faster than the edge, the scope adds 0.2 × tr, so the measured time is tr × √(1 + 0.04) = 1.02 × tr. The error is 2%. At 2 times faster the error grows to 12%.
For the analyser, a similar rule of thumb says sample at 4 to 10 times the signal's switching rate. That is the course plan's rule of thumb, not a standard, but the direction is sure: the faster you sample, the more you see. Test both with the device.
The faint blue wave is the true voltage on the pin. The purple line is what a scope of the chosen bandwidth shows. The yellow steps are what a logic analyser records. Slow the scope, slow the analyser, add the series resistor.
A model. The pin is a second-order system with a ring period of four trip times (160 ps per inch assumed), damping 0.1 without the resistor and 0.6 with it. The scope is a one-pole filter at its stated bandwidth. The analyser compares the voltage to half of VDD at each sample. The numbers are illustrative; the 0.35 ÷ tr rule is exact for a one-pole system.
Chapter 8
Turn five questions about rate, distance, pins, noise and timing into the short list of buses that can do the job
A team puts a motion sensor on the end of the robot arm. The main board is two metres away. They run I2C down the cable, because the sensor library already speaks I2C. In the lab it works at 100 kHz. At 400 kHz it fails when the motors start.
Nobody made a coding mistake. They picked a bus built for centimetres and used it for metres. This chapter gives you the questions to ask before the wire is chosen.
I2C, SPI and UART are for short links on a board or between boards. They use few pins and need no special chips. I2C is the slowest and the cheapest in wires. SPI is faster and needs more wires. UART needs two wires and no clock, and its framing is the most common way to talk to a module.
CAN is a differential bus for noisy places, like cars and robots. Many nodes share one pair. When two nodes talk at once, the one with the higher-priority message wins without losing a bit, and every frame has a CRC check. The newest member, CAN XL, runs at 20 Mbit/s and beyond, with up to 2048 bytes in one frame (CAN in Automation, the CiA).
EtherCAT is for motion control with many axes. It runs on Ethernet wiring. A single frame travels through all drives, and each one reads its data and writes its reply as the frame passes. The timing is tight and the same on every cycle.
MIPI CSI-2 carries camera images from a sensor to a processor. It uses fast differential lanes over a short flex cable. The D-PHY physical layer, in version 3.0, "doubles the data rate of D-PHY's standard channel to 9 Gigabits per second" per lane (MIPI Alliance). Longer links use other physical layers, which Chapter 9 names.
USB suits devices that plug in and out, and streams of data. I3C replaces I2C for sensors where speed and interrupts matter.
Two more ideas help with the last question. Latency is the time from "the data is ready" to "the processor has it". Throughput is how much data moves per second. A bus can have high throughput and poor latency, like a lorry: it carries a lot but leaves on a schedule. For a control loop that runs every millisecond, ask how late the data may be in the worst case, and check that the bus can promise it.
Use the device below. Set the rate and distance you need. See which buses pass, and which fail because they are too slow, too short in reach, or not robust.
Move the two sliders to your requirement. The marks show where it falls on each bus's typical rate and reach. Then turn on the noisy-place switch.
The rates and reaches are typical and rough. They are rules of thumb, except where a number comes from a source in the Field Guide: CAN XL 20 Mbit/s, D-PHY v3.0 9 Gbit/s per lane, USB 2 at 480 Mbit/s, SDR I3C at 12.5 Mbit/s. A real design must check the data sheets of the exact parts, the cable and the connector.
Let us test the arm sensor, with assumptions written down. The bus is Fast-mode at 3.3 V.
So on paper the bus is legal. In practice there is almost no margin, and no noise immunity. The fix is a differential bus: for example, convert to CAN or RS-485 at the arm, or use a link chip that sends I2C differentially. The numbers decided it before any scope was used.
Chapter 9
Keep the numbers, the symptom checklist and the bus-recovery code on one page
Every bus in this lesson failed in a way that left a mark on the wire. A stuck bus holds SDA low. A slow edge misses the sample point. A wrong mode shifts the bits. A wrong divider breaks the stop bit. A missing pinmux leaves SCL flat. A bad cable stops the first 64-byte read. A fast edge rings. In each case a scope shows the cause before a debugger does. Trust the driver only after you have looked at the wire.
| Item | Value | Source |
|---|---|---|
| I2C bus clear | up to 9 SCL clocks, then STOP (Linux) | UM10204 3.1.16; Linux i2c core |
| I2C addresses | 128 codes, 16 reserved, 112 usable | UM10204 3.1.12 |
| I2C rates and rise times | 100 kbit/s 1000 ns; 400 kbit/s 300 ns; 1 Mbit/s 120 ns; Hs 3.4 Mbit/s | UM10204 Table 11 |
| I2C bus capacitance | 400 pF (Sm, Fm), 550 pF (Fm+) | UM10204 Table 11 |
| Pull-up window | Rp(min) = (VDD − 0.4 V) ÷ IOL; Rp(max) = tr ÷ (0.8473 × Cb) | UM10204 section 7.1 |
| Fast-mode at 3.3 V | floor 967 Ω; window closes at 366 pF | worked from the two lines above |
| SPI flash ID | 9Fh returns EFh 40h 18h (W25Q128JV-IQ/JQ); modes 0 and 3 | Winbond W25Q128JV datasheet |
| Quad SPI flash | 133 MHz × 4 bits = 532 Mbit/s (3.0 to 3.6 V) | Winbond W25Q128JV datasheet |
| UART 115200 8N1 | 8.68 µs per bit; 11,520 bytes/s; ideal limit 5.26%; plan on 2% to 3% total | worked; Analog Devices UART clock note |
| I3C | SDR 12.5 Mbit/s; HDR-DDR 25 raw, 20 effective; HDR-TSP 39.5 raw, 33.3 effective; 50 ns spike filter | I3C summary; UM10204 Table 10 |
| USB | FS 12 Mbit/s; HS 480; 125 µs microframe; 1024 B isochronous (HS); up to 3 per microframe; 80% periodic | Beyond Logic; USB 2.0 spec ch. 5 |
| Edge bandwidth | BW ≈ 0.35 ÷ tr; FR4 about 150 to 180 ps per inch; scope ≥ 5× the signal | derived above |
| MIPI D-PHY v3.0 | 9 Gbit/s per lane (standard channel) | MIPI Alliance |
| CAN XL | 20 Mbit/s and beyond; up to 2048 bytes per frame | CAN in Automation |
| USB4 Version 2.0 | 80 Gbit/s symmetric; 120 Gbit/s asymmetric | USB4 summary |
| MIPI A-PHY | up to 15 m; 2 to 16 Gbit/s downlink (v1.0, v1.1) | MIPI Alliance |
| I3C in memory modules | DDR5 uses I3C for serial presence detect (2021) | I3C summary |
Pick a symptom. The device gives the first measurement to make and the usual fix.
The checks come from the chapters above. Each one names a measurement, not a guess.
This is the machine behind the hero, in C. It runs on any Cortex-M part once you give it six pin helpers: scl_low, scl_release, scl_read, sda_low, sda_release and sda_read. Each helper uses open-drain GPIO. "Release" means switch to input and let the pull-up work. It writes one byte, honours clock stretching, and reports a stuck line instead of hanging.
c typedef enum { I2C_OK, I2C_NACK, I2C_STUCK_SCL, I2C_STUCK_SDA, I2C_ARB_LOST } i2c_err_t; /* release SCL, then wait while a target stretches the clock */ static bool scl_high_wait(void) { scl_release(); for (int i = 0; i < 1000; i++) { /* about 1 ms at 1 us per try */ if (scl_read()) return true; delay_us(1); } return false; /* SCL held low: do not hang */ } static i2c_err_t i2c_write_byte(uint8_t b) { for (int i = 7; i >= 0; i--) { bool one = (b >> i) & 1; scl_low(); delay_us(2); one ? sda_release() : sda_low(); /* change SDA only while SCL is low */ delay_us(3); if (!scl_high_wait()) return I2C_STUCK_SCL; delay_us(5); if (one && !sda_read()) return I2C_ARB_LOST; /* sent 1, read 0: another controller won */ } scl_low(); sda_release(); delay_us(5); /* ninth clock: the ACK slot */ if (!scl_high_wait()) return I2C_STUCK_SCL; bool nack = sda_read(); delay_us(5); scl_low(); return nack ? I2C_NACK : I2C_OK; } /* bus clear: up to 9 clocks until the target lets go of SDA, then STOP */ i2c_err_t i2c_bus_clear(void) { sda_release(); if (!scl_high_wait()) return I2C_STUCK_SCL; /* clocks cannot fix this: reset pin or power */ for (int i = 0; i < 9 && !sda_read(); i++) { scl_low(); delay_us(5); if (!scl_high_wait()) return I2C_STUCK_SCL; delay_us(5); } if (!sda_read()) return I2C_STUCK_SDA; /* still held after 9 clocks */ scl_low(); sda_low(); delay_us(5); /* STOP: SDA rises while SCL is high */ scl_release(); delay_us(5); sda_release(); return I2C_OK; }
Use it like this. If a transfer returns I2C_STUCK_SDA or times out, switch the pins from the I2C block to plain GPIO, call i2c_bus_clear(), switch the pins back, and retry. This follows UM10204 section 3.1.16 and what the Linux generic recovery code does (nine clocks, then STOP).
The pull-up window and the UART budget, in two lines:
(VDD − 0.4 V) ÷ IOL ≤ Rp ≤ tr ÷ (0.8473 × Cb) |baudreal − baud| ÷ baud ≤ about 2% to 3%, shared by both ends
The buses here are the short ones. Past them, the same ideas scale up. USB4 Version 2.0 runs at 80 Gbit/s symmetric, or 120 Gbit/s one way in asymmetric mode. I3C already sits in DDR5 memory modules for serial presence detect. MIPI A-PHY reaches up to 15 m for car cameras, at 2 to 16 Gbit/s in version 1. Each one still has a rise time, a clock, a frame and a cable. Read the waveform first.
Opened for this lesson: NXP UM10204, I2C-bus specification and user manual, Rev. 7; the Linux kernel I2C core (i2c_generic_scl_recovery) and USB hub driver; Beyond Logic, USB in a NutShell; the USB communications, I3C and USB4 summaries; the Winbond W25Q128JV datasheet; the Analog Devices note on UART clock accuracy; Memfault Interrupt, I2C in a Nutshell; the MIPI D-PHY and A-PHY pages; CAN in Automation, CAN XL; USB-IF USB4. Named in the course plan but not opened: Johnson and Graham, High-Speed Digital Design; Making Embedded Systems, 2nd edition; TI SLVA689.
Stated from the standard but not re-opened here: up to 3 isochronous packets per high-speed microframe (USB 2.0 specification, chapter 5); the meaning of Linux error -71 as EPROTO; the STM32F4 GPIO register names (RM0090); the 160 ps per inch figure, which is derived from the speed of light and an assumed dielectric constant. Illustrative numbers in the devices are labelled as such. The I3C HDR-TSP rate here (33.3 Mbit/s effective) comes from a public summary and may differ from the figure in the full MIPI specification (the MIPI white paper lists 39.5 Mbit/s raw).
Now try the Teach button: explain the nine-clock fix on a whiteboard. Or go back to the hero and break the bus again, this time before you read the read-out.