In previous lessons, we used polling to check conditions—like whether a button is pressed or a timer has elapsed. But polling wastes CPU time and power.
That’s where Interrupts shine:
🧠 They let your microcontroller react instantly to events — without constantly checking.
🧠 What is an Interrupt?
An Interrupt is a hardware-triggered signal that pauses your main program and immediately runs a special function called an Interrupt Service Routine (ISR).
After the ISR finishes, your main code resumes as if nothing happened.
🖱️ Real-Life Analogy
Polling:
👀 You constantly check your phone for messages.
Interrupts:
📩 Your phone notifies you when a message arrives — and you respond immediately.
🔁 Polling vs Interrupt Example
❌ Polling (inefficient):
while (1) {
if (BUTTON_PIN & (1 << 2)) {
toggle_led();
}
}
✅ Interrupt-Based (efficient):
void button_isr() {
toggle_led(); // Respond only when pressed
}
🛠️ How Interrupts Work (Basic Flow)
- External event occurs (e.g., button press)
- MCU detects the signal on a configured interrupt pin
- It pauses the current task
- Executes the ISR
- Returns to the main code
🧪 Register-Level Example (Simplified for STM32/AVR-like MCU)
// Pseudocode
#define INTERRUPT_ENABLE_REG (*((volatile uint32_t*)0x40000010))
#define ISR_VECTOR_TABLE (*((void (**)())0x00000000))
void init_interrupts() {
INTERRUPT_ENABLE_REG |= (1 << 2); // Enable interrupt for button pin
ISR_VECTOR_TABLE[2] = &button_isr; // Point vector table to our ISR
}
void button_isr() {
toggle_led(); // This is your response
}
📌 Actual syntax will vary by microcontroller vendor.
🧩 Types of Interrupts
| Type | Example |
| External | GPIO button, sensor pulse |
| Timer | Delayed events, PWM refresh |
| UART/Serial | Data received |
| ADC Conversion | Analog read completed |
⚠️ Tips for Writing ISRs
- Keep them short and fast
- Don’t use delay() or heavy logic
- Use flags to signal the main loop
- Avoid using malloc(), printf(), or any blocking function
🧠 Common Pattern: Flag Set in ISR
volatile bool button_pressed = false;
void button_isr() {
button_pressed = true;
}
int main() {
while (1) {
if (button_pressed) {
button_pressed = false;
toggle_led();
}
}
}
💬 Pro Tip
Every interrupt has a priority. Some are more critical (e.g., system faults, timers). Learn how to configure interrupt priority levels for real-time systems.
🧰 Debugging Interrupts
- Use LED toggles inside ISRs for quick visual checks.
- Use a logic analyzer or breakpoints to trace ISR triggers.
- Make sure to clear the interrupt flag after handling.
🔍 Up Next (Day 9):
🧱 Digital Input – Reading Sensors, Buttons, and Switches
How do you reliably read buttons, avoid bouncing, and handle digital inputs with confidence?





















