In this lesson, you will learn how the processor hardware automatically "takes a snapshot" of its current work when an interrupt occurs, allowing it to seamlessly return to your main code later.
The Problem: Interrupting the Flow
Imagine your processor is calculating a complex mathematical formula in your main loop when suddenly, a timer interrupt triggers. If the processor immediately jumped to the Interrupt Service Routine (ISR) and started changing register values (like R0 or R1), it would overwrite the data needed for your math formula. When the ISR finished, your original calculation would be corrupted. To prevent this, we need a mechanism for Context Switching.
Hardware-Assisted State Preservation
On most modern embedded microcontrollers (like those using the ARM Cortex-M architecture), the processor performs this preservation automatically in hardware the moment an interrupt is signaled. This process is called "stacking."
When an interrupt occurs, the hardware automatically pushes the critical registers—specifically the Program Counter (PC), the Link Register (LR), the Status Register (xPSR), and general-purpose registers (R0-R3, R12)—onto the Stack.
Think of the Stack as a dedicated "waiting room" in RAM. By pushing these values onto the stack, the processor creates a "context" or a snapshot of exactly where it was and what values it was holding.
; Conceptual view of what the hardware does:
PUSH {R0-R3, R12, LR, PC, xPSR} ; Hardware saves context to memory
BL Interrupt_Handler ; Jump to your ISR code
POP {R0-R3, R12, LR, PC, xPSR} ; Hardware restores context from memory
Restoring the Context
Once your ISR finishes, the processor executes a special return instruction. This triggers the hardware to perform an "unstacking" operation. It pops those stored values off the stack and back into the physical registers. Because the PC (which tells the processor which instruction to execute next) was part of the stack, the processor doesn't just return to the main code—it returns to the exact line of code it was executing the moment the interrupt occurred. This ensures the transition between the background task and the interrupt is completely transparent to your main program.
Key Takeaway: Processor state preservation uses the Stack to automatically save and restore critical registers, ensuring the system can resume its original task exactly where it left off after an interrupt.