Lite / Textbooks / Electrical and Embedded Systems / Chapter 9
9. Registers, interrupts and integration
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.
Figure 9.1. Touch one bit, leave the rest (described in words)
Three rows of eight bit cells. The register holds 10100000 (160). OR with 1 << 3 sets bit 3, giving 10101000 (168). AND with NOT (1 << 7) then clears bit 7, giving 00101000 (40). Bit 7 is on the left.
Explanation
Built from 3 School lessons. Each part is the lesson's own explanation.
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 Lite 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 Lite 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 Lite 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
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Code Lab (Studio)
Write set_bit, clear_bit and test_bit functions with masks and test them on every bit of a byte.
Open on the full site - Silicon Studio: Registers (Silicon Studio stage)
Load and hold a value in a register, then explain what a write-enable signal protects.
Open on the full site
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.
- Which C expression clears bit 5 of reg and leaves every other bit unchanged?
Answer it in “Registers and bit masks: where software touches silicon” - reg = 0x3C. After reg |= 0x81, what is reg in decimal?
Answer it in “Registers and bit masks: where software touches silicon” - Main code does PORT |= LED_BIT while an interrupt handler sets MOTOR_BIT in the same register. Occasionally the motor bit is lost. Why?
Answer it in “Registers and bit masks: where software touches silicon” - A battery-powered door sensor must react within 10 ms to a door opening, which happens a few times a day. Which design?
Answer it in “Polling or interrupts? Latency, energy and shared data” - Which is good practice inside an interrupt handler?
Answer it in “Polling or interrupts? Latency, energy and shared data” - 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” - 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
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)
Streaming video uses a lot of data. Everything you need is in the text.
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. Field Guide
- 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
- 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
- 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. Field Guide
- 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. 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
Write it up on paper or in your own notes. Lite never stores what you write.
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.