Table of Contents
The ESP32 allows interrupts to be triggered on GPIO pins. The most common scenarios are when a pin changes state (either HIGH to LOW or LOW to HIGH), and an interrupt is triggered to execute an ISR.
Steps to Configure GPIO Interrupts:
- Define the ISR Function:
- The ISR should be a short function that handles the interrupt event. It will typically change a flag or set a variable.
- Attach the Interrupt:
- Use the function attachInterrupt() to associate a GPIO pin with an interrupt service routine.
- Set the Triggering Mode:
- You can set the interrupt to be triggered on a rising edge, falling edge, or change in state.
- Enable the Interrupt:
- You use attachInterrupt() to enable the interrupt on a specific GPIO pin.
Example Code: GPIO Interrupt for Button Press (External Interrupt)
In this example, we will use a GPIO pin (e.g., GPIO 12) to detect a button press. The interrupt will trigger a function whenever the button is pressed (falling edge event).
#define BUTTON_PIN 12 // Button is connected to GPIO12
volatile bool buttonPressed = false; // Flag to indicate button press
// Interrupt service routine (ISR)
void IRAM_ATTR buttonISR() {
buttonPressed = true; // Set the flag when the button is pressed
}
void setup() {
Serial.begin(115200);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set BUTTON_PIN as input with pull-up resistor
// Attach interrupt on falling edge (button press)
attachInterrupt(BUTTON_PIN, buttonISR, FALLING); // Trigger ISR on falling edge
Serial.println("System Ready. Press the button.");
}
void loop() {
if (buttonPressed) {
Serial.println("Button pressed!");
buttonPressed = false; // Reset the flag after handling
}
}
Explanation:
- ISR Function: The ISR (buttonISR()) is executed when GPIO12 detects a falling edge (i.e., when the button is pressed). The ISR sets a flag buttonPressed to true.
- GPIO Setup: The pinMode(BUTTON_PIN, INPUT_PULLUP) ensures that the button pin is set up with a pull-up resistor, meaning the pin will read HIGH when the button is not pressed and LOW when it is pressed.
- Interrupt Attachment: The attachInterrupt() function is used to attach the ISR to GPIO12. The interrupt is triggered on the falling edge of the button press.
Interrupt Modes:
The interrupt can be triggered in the following ways:
- RISING: Triggered when the pin goes from LOW to HIGH.
- FALLING: Triggered when the pin goes from HIGH to LOW.
- CHANGE: Triggered whenever the pin changes state (HIGH to LOW or LOW to HIGH).