In this lesson, you will learn how to shift your CPU from a "constant watcher" to an "event responder" by using hardware interrupts instead of polling.
The Inefficiency of Polling
Up until now, you have likely been reading sensors or checking status flags by using a while loop that runs constantly, checking a register value over and over. This is called polling. If you are waiting for a button press or a sensor threshold, the CPU spends 99% of its time asking, "Has anything happened yet?" This wastes power and prevents the CPU from doing other meaningful work, like calculating complex motor control algorithms.
Interrupts: The "Doorbell" Approach
An asynchronous interrupt acts like a doorbell. Instead of you (the CPU) standing at the door looking through the peephole all day (polling), you go about your work. When a specific hardware event occurs—such as a voltage change on an input pin—the hardware momentarily "pauses" the CPU’s main task, jumps to a special function called an Interrupt Service Routine (ISR) to handle the event, and then returns exactly where it left off.
This transition from polling to interrupts allows your system to handle real-time events with minimal latency and high power efficiency.
Conceptual Comparison
Consider the difference in code logic:
Polling (Inefficient):
while(1) {
if (GPIO_Read(PIN) == HIGH) { // CPU is trapped in this loop
HandleEvent();
}
}
Interrupt-Driven (Efficient):
// CPU performs other tasks, like managing PWM or ADC updates
void EXTI_IRQHandler(void) {
// Only runs when the hardware event occurs
HandleEvent();
}
In the interrupt-driven version, the CPU remains free to execute background tasks until the hardware triggers the IRQHandler. This decoupling of the CPU from the peripheral's status ensures that your system can respond immediately to asynchronous external events without wasting cycles on empty check loops. By utilizing the interrupt controller, you transform your architecture from a reactive system into a truly responsive one.
Key Takeaway: Interrupts improve CPU efficiency by allowing the processor to perform other tasks while waiting for hardware-triggered events, eliminating the wastefulness of constant polling.