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

Configuring the Initial Stack Pointer

Students will demonstrate how the hardware automatically initializes the stack pointer from the first entry of the vector table upon reset.

In this lesson, you will learn how the hardware automatically initializes the Stack Pointer (SP) by reading the very first entry of the vector table upon system reset.

The Foundation of Execution

Before your main() function can ever execute, your microcontroller needs a place to store temporary variables, return addresses, and local data. This workspace is the stack, and its location is tracked by a special CPU register called the Stack Pointer (SP).

In most modern embedded architectures (like ARM Cortex-M), you don't manually set the SP register using C code. Instead, the hardware performs this task automatically the moment you power on or reset the chip.

The Vector Table Connection

When the CPU resets, it performs a hardware-level "fetch" from a specific memory address—usually 0x00000000—where the Vector Table begins. The first 4-byte entry in this table is not code; it is the Initial Stack Pointer value.

Imagine your startup file looks like this:

// A simplified vector table
uint32_t vector_table[] __attribute__((section(".isr_vector"))) = {
    0x20002000,  // [0] Initial Stack Pointer (Top of RAM)
    (uint32_t)Reset_Handler, // [1] Reset Vector
    // ... other interrupts
};

When the processor comes out of reset:

  1. It reads the value at vector_table[0] (0x20002000).
  2. It copies that value directly into the internal SP register.
  3. Only then does it jump to the address found at vector_table[1] to start executing your Reset_Handler.

Why This Matters

If you define the wrong address in that first slot, the CPU will attempt to use a memory location that might be invalid or outside of RAM. If that happens, any function call or local variable declaration will trigger a "Hard Fault," crashing your program before it even begins. By ensuring the first entry of your vector table points to the very top of your allocated RAM, you provide the system with a safe, empty canvas for its stack operations.

Key Takeaway: The hardware automatically initializes the Stack Pointer by loading the first entry of the vector table into the SP register during the reset sequence, long before your C code executes.