Textbooks/Electrical and Embedded Systems/Chapter 9Lite (plain text) version
9Registers, interrupts and integration
Version 1 · Technically checked (automated checks only) · 3 source lessons · 7 practice items
Introduction
Underneath every library call, software controls hardware by writing bits into registers. Bit masks set, clear and test single bits without disturbing their neighbours. Interrupts let hardware call the processor when something happens, saving the energy and latency of constant polling, but they bring shared-data hazards. Finally, the build chain turns source into a running image, and hardware-in-the-loop tests check the join between code and circuit.
Explanation
This chapter is built from 3 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
9.1 Registers and bit masks: where software touches silicon
One line of C turns on a motor driver. Which single bit, at which address, did it change, and what else could it break?
Memory-mapped I/O
Microcontrollers give each peripheral (GPIO, timers, ADC, UART) a block of addresses. Writing to an address doesn't store data in RAM; it sets flip-flops whose outputs drive the hardware: a pin's direction, a timer's prescaler, an interrupt enable. Reading may return live hardware state, such as whether a conversion has finished.
The four mask operations
Set bit n: reg |= (1 << n). Clear: reg &= ~(1 << n). Toggle: reg ^= (1 << n). Test: (reg & (1 << n)) != 0. Multi-bit fields (a 3-bit prescaler at bits 4–6) are cleared with a field mask, then the new value is ORed in, shifted into place. Datasheets give each bit's meaning; the code should name them, not use magic numbers.
Read–modify–write hazards
reg |= mask is really three steps: read, OR, write. If an interrupt changes the same register between the read and the write, its change is lost. Fixes: disable interrupts briefly around the update, or use hardware 'set' and 'clear' registers that change only the bits you write as 1. Some status bits clear when read, so even reading has side effects.
Integration means checking both sides
A firmware unit test can't see a wrongly configured clock. Integration tests run real code on real (or accurately simulated) hardware and check observable behaviour: the pin toggles at the expected frequency, the ADC reads a known voltage correctly. Write down what each register should contain and check it in a debugger.
Common mix-ups
- Writing to a register is like writing to a variable.
✓ It changes hardware immediately and can have side effects; reading can too. - reg |= mask is a single, safe operation.
✓ It is read–modify–write and can lose updates made by interrupts in between.
Open the full lesson: Registers and bit masks: where software touches silicon →
9.2 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 →
9.3 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
Registers and bit masks: where software touches silicon: example 1
reg = 0x5A (0101_1010). Clear bit 3, then toggle bit 0. Result?
Solution
Clear bit 3: 0101_1010 & 1111_0111 = 0101_0010 (0x52). Toggle bit 0: 0101_0011 = 0x53.
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.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Studio
Code Lab
Write set_bit, clear_bit and test_bit functions with masks and test them on every bit of a byte.
Open Code Lab →Silicon Studio stage
Silicon Studio: Registers
Load and hold a value in a register, then explain what a write-enable signal protects.
Open Silicon Studio: Registers →
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.
- Which C expression clears bit 5 of reg and leaves every other bit unchanged?
- reg = reg & (1 << 5)
- reg &= ~(1 << 5)
- reg |= (1 << 5)
- reg ^= 0xFF
- reg = 0x3C. After reg |= 0x81, what is reg in decimal?
- Main code does PORT |= LED_BIT while an interrupt handler sets MOTOR_BIT in the same register. Occasionally the motor bit is lost. Why?
- The compiler is broken
- The interrupt ran between main's read and write, so main wrote back the old value
- Bits can't be shared
- The LED draws too much current
- A battery-powered door sensor must react within 10 ms to a door opening, which happens a few times a day. Which design?
- Poll every 1 ms forever
- Interrupt on the sensor pin, sleeping between events
- Poll every 10 seconds
- Neither can meet 10 ms
- 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
- 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
- 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
Sleeping until needed
Battery devices spend most of their time asleep and let an interrupt from a timer, a button or a radio wake them. Polling the same button in a loop would keep the processor awake and empty the battery.
Testing the join
Hardware-in-the-loop rigs feed real firmware with simulated sensor signals and check its outputs. They find the bugs that only appear when code meets real timing and real voltages.
Watch
Optional verified videos. Nothing loads from YouTube until you press play.
- Interrupt handling (Ben Eater)
- CPU Interrupts - Computerphile (Computerphile)
Chapter summary
- Registers are memory addresses wired to hardware; each bit or field controls something.
- Set with OR, clear with AND NOT, test with AND; a read-modify-write can race with an interrupt.
- Interrupts cut latency and energy compared with polling; keep handlers short and protect shared data.
- The build chain compiles, links and flashes; hardware-in-the-loop tests the code with its circuit.
Glossary
- Registers
- Registers are a small number of very fast storage locations inside the processor that hold the values it is working on right now.
- 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.
- 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.
- Bits and bytes
- A bit is a single binary digit, 0 or 1. A byte is 8 bits. n bits can represent 2^n different values.
- Hexadecimal
- Hexadecimal is base 16, using digits 0–9 and A–F. Each hex digit stands for exactly four bits, so two hex digits describe one byte.
Definitions from the Field Guide.
Project: A register-level driver
Write a tiny driver for an imaginary peripheral whose 8-bit control register has an enable bit, a two-bit mode field and an interrupt-enable bit. Provide functions to enable it, set the mode and acknowledge an interrupt, using masks only, and explain where a race could occur.
Deliverables
- A register map table
- The driver functions with tests on a simulated register
- A note on the race and how you would prevent it
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- Edward A. Lee and Sanjit A. Seshia (2017). Introduction to Embedded Systems: A Cyber-Physical Systems Approach, 2nd edition. MIT Press.
- Elecia White (2011). Making Embedded Systems: Design Patterns for Great Software. O'Reilly Media.
- Paul Horowitz and Winfield Hill (2015). The Art of Electronics, 3rd edition. Cambridge University Press.
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.