An interrupt is a mechanism that allows a microcontroller like the ESP32 to pause the execution of the current program and execute a special function (called an interrupt service routine, or ISR) in response to an event (such as a change in a GPIO pin, a timer reaching a certain value, etc.). After the ISR is executed, the ESP32 will resume the main program where it left off.
Types of Interrupts in ESP32
- External Interrupts (GPIO Interrupts):
- The ESP32 allows external events (like pin changes) to trigger an interrupt. These are typically triggered by changes on GPIO pins (rising edge, falling edge, or both).
- External interrupts are useful for tasks like detecting button presses or reading sensor inputs in real-time.
- Internal Interrupts:
- These are triggered by internal events, such as timers or peripherals like the ADC (Analog-to-Digital Converter). For example, you can configure an interrupt to be triggered when a certain timer expires.
- ESP32 has built-in timers that can trigger interrupts at specified intervals.
Interrupts in the ESP32: Key Concepts
- Interrupt Service Routine (ISR):
- An ISR is the function that is executed when an interrupt occurs. This function should be short and fast because the microcontroller stops executing the main code and runs the ISR.
- ISRs must be defined with interrupt attributes to ensure they work correctly in the interrupt context.
- Interrupt Priority:
- The ESP32 allows different interrupt sources to have priorities. Higher-priority interrupts are executed before lower-priority ones.
- Edge Triggered vs Level Triggered:
- Edge Triggered: The interrupt is triggered when the GPIO pin changes state (from HIGH to LOW or from LOW to HIGH).
- Level Triggered: The interrupt is triggered when the GPIO pin stays in a certain state (HIGH or LOW) for a period of time.
- Interrupt Masking:
- The ESP32 can mask interrupts to prevent certain interrupts from being executed while other tasks are in progress.
Using Timers for Interrupts (Internal Interrupts)
The ESP32 has internal timers that can generate interrupts. These timers can be used to execute code at specific intervals, like setting up periodic tasks.