Skip to content
LumenaryAcademy
Embedded 70 min

Buses and interfaces

How chips talk to each other — UART, I²C, SPI and CAN bit by bit, USB and Ethernet in outline — and how to find out why they are not talking.

Code tested · 6AI-draftedAwaiting review by an electrical engineer

Your guides: Chloe · The Physicist, Margaret · The Bench Engineer, Gideon · The Design Reviewer

MotivationH

Chips have to talk

Open any gadget and you will find a microcontroller surrounded by other chips: a temperature sensor, a flash memory, a display, a radio module, a motor driver. They are made by different companies, run at different speeds, and must exchange data over a few copper traces. A car is the same story at a larger scale, with dozens of control units spread across several metres of wiring harness, all of which must agree on what the brake pedal is doing.

Early computers moved data in parallel: eight or more wires, one per bit, plus a clock. That is fast over a few centimetres but costs many pins, and over longer distances the bits drift apart in time (skew). Almost every modern interface is serial: one or two data wires, one bit after another, and clever rules about when to look. This lesson goes through the serial buses a microcontroller engineer meets every day, bit by bit, and ends with the tool that makes them debuggable: the logic analyser. Lumenary CS's networking lesson picks up where the wires end, with packets, addresses and protocols layered on top.

DefinitionsH

The vocabulary of interfaces

Definition— Synchronous and asynchronous serial links

A synchronous link sends a clock signal alongside the data, so the receiver knows exactly when to sample each bit (SPI, I²C). An asynchronous link sends no clock: transmitter and receiver agree on a bit rate in advance and the receiver re-times itself on edges in the data (UART, CAN, USB, Ethernet).

A few more distinctions recur:

  • Duplex. Full duplex links carry data both ways at once (UART with separate TX and RX wires, SPI); half duplex links take turns on shared wires (I²C, RS-485).
  • Signalling. Single-ended signals are voltages measured against ground, fine on a board. Differential signals use a pair of wires driven in opposite directions; the receiver looks only at the difference, so noise that hits both wires equally cancels. Everything that leaves a board for more than a metre or runs fast — CAN, RS-485, USB, Ethernet — is differential.
  • Drivers. A push-pull output actively drives both high and low. An open-drain (or open-collector) output can only pull low; a resistor pulls the line high when no one is pulling it down. Several open-drain outputs on one wire form a wired-AND: the line is high only if every device lets go.
  • Topology and roles. Some links are point to point; others are buses with many devices. The device that starts transfers is the controller and the others are targets or peripherals (older documents use the terms master and slave).
Worked examplesH

UART: the oldest serial link

A UART (universal asynchronous receiver–transmitter) sends bytes over one wire in each direction. The line idles high. Each byte travels in a frame: a start bit (low), the data bits least significant first, an optional parity bit, and one or two stop bits (high). The most common format, "8N1", has 8 data bits, no parity and 1 stop bit, so every byte costs 10 bit times.

idleidlestartb0b1b2b3b4b5b6b7stop0110100101one bit time = 1 / baud rate
The byte 0x4B (the letter K) as an 8N1 UART frame. The falling edge of the start bit tells the receiver a frame has begun; it then samples each bit in its middle (dashed lines), data bits least significant first, and checks that the stop bit is high. At 115,200 baud each bit lasts 8.68 µs.

The baud rate is the number of symbols per second, here equal to bits per second. Common rates are 9,600, 115,200 and, on fast links, 1 to 3 Mbit/s. Because there is no clock wire, the two ends must agree on the rate, and the receiver re-synchronises on every start bit. A typical receiver samples the line 16 times per bit: when it sees the line go low it waits 8 samples to reach the middle of the start bit, checks it is still low (otherwise it was a glitch), then takes one sample every 16 for each remaining bit. Small differences between the two clocks accumulate across the frame, so the question is how much difference is too much. The baud rate itself comes from dividing the peripheral clock by an integer, which usually cannot hit a standard rate exactly.

python
def uart_frame(byte):
    """8N1: a start bit (0), eight data bits least significant first, a stop bit (1)."""
    return [0] + [(byte >> i) & 1 for i in range(8)] + [1]

print("0x4B ('K') on the wire:", uart_frame(0x4B))

