UNIT 09 · INTERACTING WITH HARDWARE
Interrupts and Events
React to the world the moment it changes.
An interrupt lets hardware stop the program and run a handler the moment something happens: a byte arrives, a timer expires, a pin changes. It is the most powerful tool in firmware and the source of its most elusive bugs: flags cleared the wrong way, a counter that loses one increment in a million, a fault input that waits behind a slow display update, a handler that runs twice for one event.
The unit in six ideas
- 1Polling costs CPU time on every check and adds up to one period of latency; interrupts cost nothing while idle and a fixed amount per event.
- 2An interrupt is inactive, pending, active, or active and pending; software can set and clear pending bits.
- 3Lower priority numbers are more urgent; more urgent interrupts preempt; equal ones never preempt, and among them the lowest IRQ number is taken first.
- 4A handler must clear its source; otherwise the level-held request re-enters the handler forever.
- 5Shared flags must be volatile; volatile does not make multi-instruction operations atomic.
- 6A handler blocks all interrupts of equal and lower priority for its whole duration; keep it to capture, clear and hand on.
Lessons
Polling, Interrupts, and Events
Which one should it use, and why does an interrupt that is “enabled” sometimes never arrive?
Interrupt Requests and Handler Execution
And when one interrupt line serves eight GPIO pins, whose job is it to find out which pin it was?
Latency, Priorities, and Nesting
What decides how long an interrupt waits, and how do you guarantee the important one never waits long?
Acknowledging and Clearing Interrupt Flags
How hard can writing one bit be?
Sharing Data with Interrupt Handlers
What does it take to share even a single number with an interrupt handler?
Deferring Work and Keeping Handlers Short
How can a handler that works correctly break everything around it?