Interfacing GPIOs with External Interrupt Controllers
In this lesson, you will learn how to configure GPIO pins to trigger hardware interrupts on edge transitions, allowing your processor to respond to events instantly without wasting cycles on constant polling.
The Problem with Polling
Up until now, you have mostly used "polling" to detect input changes. In a polling loop, the CPU continuously checks a GPIO register to see if a switch has been pressed. This is inefficient: if you have a slow human pressing a button, the CPU might check that register millions of times while doing nothing else. It’s like standing at your front door watching through the peephole all day waiting for a delivery.
The Interrupt Solution
An External Interrupt Controller (often called an EXTI or NVIC peripheral) acts like a doorbell. Instead of watching the door, the CPU goes about its other tasks. When a signal transition—like a physical switch being pressed—occurs on a GPIO pin, the hardware automatically pauses the main program and jumps to a specific "Interrupt Service Routine" (ISR).
To set this up, you follow three steps:
- Configure the Pin: Set the GPIO pin as a digital input (as you learned in lesson 21).
- Configure the Trigger: Tell the Interrupt Controller whether to look for a Rising Edge (low-to-high transition), a Falling Edge (high-to-low), or both.
- Enable the Interrupt: Unmask the interrupt line in the controller so the CPU knows to pay attention to that specific pin.
Here is a conceptual look at how this logic is structured:
// Conceptually configuring an external interrupt
void setup_button_interrupt() {
// 1. Set pin as input
GPIO_SetMode(PORTA, PIN_0, MODE_INPUT);
// 2. Configure edge detection (Falling edge for active-low buttons)
EXTI_SetTrigger(PIN_0, FALLING_EDGE);
// 3. Enable the interrupt line in the NVIC
NVIC_EnableIRQ(EXTI0_IRQn);
}
// The processor jumps here automatically when the button is pressed
void EXTI0_IRQHandler() {
// Perform task immediately without polling
handle_button_press();
// Clear the interrupt pending bit to allow future triggers
EXTI_ClearPendingBit(PIN_0);
}
By offloading the monitoring task to hardware, you ensure your system remains responsive to external signals while saving power and CPU cycles for more important logic.
Key Takeaway: External interrupt controllers allow the CPU to remain idle or execute other code until a specific hardware event on a GPIO pin triggers an immediate, asynchronous response.