# 1. Baud-rate error from an integer divider with 16x oversampling.
print("\nclock (MHz)   baud     divisor  actual baud   error")
for f_clk in (16e6, 48e6, 14.7456e6):
    for baud in (9600, 115200, 1_000_000):
        div = round(f_clk / (16 * baud))
        actual = f_clk / (16 * div)
        print(f"{f_clk / 1e6:10.4f} {baud:>9} {div:>8} {actual:>12.0f} {100 * (actual - baud) / baud:+7.2f}%")

# 2. What a mismatch does to a receiver that samples 16 times per bit.
def receive(byte, tx_baud, rx_baud, phase):
    """Simulate one frame. The receiver finds the start edge on its 16x sample clock, then
    samples each bit 8 + 16k ticks later. Returns the byte, or None on a framing error."""
    bits = uart_frame(byte) + [0]                  # the next frame's start bit follows at once
    def line(t):                                   # the line's level at time t (seconds)
        i = int(t * tx_baud)
        return bits[i] if 0 <= i < len(bits) else 1
    tick = 1 / (16 * rx_baud)
    k = 0
    while line((k + phase) * tick) == 1:           # look for the falling edge of the start bit
        k += 1
    samples = [line((k + phase + 8 + 16 * j) * tick) for j in range(10)]
    if samples[0] != 0 or samples[9] != 1:
        return None
    return sum(b << i for i, b in enumerate(samples[1:9]))

print("\nreceiver clock error   bytes received correctly (of 256 x 4 phases)")
for err in (0.0, 0.02, -0.02, 0.04, -0.04, -0.045, -0.05, 0.055, 0.06):
    ok = sum(receive(b, 115200, 115200 * (1 + err), ph) == b
             for b in range(256) for ph in (0.0, 0.25, 0.5, 0.75))
    print(f"{100 * err:+18.1f}%   {ok:5}")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Read the divider table first. A 16 MHz clock cannot make 115,200 baud: the nearest divisor, 9, gives 111,111 baud, 3.55% slow. A 48 MHz clock gets within 0.16%, and the odd-looking 14.7456 MHz crystal hits every standard rate exactly, which is why such "baud-rate crystals" exist. (Many modern UARTs have fractional dividers that fix the problem in hardware.)

The second table shows the cliff. Every byte arrives intact up to a mismatch of about +5.5% or −4.5%, and then almost nothing does. The receiver's sample of the stop bit lands about 9.5 bit times after the start edge; if its clock is 5% slow, that sample falls 9.5/0.95=109.5/0.95 = 10 bit times in, past the end of the stop bit and onto the next frame's start bit. The simulation is the ideal case, with perfect edges. Real lines have slow edges, noise and their own uncertainty in finding the start edge, and the error budget is shared between two clocks that may each be off in opposite directions, so the usual design rule is to keep each end within about 2%. The 16 MHz board above, at 3.55%, works with one partner and fails with another: a classic intermittent bug.

Worked examplesH

I²C: two wires, many chips

I²C (inter-integrated circuit), introduced by Philips in 1982, connects many low-speed chips with two open-drain wires: SCL (clock), driven by the controller, and SDA (data). Each wire has one pull-up resistor; any device pulls it low; nobody ever drives it high. Every target has an address, usually 7 bits, set by its maker (often with one or two pins to choose among a few values).

3.3 Vpull-upsSDASCLcontrollermicrocontrollertemperaturesensor, 0x48EEPROM0x50motionsensor, 0x68
An I²C bus. Two pull-up resistors hold SDA and SCL high; the controller and every target hang off the same two wires and can only pull them low, so the lines form a wired-AND. Each target answers only to its own address (the addresses shown are typical for such parts).

A transfer goes like this:

  1. START: the controller pulls SDA low while SCL is high. (Data may change only while SCL is low, so a change while SCL is high is a special signal.)
  2. Address: the controller clocks out the 7-bit address and an eighth bit, R/W: 0 to write, 1 to read.
  3. ACK: on the ninth clock the controller releases SDA, and the addressed target pulls it low to acknowledge. If no one does — a NACK — no device has that address, or it is busy.
  4. Data: bytes follow, each acknowledged by whoever received it. To read a register, the controller usually writes the register number, then sends a repeated START and the address with R/W = 1, and reads.
  5. STOP: the controller releases SDA while SCL is high.

Standard mode runs at 100 kHz, Fast mode at 400 kHz and Fast-mode Plus at 1 MHz. Two subtleties follow from the open-drain wiring. In clock stretching, a slow target holds SCL low after the controller releases it, and the controller must wait until SCL actually rises; a controller that ignores stretching loses data. In arbitration, two controllers that start at once both watch SDA, and one that releases the line (sending a 1) but sees it low (someone sent a 0) knows it has lost and backs off; the same idea, on a larger scale, is the heart of CAN below.

The pull-up resistors are a real design decision. Too large and the bus capacitance (every pin and centimetre of trace adds some, up to 400 pF allowed) charges too slowly, so the rising edges are late; too small and the devices cannot pull the line low enough. Charging a capacitance CbC_b through RpR_p gives v(t)=VDD(1−e−t/RpCb)v(t) = V_{DD}(1 - e^{-t/R_pC_b}), so the rise from 30% to 70% of VDDV_{DD}, the rise time the specification limits, takes RpCbln⁡(0.7/0.3)=0.8473 RpCbR_pC_b\ln(0.7/0.3) = 0.8473\,R_pC_b.

python
import math

VDD, VOL = 3.3, 0.4                       # supply, and the highest allowed "low" voltage
# mode: (clock, maximum rise time, current a device must be able to sink at VOL)
MODES = {"Standard": (100e3, 1000e-9, 3e-3), "Fast": (400e3, 300e-9, 3e-3), "Fast-mode Plus": (1e6, 120e-9, 20e-3)}

# A pull-up charges the bus capacitance: v(t) = VDD (1 - exp(-t / RC)).
# The rise time is measured from 30% to 70% of VDD:
k = math.log(0.7 / 0.3)
print(f"rise time (30% -> 70%) = {k:.4f} RC\n")

print(f"{'mode':15} {'R min':>8} " + " ".join(f"{'R max @' + str(c) + ' pF':>14}" for c in (50, 100, 200, 400)))
for name, (f, t_rise, i_ol) in MODES.items():
    r_min = (VDD - VOL) / i_ol                     # strong enough that a device can pull it low
    r_max = [t_rise / (k * c * 1e-12) for c in (50, 100, 200, 400)]   # weak enough to rise in time
    cells = " ".join(f"{r:>12.0f} {'ok' if r >= r_min else '--'}" for r in r_max)
    print(f"{name:15} {r_min:>8.0f} {cells}")

# Power: while a line is held low, the pull-up wastes VDD^2 / R.
for r in (1000, 2200, 4700, 10000):
    print(f"pull-up {r:>6} ohm: {1000 * VDD**2 / r:5.2f} mW per line while low")
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

On a small board with 100 pF of bus capacitance in Fast mode, any pull-up from 967 Ω to 3,541 Ω works, and 2.2 kΩ is a common choice. At 400 pF Fast mode is impossible with 3 mA drivers (the "--"): the bus must slow down, be split with a buffer, or use stronger drivers. The last lines are why battery-powered designs prefer larger pull-ups and slower buses: every low bit burns VDD2/RV_{DD}^2/R.

I²C's successor for sensors, I3C from the MIPI Alliance, keeps two wires and backward compatibility with I²C targets but adds push-pull signalling at 12.5 MHz, dynamic addresses and in-band interrupts. SMBus and PMBus, used for batteries and power supplies, are stricter dialects of I²C.

DefinitionsH

SPI: two shift registers in a ring

SPI (serial peripheral interface) is the simplest and fastest of the board-level buses. It has four signals: SCLK (clock, from the controller), MOSI (controller out, peripheral in), MISO (controller in, peripheral out), and an active-low chip select (CS) for each peripheral (newer documents rename the data lines COPI/CIPO or SDO/SDI). Inside, it is two 8-bit shift registers wired in a ring: on every clock both shift by one place, so after eight clocks the controller and the peripheral have exchanged a byte. To read, the controller must write something, if only zeros. There are no addresses (the chip select chooses), no acknowledgements and no protocol overhead, and with push-pull drivers the clock can run at tens of MHz; quad SPI and octal SPI use four or eight data lines to read flash memories fast enough to execute code from them directly.

Definition— SPI mode

The mode of an SPI link is the pair (CPOL, CPHA). CPOL is the clock's idle level (0 low, 1 high). CPHA says on which clock edge data is sampled: 0 on the first (leading) edge after chip select falls, with data set up before it; 1 on the second (trailing) edge.

ModeCPOLCPHAClock idlesData sampled on
000lowrising edge
101lowfalling edge
210highfalling edge
311highrising edge

