TactivergeLite

Lite / Textbooks / Computer Architecture / Chapter 5

5. Input, output and the hardware–software boundary

Version 1 · Technically checked (automated checks only) · 4 source lessons · Full interactive version

Introduction

A processor is only useful when it talks to the world. This chapter follows bytes across the boundary: serial frames on a UART wire, full-duplex transfers on SPI, the choice between polling a device and letting it interrupt you, and the tool chain that turns source code into an image at fixed addresses. Each choice trades latency, throughput, energy and the risk of subtle bugs where software meets hardware.

Figure 5.1. One byte on a UART wire (described in words)

A UART 8N1 frame for the byte 0x4B (0100 1011). The idle-high line drops for the start bit, then carries data bits 1 1 0 1 0 0 1 0, least significant first, then a stop bit of 1. With 10 bits per byte, 115200 baud moves 11520 bytes per second.

Explanation

Built from 4 School lessons. Each part is the lesson's own explanation.

5.1 UART: one wire, ten bits, one byte

There is no clock wire between your laptop and a GPS module, yet not a single bit gets lost. How does the receiver know when each bit starts?

Asynchronous means no shared clock

A UART line rests high (idle). To send a byte, the transmitter pulls it low for one bit time: the start bit. The receiver sees that falling edge, waits half a bit, then samples once per bit time. Both sides must agree on the baud rate in advance; each keeps its own clock, so they only have to stay in step for one short frame before the next start bit lines them up again.

The frame, bit by bit

After the start bit come 8 data bits, least significant bit first, then an optional parity bit, then a stop bit (high) that returns the line to idle. The common format 8N1 means 8 data bits, no parity, 1 stop bit: 10 bits on the wire per byte. 8E1 adds an even-parity bit (11 bits). The letter A is 0x41 = 01000001, so the data bits go out as 1 0 0 0 0 0 1 0.

Parity: a one-bit alarm

With even parity the transmitter picks the parity bit so the total number of 1s in data + parity is even. 0x41 has two 1s, so its even-parity bit is 0. If noise flips any single bit, the count becomes odd and the receiver flags the frame. Two flipped bits cancel out and slip through, so parity detects errors but cannot correct them; real protocols add checksums on top.

When the text turns to garbage

A baud-rate mismatch makes the receiver sample in the wrong places, so bytes decode as nonsense or framing errors (no high stop bit where one was expected). Other usual suspects: transmit wired to transmit instead of crossing TX→RX, no shared ground, or a 5 V device talking to a 3.3 V input. UART voltage levels are a separate choice from the frame format.

Derivation: From baud rate to bytes per second
  1. One bit lasts T = 1/baud seconds. At 9600 baud, T = 1/9600 s ≈ 104.2 µs.

  2. One 8N1 frame is 1 start + 8 data + 1 stop = 10 bits, so it lasts 10·T ≈ 1.042 ms.

  3. Back to back with no idle gaps, frames per second = 1/(10·T) = baud/10 = 960.

  4. Each frame carries one data byte, so the maximum data rate is 960 bytes/s. In general: bytes/s = baud ÷ (bits per frame).

Common mix-ups

Open the Lite lesson: UART: one wire, ten bits, one byte

5.2 SPI: swapping bytes at full speed

A tiny colour screen needs over a megabyte every second. Which bus can keep up, and why does reading from it mean sending something too?

Four wires, one conversation at a time

SCLK is the clock from the controller. MOSI (controller out, peripheral in) and MISO (controller in, peripheral out) carry data. CS (chip select, active low) picks which peripheral is listening: each peripheral normally gets its own CS line, so four devices need four CS pins. There are no addresses: pulling a CS low is the address.

Two shift registers in a ring

Inside, the controller and the peripheral each hold an 8-bit shift register, joined in a ring by MOSI and MISO. On each clock, each side shifts its most significant bit out and takes the other side's bit in. After 8 clocks the bytes have swapped. That is why SPI is full duplex, and why reading always means writing something.

Modes: when to sample

Devices differ on the clock's idle level (CPOL) and on which edge data is sampled (CPHA), giving modes 0–3. Mode 0 (clock idles low, sample on the rising edge) is the most common. Controller and peripheral must use the same mode, or every bit is read half a clock off. The datasheet always states it; check it before blaming the wiring.

Choosing a bus

