Understanding Interrupts in Microcontrollers

1. What is an Interrupt? — A Simple Understanding

Let’s start with a real-life example:

You are writing a blog when suddenly your boss sends a message asking you to handle an urgent task immediately. So, you pause your blog work, complete your boss’s task, and then return to writing your blog.

This is the essence of an interrupt!

Understanding Interrupts in Microcontrollers

💡 Professional Terminology Explained:

  • Interrupt Source: The boss’s message — triggers the interrupt
  • Interrupt Response: You pause writing the blog — CPU responds to the interrupt
  • Interrupt Service: Handling the boss’s task — Interrupt Service Routine (ISR)
  • Interrupt Return: Returning to continue writing the blog — Interrupt handling ends, returning to the original task

This entire process in a microcontroller is called the interrupt mechanism: When a more urgent event occurs during program execution, the CPU will “interrupt” the current task to handle that more urgent task, and then return to continue the original program.

2. Why Do We Need Interrupts?

In embedded systems, many events are spontaneous or random, such as:

  • External buttons being pressed
  • Data received on the serial port
  • Sensor state changes
  • Timer timeouts

If we use polling to check these events, it is not only inefficient but also easy to miss opportunities. The interrupt mechanism can capture these spontaneous events in a timely manner, improving response efficiency and is one of the core mechanisms of embedded systems.

3. The Relationship Between Threads and Interrupts (A Deeper Understanding)

Although most microcontroller programs are executed in a single thread, we can use the concept of threads to better understand interrupts:

  • Main program = Main thread
  • Interrupt Service Routine = Interrupting thread

An interrupt is like an interrupting thread, which executes and then returns to the main thread to continue running.

Although microcontrollers typically have a single CPU (usually single-core), through interrupts combined with “time slicing,” they can achieve an effect that looks like multi-threaded operation.

For example:

Main program: Read temperature sensor → Update display → Write log
Interrupt A: Trigger every 1 second, collect temperature data
Interrupt B: Respond immediately when a command is received on the serial port

The interrupt mechanism allows microcontrollers to handle multiple tasks without missing any important events.

4. Basic Components and Process of Interrupts

🌐 Components of the Interrupt System:

  1. Interrupt Source: The event that generates the interrupt request (e.g., external button, timer overflow, etc.)
  2. Interrupt Controller: Manages multiple interrupt sources, priorities, masking, etc. (e.g., NVIC)
  3. Interrupt Vector Table: After an interrupt occurs, the CPU looks up the jump address of the service function
  4. Interrupt Service Function (ISR): The program logic code that responds to the interrupt

🔁 Interrupt Handling Process:

Program running normally...
↓
Interrupt source event occurs (e.g., button press)
↓
CPU pauses the current task, saves context
↓
Executes the Interrupt Service Function (ISR)
↓
ISR execution completes, restores context
↓
Program continues executing the interrupted main task

5. Interrupt Priority and Nesting

If multiple interrupts occur simultaneously, which one should the CPU handle first?

This involves interrupt priority.

For example:

  • You are writing a blog (main program)
  • Your boss sends a message (Interrupt A)
  • At the same time, your wife also sends a task (Interrupt B)

Which one do you prioritize? Of course, it’s your wife’s task! This indicates that your wife’s interrupt has a higher priority.

Interrupt Nesting:

If you are executing a low-priority interrupt task and a high-priority interrupt comes in, it can interrupt the currently executing interrupt, execute itself first, and then return to continue executing the original interrupt task.

6. Common Types of Interrupts

Interrupt Type Source Description
External Interrupt From external pin transitions e.g., button interrupt
Timer Interrupt When the timer reaches its set time e.g., periodic execution
Serial Interrupt When serial data transmission is complete e.g., command communication
ADC Interrupt When analog signal conversion is complete e.g., sensor reading
DMA Interrupt When data transfer is complete e.g., high-speed data transfer

7. Practical Example: External Interrupt Example on 51 Microcontroller

🎯 Objective:

Press button K3 → LED state toggles

🔧 Example Code Analysis:

#include "reg52.h"

typedef unsigned int u16;
typedef unsigned char u8;

sbit k3 = P3^2;  // Button connected to P3.2 (INT0)
sbit led = P2^0; // LED connected to P2.0

// Delay function (for debouncing)
void delay(u16 i) {
    while(i--);
}

// Interrupt initialization function
void Int0Init() {
    IT0 = 1; // Set to trigger on falling edge
    EX0 = 1; // Enable external interrupt 0
    EA  = 1; // Enable global interrupts
}

void main() {
    Int0Init(); // Initialize interrupt
    while(1);   // Main loop waiting for interrupt
}

// External interrupt 0 service function
void Int0() interrupt 0 {
    delay(1000);  // Debounce
    if (k3 == 0) {
        led = ~led;  // Toggle LED state
    }
}

📌 Note:

  • <span>IT0=1</span> sets to trigger on falling edge (when the pin level goes from high to low)
  • <span>EX0=1</span> allows external interrupt 0
  • <span>EA=1</span> enables global interrupts
  • The ISR function is named <span>Int0()</span>, and <span>interrupt 0</span> indicates it is interrupt number 0

8. Supplement on STM32 Interrupt Mechanism (A Must-Read for STM32 Beginners)

1️⃣ Brief Summary of Interrupt Configuration Steps:

  1. Configure the pin as input mode (pull-up/pull-down/floating)
  2. Configure the mapping relationship between the pin and the interrupt line (EXTI and GPIO mapping)
  3. Set the trigger method (rising edge, falling edge, both edges)
  4. Enable the interrupt line
  5. Configure the NVIC interrupt controller (set preemption priority and response priority)
  6. Write the Interrupt Service Function (ISR)

2️⃣ Two Concepts of Interrupt Priority in STM32:

Name Description
Preemption Priority Whether it can interrupt other interrupts
Response Priority When preemption priorities are the same, which one is executed first

The smaller the priority value, the higher the level!

For example: Preemption priority = 1, response priority = 2 is higher than preemption priority = 2, response priority = 0.

3️⃣ NVIC Priority Grouping (Important)

The NVIC priority grouping determines the bit allocation for preemption priority and response priority, for example:

  • Group 0: 4 bits are all response priority (no interrupt nesting allowed)
  • Group 3: 2 bits for preemption + 2 bits for response (nesting allowed)

9. Summary in One Sentence

Interrupts are a “ready-to-call” task mechanism that allows microcontrollers to flexibly handle interrupt events, making it an indispensable mechanism in embedded development.

Leave a Comment