Mode 0 is the most common, and many parts accept 0 or 3. A wrong mode usually gives data shifted by one bit, so a sensor's "who am I" register that should read 0x6B comes back as 0xD6 or 0x35: a doubling or a halving is the signature of a mode mismatch.

ComputationC

CAN: a bus that settles arguments

CAN (controller area network) was developed at Bosch for cars and presented in 1986; the first production car to use it appeared in 1991, and it now runs through vehicles, factory machines, lifts, medical equipment and robots. A CAN bus is one twisted pair, CAN_H and CAN_L, terminated by a 120 Ω resistor at each end. A bit is dominant (0) when a transceiver drives the pair apart (about 3.5 V and 1.5 V) and recessive (1) when no one drives it and the termination pulls the two wires together. A dominant bit from any node overrides recessive bits from all the others: the bus is a wired-AND, like I²C's lines but differential and robust over tens of metres.

There are no addresses of devices. Each frame begins with an identifier (11 bits, or 29 in the extended format) that says what the data is ("wheel speeds", "engine temperature"), and it doubles as a priority. Any node may start sending when the bus is idle, and when several start at once they arbitrate: each sends its identifier bit by bit while listening to the bus, and a node that sends a recessive 1 but hears a dominant 0 knows a more important frame is on the bus, stops sending and becomes a receiver.

python
# CAN arbitration. 0 is "dominant" (a transceiver drives the bus), 1 is "recessive" (nobody drives it),
# so the bus is the AND of every bit being sent: any single 0 wins.
nodes = {"brakes": 0x123, "steering": 0x125, "engine": 0x1A0, "radio": 0x320}

def arbitrate(nodes, width=11):
    sending = dict(nodes)
    print("bit  " + "  ".join(f"{name:>8}" for name in nodes) + "   bus")
    for bit in reversed(range(width)):                     # identifiers go out most significant bit first
        sent = {name: (ident >> bit) & 1 for name, ident in sending.items()}
        bus = min(sent.values())                           # wired-AND: dominant 0 overrides recessive 1
        row = []
        for name in nodes:
            row.append(f"{sent[name]:>8}" if name in sent else f"{'':>8}")
        lost = [name for name, b in sent.items() if b == 1 and bus == 0]
        print(f"{10 - bit:3}  " + "  ".join(row) + f"   {bus}" + (f"   {', '.join(lost)} stop{'s' if len(lost) == 1 else ''}: sent 1, read 0" if lost else ""))
        for name in lost:
            del sending[name]                              # it becomes a receiver and retries later
    (winner,) = sending
    return winner

winner = arbitrate(nodes)
print(f"\n{winner} (ID 0x{nodes[winner]:03X}) wins and its frame goes through undamaged;")
print("the lowest identifier always wins:", winner == min(nodes, key=nodes.get))
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Row 0 is the identifier's most significant bit, sent first. The radio drops out at the second bit, the engine at the fourth, the steering at the ninth, and the brakes' frame continues as if no one else had tried: the arbitration is non-destructive, so no bus time is wasted on collisions, and the losers simply try again when the bus is free.

The rest of a CAN frame is built for reliability: a length field, up to 8 data bytes, a 15-bit CRC, and an acknowledge slot in which every receiver that got the frame correctly drives a dominant bit. To keep receivers synchronised, a transmitter inserts an opposite stuff bit after five identical bits. Any node that spots an error destroys the frame with an error flag, and the sender retransmits; nodes count their own errors and take themselves off the bus if they become faulty, so one broken unit cannot jam a car. Classic CAN runs at up to 1 Mbit/s over about 40 m. CAN FD (2012) switches to a faster bit rate after arbitration, typically 2 to 8 Mbit/s, and carries up to 64 bytes; CAN XL goes to about 20 Mbit/s and 2,048 bytes. Cars also use LIN, a cheap single-wire bus at 20 kbit/s for windows and seats, and, increasingly, Ethernet.

ExplanationH

USB and Ethernet, in outline

USB connects a device to a host computer. The host controls everything: it polls each device, and a device speaks only when asked. When a device is plugged in, the host enumerates it, asking for descriptors that say what the device is, and loads a driver for its class: HID (keyboards, mice, game controllers), CDC-ACM (a virtual serial port), mass storage, audio, MIDI and others, so that common devices need no custom driver at all. USB 2.0 uses one differential pair, D+ and D−, at low speed (1.5 Mbit/s), full speed (12 Mbit/s) or high speed (480 Mbit/s); later generations add more pairs, up to 80 Gbit/s with USB4 version 2.0, and USB-C connectors negotiate how much power to supply. Many microcontrollers include a full-speed device controller, and open-source stacks such as TinyUSB make a board appear as a keyboard or a serial port with a few hundred lines of configuration.