UART: 2 wires, point to point, no clock; 115200 baud 8N1 is about 11.5 kB/s. I²C: 2 wires shared by many addressed devices, acknowledged; 400 kHz gives at most about 44 kB/s before addressing overhead. SPI: 3 wires plus a CS per device, no addressing or acknowledge; 10 MHz moves 1.25 MB/s. Choose by data rate, number of devices and spare pins.

Derivation: SPI burst time and data rate
  1. SPI moves one bit per clock edge pair and has no start, stop, parity or acknowledge bits.

  2. So N bytes need exactly 8N clocks (with CS held low and no gaps).

  3. One clock lasts 1/f, so the burst takes t = 8N/f. With f in MHz, t comes out in microseconds.

  4. The maximum data rate is N/t = f/8 bytes per second: 8 MHz → 1 000 000 bytes/s.

Common mix-ups

Open the Lite lesson: SPI: swapping bytes at full speed

5.3 Polling or interrupts? Latency, energy and shared data

Checking a button a million times a second never misses a press. Why is it usually the wrong design?

Polling

The main loop repeatedly reads a status bit. Simple, deterministic and easy to debug. Worst-case latency is the loop period (plus the work done each loop). Energy cost: the CPU wakes every period whether or not anything happened. Good when events are frequent and regular, or when you need a fixed sampling rate anyway (a control loop at 1 kHz).

Interrupts

Hardware detects the event and forces the CPU to run a short handler (an ISR). Latency is microseconds (entry cycles plus any time interrupts are disabled). Between events the CPU can sleep. The price is complexity: handlers interrupt main code at unpredictable moments, which creates races on shared data.

Protecting shared data

Rules of thumb: keep ISRs short (set a flag, copy a value, leave); declare shared variables volatile; read multi-byte values with interrupts briefly disabled or with a consistency check; use a ring buffer with one writer and one reader. Never call slow or blocking functions inside an ISR.

Hybrid designs

Many systems use an interrupt to wake from sleep, then poll briefly while active, or a timer interrupt that runs a fixed-rate control loop. The choice is a budget trade: latency target, energy per event, CPU time left for other work, and how much complexity you can verify.

Common mix-ups

Open the Lite lesson: Polling or interrupts? Latency, energy and shared data

5.4 From source code to running hardware, and testing the join

The code compiled, the tests passed, and the robot still twitched. Where in the chain did it go wrong?

The chain

Compiler: C or Rust → assembly for the target. Assembler: assembly → machine-code object files. Linker: combines objects and libraries, places code and data at real addresses using a linker script (flash here, RAM there). Image: a binary or hex file. Flashing: a programmer writes it into the chip's flash. Boot: the reset vector jumps to start-up code that sets up the stack and memory, then calls main.

Optimisation levels are trade-offs

-O0: slow, large, every variable visible to the debugger. -O2: fast, usually smaller. -Os: smallest. -O3: aggressive inlining, can be larger. On a microcontroller with 64 KB of flash, size may decide. Benchmark the configuration you will ship: timings measured on a debug build can differ greatly.

What changes between builds

Library versions, compiler versions, flags, linker scripts and configuration headers can all change behaviour. Reproducible builds pin them all and record a version or commit hash in the firmware itself, so a measurement can always be traced to the exact binary that produced it.

Integration testing

Unit tests check functions in isolation on a computer. Hardware-in-the-loop tests run the real firmware on the real board while a test rig feeds sensor signals and measures outputs and timing. Test the joins: clock configuration, interrupt latency under load, behaviour at power-up, and what happens when a sensor is unplugged.

Common mix-ups

Open the Lite lesson: From source code to running hardware, and testing the join

Worked examples

UART: one wire, ten bits, one byte: example 1

A logic analyser shows, after the start bit, the data bits 0 0 1 0 1 1 0 0 (first to last). What byte is it?

Solution

The first bit is bit 0. Reverse to read MSB first: 00110100 = 32 + 16 + 4 = 52 = 0x34, the ASCII character '4'.

UART: one wire, ten bits, one byte: example 2

How long does one 8E1 frame take at 115200 baud?

Solution

11 bits × (1/115200 s) = 11 × 8.68 µs ≈ 95.5 µs.

SPI: swapping bytes at full speed: example 1

How long does it take to send 64 bytes to an SD card at 4 MHz?

Solution

64 × 8 = 512 clocks. 512 / 4 MHz = 128 µs.

SPI: swapping bytes at full speed: example 2

A board has 3 SPI peripherals and 1 I²C sensor. How many microcontroller pins do the buses use?

Solution

SPI: SCLK, MOSI, MISO shared (3) plus one CS each (3) = 6. I²C: SDA and SCL = 2. Total 8 pins.

