Skip to content
Tactiverge

Textbooks/Computer Architecture/Chapter 5Lite (plain text) version

5Input, output and the hardware–software boundary

Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items

Text
All chapters and search
  1. 1. Instruction-set design
  2. 2. The performance equation
  3. 3. Pipelining and hazards
  4. 4. Caches and the memory hierarchy
  5. 5. Input, output and the hardware–software boundary
  6. 6. Parallelism and acceleration
  7. 7. Energy and reduced precision
  8. 8. Measuring performance honestly

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.

byte 0x4B = 0100 1011, sent LSB firststart0d01d11d20d31d40d50d61d70stop11010 bits carry 8 data bits; at 115200 baud115200 ÷ 10 = 11520 bytes per second.
Figure 5.1. One byte on a UART wire. 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

This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.

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

  • Baud rate ÷ 8 gives bytes per second.
    ✓ Divide by the frame length: 10 bits for 8N1, so 9600 baud carries 960 bytes/s, not 1200.
  • Bytes are sent most significant bit first, just as we write them.
    ✓ UART sends the least significant bit first; I²C and most SPI devices send the most significant bit first.
  • Parity can fix a corrupted byte.
    ✓ Parity only detects an odd number of flipped bits. It cannot tell which bit flipped, and two flips go unnoticed.

Open the full 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

  • You can read from SPI without writing.
    ✓ Every clock shifts one bit each way; reading N bytes means sending N bytes (often dummies).
  • SPI devices have addresses like I²C devices.
    ✓ SPI has none: the chip-select line picks the device, at the cost of one pin each.
  • If the wiring is right, any SPI mode will work.
    ✓ Controller and peripheral must agree on CPOL and CPHA; the wrong mode shifts every bit by half a clock.

Open the full 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

  • Interrupts are always better than polling.
    ✓ Polling is simpler and deterministic; it is often right for fixed-rate control loops or frequent events.
  • A variable shared with an ISR is safe if it's only one line of code.
    ✓ One line can compile to several instructions; protect shared data explicitly.

Open the full 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

  • If it compiles and the unit tests pass, the firmware works.
    ✓ Configuration, timing and hardware interaction need integration tests on the real target.
  • Compiler optimisation changes what the program does.
    ✓ It preserves defined behaviour; failures after optimising usually expose bugs such as missing volatile or undefined behaviour.

Open the full 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

Figure 5.2 from UART: one wire, ten bits, one bytePick 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?
Can't use the interactive? Read a description instead

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).

Interactive figure (online). Description: 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 speedSet 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?
Can't use the interactive? Read a description instead

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.

Interactive figure (online). Description: 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.

Laboratory

Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.

  • Simulation OS experiment

    Simulation OS: Battery sensor node

    Compare a node that wakes to poll every second with one that sleeps until an event, and read the battery life for each.

    Open Simulation OS: Battery sensor node →
  • Studio

    Robotics Workbench

    Decide which sensor in a robot design should interrupt the processor and which can be polled, and write down the latency each needs.

    Open Robotics Workbench →

Guided practice

Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.

Practice 1

What level does a UART transmit line sit at when nothing is being sent?

Practice 2

Your microcontroller prints readable text in one terminal but random symbols in another. What is the most likely difference?

Practice 3

Why does a controller send 0x00 on MOSI while reading a byte from an SPI sensor?

Practice 4

Which bus suits a colour display that needs about 1 MB/s, on a board with pins to spare?

Practice 5

Which is good practice inside an interrupt handler?

Practice 6

A poll check takes 5 µs and runs every 1 ms. What percentage of CPU time does polling use?

%

Practice 7

Which tool decides the actual memory addresses where code and data end up?

Practice 8

What can a hardware-in-the-loop test catch that a unit test on a laptop cannot?

  1. What level does a UART transmit line sit at when nothing is being sent?
    • Low (0)
    • High (1)
    • It toggles at the baud rate
  2. Your microcontroller prints readable text in one terminal but random symbols in another. What is the most likely difference?
    • The second terminal uses a different baud rate
    • The second terminal has a faster computer
    • The cable is too short
  3. Why does a controller send 0x00 on MOSI while reading a byte from an SPI sensor?
    • To reset the sensor
    • Because clocking 8 bits in always clocks 8 bits out
    • To tell the sensor its address
  4. Which bus suits a colour display that needs about 1 MB/s, on a board with pins to spare?
    • UART at 115200 baud
    • I²C at 400 kHz
    • SPI at 10 MHz
  5. Which is good practice inside an interrupt handler?
    • Print a long debug message over a slow serial port
    • Set a flag or copy a value into a buffer, then return
    • Wait for another sensor to be ready
    • Run the whole control algorithm, however long it takes
  6. A poll check takes 5 µs and runs every 1 ms. What percentage of CPU time does polling use? (%)
  7. Which tool decides the actual memory addresses where code and data end up?
    • The compiler
    • The linker, using a linker script
    • The debugger
    • The flash programmer
  8. What can a hardware-in-the-loop test catch that a unit test on a laptop cannot?
    • Spelling errors in comments
    • A wrongly configured clock that makes the control loop run at the wrong rate
    • A sorting bug in pure code
    • Nothing

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 verified videos. Nothing loads from YouTube until you press play.

A short, clear explanation of UART framing and baud rate.

6 min 11 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

Probes a real SPI bus with a logic analyser so you can see clock, data and chip-select line by line.

32 min 59 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

Explains interrupts from the CPU's side: how hardware gets the processor's attention.

16 min 46 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

Adds interrupt handling to a 6502 computer and shows why it beats checking a button in a loop.

25 min 37 s · captions on YouTube · source

Nothing loads from YouTube until you press play.

  • Understanding UART (Rohde & Schwarz)
  • SPI: The serial peripheral interface (Ben Eater)
  • CPU Interrupts - Computerphile (Computerphile)
  • Interrupt handling (Ben Eater)

Chapter summary

  • UART frames each byte with start and stop bits: 8N1 sends 10 bits per byte.
  • SPI shifts a byte out and a byte in on every transfer; reading means sending dummy bytes.
  • Polling costs processor time and energy; interrupts cost complexity and shared-data hazards.
  • The linker fixes addresses; hardware-in-the-loop tests catch what pure simulation cannot.

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.
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.
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.
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.

Definitions from the 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

  • A device table with bus, data rate and interrupt choice
  • Bus load calculations
  • One risk at the hardware–software boundary and its mitigation

Keep your work in your Engineering Journal; it stays private unless you choose to share it.

References

  • Randal E. Bryant and David R. O'Hallaron (2016). Computer Systems: A Programmer's Perspective, 3rd edition. Pearson.
  • David A. Patterson and John L. Hennessy (2017). Computer Organization and Design RISC-V Edition: The Hardware Software Interface. Morgan Kaufmann.

Publication record

Version
1
Status
Technically checked (automated checks only)
Technical review
Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
Written by
Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
Licence
All rights reserved by the founders unless a licence is approved.
Corrections
None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.