Subsection 8.3.6 Writing an ISR: The Rules, and volatile
An Interrupt Service Routine looks like an ordinary C function, but three rules set it apart, each a consequence of the mechanism in Subsection 8.3.4. Rule 1 (the fixed, exact name, and no arguments or return value) is covered there. The other two:
Rule 2: get in and out fast, and never block. While your ISR runs, the interrupted program is stopped, and other interrupts may be kept waiting. An ISR that loops, waits on a flag, or calls something slow (
printf(), delay_ms()) holds up everything below it. The standard pattern: do the minimum the event requires (clear the flag, record a value, set a marker) and let main() do the real work at its leisure.
Rule 3: shared variables must be
volatile. The minimal-work pattern of Rule 2 usually means the ISR sets a global flag variable that main() checks:
volatile int timerElapsed; // shared between the ISR and main
int main(void) {
timerElapsed = 0;
while (1) {
if (timerElapsed) {
timerElapsed = 0; // consume the flag ...
// ... then do the work the event calls for
} else {
// free to do something else
}
}
return 0;
}
The keyword
volatile is what makes this work, and to see why it is needed, you need one fact about how C is built, a fact no interpreted language prepares you for. C is not executed line by line as written: the compiler is free to rewrite your code into anything that behaves identically for everything it can see, including deleting a read, or a whole branch, that it can prove makes no difference. Now apply that to the loop above (Figure 8.3.8). The compiler compiles the ISR too, but no call to the ISR appears anywhere in the program, because hardware is the caller. So when the optimizer builds main(), where nothing ever sets timerElapsed, it is entitled to conclude the flag is always 0, read it once (or never), and quietly turn if (timerElapsed) into if (0). Declaring the variable volatile tells the compiler: this value can change at any time, by means you cannot see: fetch it fresh from memory at every use. Every variable an ISR shares with the rest of the program gets volatile, always.
volatile. The compiler compiles the ISR too, but no call to the ISR appears anywhere in the program, so when the optimizer builds main() (dashed boundary) it has no reason to think the flag can change mid-loop. The ISR’s write happens at a moment the hardware chooses. volatile forbids the assumption and forces a fresh read at every use.