CodeBlanks Logo Icon CodeBlanks

Interrupts

Learn to write interrupt handlers.

Interrupt

An interrupt is hardware notifying the CPU of an event. The CPU drops the current instruction, saves registers and jumps to the interrupt service routine (ISR). When the ISR ends, the CPU returns to its previous work.

ISRs must be very short: other interrupts may be delayed, the system may lock up. They do not throw exceptions (usually compiled with -fno-exceptions), do not use the heap, have no long loops. The hardware flag is cleared, a flag is set on a shared variable, the main loop does the work.

Shared variable is volatile

A variable shared between the ISR and the main loop must be volatile. Otherwise the compiler may read the variable once in the main loop and cache it; it will not see the new value written by the ISR.

Example: volatile bool flag = false;. The ISR sets flag = true;; the main loop waits with while (!flag) { }. Without volatile the compiler reads flag once and loops forever. So every variable shared with an ISR must be volatile.

Practice Use ISR-style volatile variables

Define global volatile bool flag = false; and volatile int counter = 0;. In main write flag = true;, counter = 5; and std::cout << counter;.

Starter code

main.cpp
#include <iostream>

// Define the flag and counter volatile variables here

int main() {
    // Set flag true, assign 5 to counter and print it
    return 0;
}

Sample solution

main.cpp
#include <iostream>

volatile bool flag = false;
volatile int counter = 0;

int main() {
    flag = true;
    counter = 5;
    std::cout << counter;
    return 0;
}

Expected output

5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does an ISR usually NOT do?

main.cpp
__attribute__((interrupt)) void isr() { /* ... */ }
  • Return quickly
  • Throw an exception Correct answer
  • Clear the flag
  • Write to hardware

Explanation: ISRs do not throw exceptions; exception tables are expensive and return is complex.

2 Complete the ISR name

Question
__attribute__((interrupt)) void ____() { /* ISR body */ }
Answer
__attribute__((interrupt)) void isr() { /* ISR body */ }

Explanation: isr is the name of the interrupt service routine.

3 Match each concept to its role

Term Meaning
ISR Interrupt service routine
volatile Shared variable
noexcept No exception
flag Interrupt flag

All lessons in Expert