ABC of Electronics cosycom.com
ESP32 BASICS · LESSON 17

Using Interrupts on the ESP32

Reacting to a pin change instantly instead of polling it in a loop, and doing it safely.

Polling a pin in loop() works, but it wastes time checking a pin that hasn't changed, and it can miss a fast pulse entirely if the loop is busy doing something else. An interrupt lets the hardware call a function the instant a pin changes, no matter what the main code is doing.

interrupt_basic.ino
#define BUTTON_PIN 14
volatile bool pressed = false;

void IRAM_ATTR onButtonPress() {
  pressed = true;
}

void setup() {
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), onButtonPress, FALLING);
}

void loop() {
  if (pressed) {
    Serial.println("Caught it!");
    pressed = false;
  }
}

Rules for interrupt handlers

  • Keep the handler tiny — set a flag or a counter, and do the real work back in loop().
  • Mark shared variables volatile so the compiler doesn't cache a stale copy.
  • Mark the handler function IRAM_ATTR so it's kept in fast internal memory, ready to run immediately.
KEY IDEA
An interrupt handler is not the place for Serial.println(), delay(), or anything slow — treat it as a doorbell, not a conversation.