💡 Electron Parade
← Back to Academy

Hardware Interrupts

Ever write an Arduino sketch filled with delay() functions, only to realize your buttons are completely ignoring you? Your Arduino is too busy doing nothing during that delay to notice your frantic button pressing. Stop polling like a chump. Enter the magic of hardware interrupts. It’s the microcontroller equivalent of tapping someone on the shoulder and screaming “PAY ATTENTION TO ME NOW.”

What is a Hardware Interrupt?

Think of a hardware interrupt as a tap on the shoulder for your microcontroller. No matter what your Arduino is currently doing (even if it’s stuck in a long delay or a heavy calculation), an interrupt forces it to drop everything, handle the event immediately, and then resume exactly where it left off.

Here are a few reasons why interrupts are game-changers:

How to Use attachInterrupt()

To use a hardware interrupt on an Arduino Uno, you typically use pins 2 or 3. Here is a simple example that turns on an LED when a button is pressed, using an interrupt.

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  
  // Attach the interrupt to pin 2
  // Trigger the blink() function when the pin goes from HIGH to LOW (FALLING edge)
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, FALLING);
}

void loop() {
  // The main loop can do whatever it wants!
  // The LED state is handled entirely in the background.
  digitalWrite(ledPin, state);
  
  // Let's pretend we are doing some heavy processing here
  delay(1000); 
}

// This is the Interrupt Service Routine (ISR)
void blink() {
  state = !state; // Toggle the state
}

Breaking Down the Code

Interrupts are an essential tool for building responsive, professional-grade projects. Start incorporating them into your builds and see the difference!

Hardware You’ll Need

To follow along with this lesson, you’ll need the following components: