Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 198 of 9363. Microcontroller Fundamentals and Bare-Metal CFree lesson

Managing Automatic Context Saving and Restoration

Analyze how the hardware automatically pushes and pops core registers onto the stack during interrupt entry and exit sequences.

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 registers
  • R12: Intra-procedure call scratch register
  • LR: 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:

  1. Main Code: Processing data = x + y (using R0, R1).
  2. Interrupt: Hardware pushes R0, R1, PC, etc., to the stack.
  3. ISR: You run your code; you can freely modify R0–R3 because the originals are safe on the stack.
  4. Exit: Hardware pops the original values back into the registers, and the PC is restored to point exactly back to your data = x + y calculation.

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.