Skip to main content

Subsection 9.1.1 The Press That Nobody Saw

In the Lab 2 button-race game, two players each had a button, and the game had to detect the first press after a countdown. The countdown was made of delays, and while the program was stuck in such a delay, it was not looking at the buttons. A player who pressed and released during a delay pressed a button that, as far as the program was concerned, was never pressed at all.
This is not a bug in the game and it cannot be fixed using the tools we had at that point. A polling loop reads the pin’s current level, so it can only see a press that is still happening at the moment it looks. One work-around was to make the delay shorter, thereby narrowing the window, but the problem never vanishes entirely, and you pay for the narrowing with a loop that does nothing but ask. We made the same argument about timekeeping and answered it by moving the counting into hardware. The answer here is the same in shape: let the hardware watch the pin, and have it tell the CPU when something happened.
What we want is a program that notices the press whenever it occurs, including in the middle of a delay, in the middle of a printf(), or in the middle of a single line of C. That is exactly what an interrupt is for.