Ethernet connects a device to a network. A microcontroller's MAC (media access controller) builds frames; an external PHY chip turns them into signals on the cable, connected to the MAC through an interface such as RMII; and small transformers (the "magnetics") isolate the cable from the board. Above sit IP, TCP and UDP, usually from an open-source stack such as lwIP or the ones built into Zephyr. Two newer variants matter for embedded systems: single-pair Ethernet from IEEE 802.3cg (2019), whose 10BASE-T1L version reaches about a kilometre in process plants and whose 10BASE-T1S version lets many nodes share one pair, like CAN; and automotive Ethernet, which links a car's cameras and computers at 100 Mbit/s to multiple Gbit/s.

BusWires (plus ground)Typical speedReachTopologyTypical use
UART2 (TX, RX)9.6 kbit/s – 3 Mbit/sa board (RS-485: ~1 km)point to pointconsoles, GPS and modem modules
I²C2 (SDA, SCL)100 kbit/s – 1 Mbit/sa boardaddressed bussensors, EEPROMs, power chips
SPI3 + one chip select per device1 – 100 MHza boardone controller, a select per deviceflash, displays, fast ADCs, radios
CAN / CAN FD2 (differential)125 kbit/s – 8 Mbit/stens to hundreds of metresmulti-controller bus with prioritiesvehicles, machines, robots
USB 2.02 (differential) + power12 – 480 Mbit/s5 mhost-centred treeconnecting to a computer
Ethernet4 (two pairs) or 2 (single pair)10 Mbit/s – 1 Gbit/s100 m (T1L ~1 km)switched networknetworked and industrial devices

Choosing usually comes down to four questions: how far, how fast, how many devices, and what the chips you want already speak. A sensor on the same board: I²C, or SPI if it is fast. A module with its own processor: UART. Several boards in a robot or a vehicle: CAN. A PC: USB. A building or a factory: Ethernet or RS-485.

ComputationC

A UART receiver in hardware

Inside the microcontroller, a UART is a small digital circuit, and writing one is a classic exercise in the state machines of Sequential logic and state machines. This receiver counts clock cycles rather than taking 16 samples per bit: it waits half a bit time after the falling edge to reach the middle of the start bit, then one full bit time for each later bit. The first two flip-flops are a synchroniser: the line comes from outside the chip's clock domain, and as Timing and clocking explained, sampling an asynchronous signal can leave a flip-flop metastable, so it passes through two before any logic sees it. The testbench sends five bytes bit by bit, then a frame with a broken stop bit, then a good frame to check that the receiver recovers; it calls $fatal if anything is wrong.

