Skip to main content

Microcontrollers

Chapter 8 Interrupts

Interrupts are used to respond to important events that require immediate attention. Rather than checking multiple sensors, peripheral hardware, or other status flags continuously throughout the execution of program code (a process known as polling), important events can be made to interrupt regular program flow to execute a particular action, and then go back to regular program code.
If a particular interrupt is enabled, the corresponding hardware in the microcontroller can generate an interrupt request. When an interrupt request is asserted, the current value in the program counter is stored so the microcontroller knows where to return to after the interrupt has been handled. After the interrupt request is asserted, this causes a special piece of code known as an interrupt service routine (ISR) to be executed. The program memory address of each ISR is stored in a special location in memory known as an interrupt vector table. This allows each individual interrupt to have its own custom ISR associated with it. The address location in the interrupt vector table is loaded into the program counter to execute the ISR. When the ISR has concluded, the interrupt request flag is de-asserted and the code goes back to the previous program counter value and continues executing normally until another interrupt request is generated.
Flowcharts that compare continuous polling to interrupts are shown in FigureΒ 8.0.1.
Two flowcharts. The flowchart on the left is labeled "polling." First is a setup block. Then it checks system A, addresses system A, checks system B, addresses system B, checks system C, addresses system C, performs tasks, and goes back to checking system A. The flowchart on the right is labeled "Interrupts." First is a setup block. Then it continuously performs tasks. As needed, a block named "interrupt service routine" is accessed.
Figure 8.0.1. Program flow of software that uses continuous polling to monitor systems (left), versus software that uses interrupts to asynchronously handle important events (right).
Because interrupts are invoked asynchronous to normal program executing, there are some important things to keep in mind when writing code that includes interrupts.
  • The program counter will load the address listed in the interrupt vector table, so if an interrupt is enabled, a corresponding ISR must be defined. Otherwise, the program counter will go to a memory location that could cause the program to stop executing.
  • An ISR cannot be formally invoked, so variables accessed by an ISR must be global.
  • ISRs must be kept as short as possible so as not to otherwise interfere with other program operations as well as other interrupt servicing. This includes avoiding the use of function calls in an ISR.