Subsection 8.1.4 The Idea of an Interrupt
A timer counting on its own solves half the problem. The other half is delivery: how does the CPU learn that the period has elapsed, without sitting in a loop asking? Consider two ways of handling a question you have sent your instructor by email. You could stare at your inbox until the reply arrives. That is a blocking wait. You could check your inbox after every paragraph of work. That is polling, and both of these cost you attention. Or you could simply keep working until your mail program pings you. The ping is the interrupt, and the whole point is what it lets you do the rest of the time.
Here is the idea. An interrupt is a signal from a piece of hardware (a timer, a button’s pin, the UART) that makes the CPU pause what it is doing, run a function you wrote, and then resume exactly where it left off, as if nothing had happened. The function has a name of its own: an Interrupt Service Routine, or ISR. The interruption can land between any two instructions, even in the middle of
delay_ms(), and that is precisely what makes it powerful: your main program no longer has to watch for anything. The hardware watches; your ISR responds; main() works.
One caution about the acronym. Since Day 5 you have used “ISR” for a peripheral’s interrupt and status register:
USART2->ISR, ADC1->ISR. The Interrupt Service Routine is a different thing using the same acronym: not a register but a function you write. In class you will also hear “handler” for the function, which is unambiguous.
Two habits follow from the idea, and class makes them concrete. Because an ISR borrows the CPU from your main program, it must be quick: do the minimum and get out. And because the hardware, not your code, is the caller, hooking an ISR up means telling the hardware about it, which is most of what Day 8’s class hour builds. How the machinery works (what the CPU saves, how it finds your function, and why shared variables need a keyword called
volatile) is the pre-class video; the written version lives in Subsection 8.3.4 and Subsection 8.3.6 for revisiting.
volatile.