Polling or interrupts? Latency, energy and shared data: example 1

A polling loop runs every 2 ms and takes 0.3 ms per pass. What is the worst-case delay before an event is noticed?

Solution

The event may occur just after a check: up to 2 ms until the next check starts, plus up to 0.3 ms to reach the check in the loop. About 2.3 ms worst case.

From source code to running hardware, and testing the join: example 1

A firmware image is 58 KB at -O2 and 49 KB at -Os on a chip with 64 KB flash. The -Os build runs a control loop 12% slower. The loop has 30% timing margin. Which do you ship, and what do you record?

Solution

-Os leaves room for growth and the 12% slowdown fits within the 30% margin. Record the compiler version, flags and commit hash in the image, and re-run the timing integration test on the -Os build.

Interactive figures, in words

Figure 5.2 from UART: one wire, ten bits, one byte

Pick the letter A (65) and look at the waveform: find the start bit and read the data bits from left to right. Then flip one data bit with parity off, then with even parity on. Which setting notices the damage?

The UART diagram draws one frame as a square wave. For the letter A (65 = 0x41) with even parity the line reads, in time order: start 0, data 1 0 0 0 0 0 1 0, parity 0, stop 1. Choosing a byte updates the bits; choosing a data bit to flip inverts it and the readout reports the wrongly decoded byte and whether the parity check fails (it fails for any single flip when parity is on; with no parity the error is not noticed).

Figure 5.3 from SPI: swapping bytes at full speed

Set the controller to 0x9F and the peripheral to 0x3C. Clock once at a time and watch both registers. After how many clocks have the two bytes completely swapped places?

The SPI diagram shows two 8-bit registers. Starting with the controller holding 0x9F (10011111) and the peripheral holding 0x3C (00111100), each press of Clock once shifts both registers left by one: the controller's top bit goes into the peripheral's bottom bit over MOSI and the peripheral's top bit goes into the controller's bottom bit over MISO. After 8 clocks the controller holds 0x3C and the peripheral holds 0x9F: the bytes have swapped.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. What level does a UART transmit line sit at when nothing is being sent?
    Answer it in “UART: one wire, ten bits, one byte”
  2. Your microcontroller prints readable text in one terminal but random symbols in another. What is the most likely difference?
    Answer it in “UART: one wire, ten bits, one byte”
  3. Why does a controller send 0x00 on MOSI while reading a byte from an SPI sensor?
    Answer it in “SPI: swapping bytes at full speed”
  4. Which bus suits a colour display that needs about 1 MB/s, on a board with pins to spare?
    Answer it in “SPI: swapping bytes at full speed”
  5. Which is good practice inside an interrupt handler?
    Answer it in “Polling or interrupts? Latency, energy and shared data”
  6. A poll check takes 5 µs and runs every 1 ms. What percentage of CPU time does polling use?
    Answer it in “Polling or interrupts? Latency, energy and shared data”
  7. Which tool decides the actual memory addresses where code and data end up?
    Answer it in “From source code to running hardware, and testing the join”
  8. What can a hardware-in-the-loop test catch that a unit test on a laptop cannot?
    Answer it in “From source code to running hardware, and testing the join”

Engineering applications

Debug consoles

Almost every embedded board prints its boot log over a UART. When the text arrives as garbage, a mismatched baud rate on one end is the first suspect.

Displays and storage

Colour displays and memory cards use SPI because it clocks data both ways at many megahertz with no addressing overhead, at the cost of one chip-select pin per device.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

Interrupts
An interrupt is a hardware signal that makes the processor pause the main program, run a short interrupt service routine (ISR), and then resume where it left off. Field Guide
Bus and link bandwidth
Bandwidth is how much data a bus or link can move per second. For a UART each byte usually costs 10 bit times: one start bit, eight data bits and one stop bit. Field Guide
Memory-mapped I/O
With memory-mapped I/O, peripheral control and data registers appear at fixed memory addresses, so the processor talks to hardware with ordinary load and store instructions. Field Guide
Endianness
Endianness is the order in which the bytes of a multi-byte value are stored in memory or sent over a link: little-endian puts the least significant byte first, big-endian the most significant. Field Guide

Project: A bus and interrupt plan

For a small robot with an IMU, a range sensor, a display and a debug console, choose a bus for each device, compute the data rate each needs, and decide which raise interrupts. Show that the total bus load leaves headroom.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

← 4. Caches and the memory hierarchy6. Parallelism and acceleration →