DEV Community

Hedy
Hedy

Posted on

What is an interrupt and how is it used?

What Is an Interrupt?

An interrupt is a signal that temporarily stops (or “interrupts”) the normal execution of a program so the CPU can quickly respond to an event.

  • Think of it like someone tapping you on the shoulder while you’re reading → you pause, handle the request, then go back to reading.
  • It’s commonly used in microcontrollers, processors, and operating systems.

How Interrupts Work

  1. Main Program Running → CPU executes instructions sequentially.
  2. Event Occurs (e.g., button press, timer overflow, sensor data ready).
  3. Interrupt Request (IRQ) → Hardware or software sends a signal to the CPU.
  4. CPU Saves Context → Current state (registers, program counter) is saved.
  5. Interrupt Service Routine (ISR) → Special function runs to handle the event.
  6. Return from ISR → CPU restores saved state and resumes main program.

Types of Interrupts

  • Hardware Interrupts: Triggered by external devices (e.g., button, UART receive, ADC complete).
  • Software Interrupts: Triggered by software instructions (e.g., system calls).
  • Internal Interrupts: From inside the CPU (e.g., divide by zero error, watchdog timer(What is a Watchdog?)).

How Interrupts Are Used (Examples)
1. Button Input Without Busy-Waiting

Instead of constantly checking if a button is pressed (polling), an interrupt can trigger an ISR when the button is pressed.

Saves CPU time and power.

2. Timer Interrupts

A timer can generate interrupts at regular intervals (e.g., every 1ms) → used for scheduling tasks, real-time clocks, or periodic sampling of sensors.

3. Communication Interfaces

  • UART/SPI/I²C use interrupts to signal when data has been sent or received.
  • This avoids constantly checking the communication status.

4. Emergency Responses

If a fault occurs (e.g., overcurrent detection), an interrupt can immediately stop the motor instead of waiting for main code to notice.

Example: Arduino LED Toggle with Interrupt

int buttonPin = 2;
int ledPin = 13;
volatile bool ledState = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleLED, FALLING);
}

void loop() {
  // Main loop does nothing – LED toggling handled by interrupt
}

void toggleLED() {
  ledState = !ledState;
  digitalWrite(ledPin, ledState);
}

Enter fullscreen mode Exit fullscreen mode

Here, pressing the button (falling edge) interrupts the main loop and runs toggleLED() instantly.

Advantages of Interrupts

  • Fast response to important events.
  • Efficient (CPU doesn’t waste time polling).
  • Real-time capability for embedded systems.

Things to Watch Out For

  • ISRs should be short and fast (no long delays, no heavy calculations).
  • Use volatile variables for shared data (to avoid compiler optimization issues).
  • Interrupts can nest or conflict → priority management is important.

Top comments (0)