In this lesson, you will learn how the hardware automatically preserves your program's state when an interrupt occurs, ensuring your main code can resume exactly where it left off.
The Problem of Interrupted Execution
When an interrupt is triggered, your CPU is mid-execution, likely busy performing calculations in registers like R0 through R12. If your Interrupt Service Routine (ISR) were to overwrite these registers without saving them first, your main program would crash or produce corrupt data upon returning. Manually saving every register in every ISR would be slow and error-prone.
The Hardware Solution: Stacking
In most modern architectures, such as the ARM Cortex-M, the hardware takes over this burden. When an interrupt is detected, the CPU performs an "automatic context save" by pushing a specific set of core registers onto the current stack. This process is called stacking.
Typically, the processor hardware automatically pushes:
R0–R3: General-purpose registersR12: Intra-procedure call scratch registerLR: Link Register (containing the return address)PC: Program Counter (address of the next instruction)xPSR: Program Status Register
The hardware uses the current stack pointer to store these values into RAM. Because this happens in silicon, it is incredibly fast and invisible to your C code.
The Return Sequence: Unstacking
Once your ISR reaches the end and executes a return instruction, the hardware initiates the unstacking process. It automatically pops those saved values from the stack back into the core registers.
Consider this sequence:
- Main Code: Processing
data = x + y(usingR0,R1). - Interrupt: Hardware pushes
R0,R1,PC, etc., to the stack. - ISR: You run your code; you can freely modify
R0–R3because the originals are safe on the stack. - Exit: Hardware pops the original values back into the registers, and the
PCis restored to point exactly back to yourdata = x + ycalculation.
This mechanism ensures that your C code doesn't need to manually save registers unless you are using specific registers that the hardware does not automatically protect.
Key Takeaway: The CPU hardware automatically stacks a core set of registers upon interrupt entry and restores them upon exit, allowing your ISR to run without destroying the state of your main application.