verilog
// uart_rx: an 8N1 UART receiver that samples each bit in its middle by counting clock cycles.
module uart_rx #(parameter CLKS_PER_BIT = 16) (
    input  wire       clk,
    input  wire       rst,
    input  wire       rx,            // the serial line: idle high
    output reg  [7:0] data,
    output reg        valid,         // one-cycle pulse: data holds a new byte
    output reg        frame_error    // one-cycle pulse: the stop bit was 0
);
    // Two flip-flops bring the asynchronous line safely into this clock domain.
    reg rx_meta = 1'b1, rx_sync = 1'b1;
    always @(posedge clk) begin
        rx_meta <= rx;
        rx_sync <= rx_meta;
    end

    localparam IDLE = 3'd0, START = 3'd1, DATA = 3'd2, STOP = 3'd3, WAIT_HIGH = 3'd4;
    reg [2:0]  state;
    reg [15:0] count;                // clock cycles counted within the current bit
    reg [2:0]  index;                // which data bit comes next
    reg [7:0]  shift;

    always @(posedge clk) begin
        valid <= 1'b0;
        frame_error <= 1'b0;
        if (rst) begin
            state <= IDLE;
            count <= 0;
            index <= 0;
        end else begin
            case (state)
                IDLE:
                    if (!rx_sync) begin                         // falling edge: a start bit begins
                        state <= START;
                        count <= 0;
                    end
                START:
                    if (count == CLKS_PER_BIT / 2 - 1) begin    // the middle of the start bit
                        count <= 0;
                        index <= 0;
                        state <= rx_sync ? IDLE : DATA;         // still high? it was a glitch
                    end else
                        count <= count + 1;
                DATA:
                    if (count == CLKS_PER_BIT - 1) begin        // the middle of the next data bit
                        count <= 0;
                        shift <= {rx_sync, shift[7:1]};         // least significant bit arrives first
                        index <= index + 1;
                        if (index == 3'd7)
                            state <= STOP;
                    end else
                        count <= count + 1;
                STOP:
                    if (count == CLKS_PER_BIT - 1) begin        // the middle of the stop bit
                        count <= 0;
                        if (rx_sync) begin
                            data  <= shift;
                            valid <= 1'b1;
                            state <= IDLE;
                        end else begin
                            frame_error <= 1'b1;
                            state <= WAIT_HIGH;                 // wait for the line to idle again
                        end
                    end else
                        count <= count + 1;
                WAIT_HIGH:
                    if (rx_sync)
                        state <= IDLE;
                default:
                    state <= IDLE;
            endcase
        end
    end
endmodule

// A self-checking testbench: send bytes bit by bit and check what the receiver reports.
module tb;
    localparam CPB = 16;
    reg clk = 1'b0, rst = 1'b1, rx = 1'b1;
    wire [7:0] data;
    wire valid, frame_error;
    uart_rx #(.CLKS_PER_BIT(CPB)) dut (.clk(clk), .rst(rst), .rx(rx), .data(data),
                                       .valid(valid), .frame_error(frame_error));
    always #5 clk = ~clk;

    integer received = 0, errors = 0;
    reg [7:0] last = 8'h00;
    always @(posedge clk) begin
        if (valid) begin
            received = received + 1;
            last = data;
        end
        if (frame_error)
            errors = errors + 1;
    end

    task send(input [7:0] b, input stop_bit);           // drive one frame onto the line
        integer i;
        begin
            rx = 1'b0;                                   // start bit
            repeat (CPB) @(negedge clk);
            for (i = 0; i < 8; i = i + 1) begin
                rx = b[i];                               // data bits, least significant first
                repeat (CPB) @(negedge clk);
            end
            rx = stop_bit;                               // stop bit (1 in a valid frame)
            repeat (CPB) @(negedge clk);
            rx = 1'b1;                                   // idle
            repeat (2 * CPB) @(negedge clk);
        end
    endtask

    reg [7:0] bytes [0:4];
    integer k;
    initial begin
        bytes[0] = 8'h4B; bytes[1] = 8'h55; bytes[2] = 8'hA5; bytes[3] = 8'h00; bytes[4] = 8'hFF;
        repeat (4) @(negedge clk);
        rst = 1'b0;
        repeat (4) @(negedge clk);
        for (k = 0; k < 5; k = k + 1) begin
            send(bytes[k], 1'b1);
            if (received != k + 1 || last !== bytes[k])
                $fatal(1, "frame %0d: expected 0x%h, received 0x%h", k, bytes[k], last);
            $display("frame %0d: received 0x%h", k, last);
        end
        send(8'h3C, 1'b0);                               // a broken frame: its stop bit is 0
        if (errors != 1 || received != 5)
            $fatal(1, "the framing error was not detected");
        $display("frame 5: framing error detected, byte discarded");
        send(8'h7E, 1'b1);                               // and the receiver recovers
        if (received != 6 || last !== 8'h7E)
            $fatal(1, "the receiver did not recover after the framing error");
        $display("frame 6: received 0x%h after recovering", last);
        $display("PASS");
        $finish;
    end
endmodule

Under Icarus Verilog it prints the five bytes 0x4b, 0x55, 0xa5, 0x00 and 0xff, reports the framing error, receives 0x7e after recovering, and ends with PASS. Notice the line shift <= {rx_sync, shift[7:1]}: each new bit enters at the top and moves down, so the first bit received, the least significant, ends in bit 0. Swap it for a left shift and the testbench fails at once, receiving 0xd2 (the bits of 0x4b reversed) — exactly the kind of bug a self-checking testbench exists to catch. A real UART adds a transmitter, FIFOs, parity, a programmable baud-rate generator and the registers of Microcontrollers, but its heart is this state machine.

ExplanationH

Debugging with a logic analyser

When a bus does not work, the program's view ("the sensor returns 0xFF") is rarely enough. A logic analyser samples several digital lines at once, at tens to hundreds of millions of samples per second, and displays them as timing diagrams; protocol decoders then annotate the waveforms with START, address, ACK and data. Open-source software such as sigrok and PulseView works with inexpensive USB analysers, and most oscilloscopes now include decoders too. Sample at least four times faster than the fastest signal, preferably ten, and connect the analyser's ground to the board's.

What you will find, again and again:

  • No common ground between two boards, so the receiver sees noise instead of bits.
  • TX connected to TX: one device's transmit must go to the other's receive.
  • Missing pull-ups on I²C (lines that never rise, or rise in slow curves), or two sets of pull-ups in parallel that are too strong.
  • The wrong address, shifted by one bit, or the wrong SPI mode, giving data shifted by one bit.
  • A baud-rate mismatch: bytes that look like nonsense but arrive at the right times. Measure the narrowest pulse; it is one bit time.
  • Mismatched logic levels: a 5 V device driving a 3.3 V input that is not 5 V tolerant, which can damage it, or a 3.3 V output too low for a 5 V input to read as high.
  • A stuck I²C bus: a target reset in the middle of a byte keeps holding SDA low. The fix is to clock SCL up to nine times until it lets go, then send a STOP.

An oscilloscope complements the analyser: it shows the analogue truth (ringing, slow edges, a line that only gets to 2.1 V) that a logic analyser reduces to 0s and 1s. Whatever the tool, the method is the one in Lumenary CS's debugging lesson: form a hypothesis, measure, change one thing at a time.

Common misconceptionsH

Common misconceptions

Misconception

"A baud rate a few per cent off is close enough." The error accumulates over a whole frame and the budget is shared with the other end. Two devices each 2.5% off in opposite directions sit at the cliff edge; keep each end within about 2%.

Misconception

"I²C devices drive the lines high and low." They only pull low. The high level comes entirely from the pull-up resistors, so without them nothing works, and with the wrong ones edges are too slow or lows too high.

Misconception

"On CAN, a collision destroys both messages, as on old Ethernet." CAN's bitwise arbitration is non-destructive: the highest-priority frame continues untouched, and the others become receivers and retry.

Misconception

"SPI's chip select is optional with only one device." Many devices use the falling edge of chip select to reset their bit counter and frame each command; tying it permanently low lets a single glitch on the clock misalign every byte that follows.

Exercises

Exercises

1. Buses and interfaces

Warm-upHuman

A UART runs at 115,200 baud with the 8N1 format and sends bytes back to back with no gaps. How many bytes of data does it carry per second?

2. Buses and interfaces

Warm-upHuman

A display controller has the 7-bit I²C address 0x3C. What is the first byte the controller sends after START to write to it? Give it in hexadecimal, like 0xAB.

3. Buses and interfaces

CoreHuman

A flash memory's datasheet says: the clock idles high, and data is sampled on the rising edge. Which SPI mode is that?

Choose one

4. Buses and interfaces

CoreComputational

Write uart_frame(byte, parity=None) returning the list of bits on the wire for one frame: a start bit 0, the 8 data bits least significant first, then, if parity is "even" or "odd", a parity bit chosen so that the data bits plus the parity bit contain an even (or odd) number of 1s, and finally one stop bit 1. (The starter has a bug and ignores parity.)

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

5. Buses and interfaces

CoreComputational

Write arbitration_losses(ids, width=11). The distinct identifiers in ids start transmitting at the same moment on a CAN bus, most significant bit first. Return a dictionary mapping each identifier to the position (0 for the first bit sent) at which it lost arbitration, or None for the winner. Remember: the bus carries 0 if any still-transmitting node sends 0, and a node that sends 1 but reads 0 stops.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

6. Buses and interfaces

CoreHuman

An I²C bus in Fast mode (maximum rise time 300 ns, measured from 30% to 70% of the supply) has 150 pF of capacitance. What is the largest pull-up resistance that meets the rise-time limit? Give whole ohms, rounded down.

7. Buses and interfaces

CoreHuman

A GPS module's serial output appears as nonsense characters, arriving at regular intervals. A logic analyser shows that the narrowest pulse on the line lasts about 104 µs; the microcontroller's UART is set to 115,200 baud. What is the most likely problem?

Choose one

8. Buses and interfaces

Warm-upHuman

A robot arm has six joint controllers, each on its own small board, spread along about 2 m of cable from the main computer. Emergency-stop messages must always get through before routine status reports. Which bus fits best?

Choose one

Further reading and resources