William Chang

How keil calculate __initial_sp(MSP) (micro lib)

Blog Post created by William Chang on May 13, 2018

MSP stands for Main stack pointer. In here, I mean the MSP stored in the address 0x0000 0000


The formula is

__initial_sp(MSP) = RAM Start address + sizeof(RW(.data)) + sizeof(ZI(.bss)) + sizeof(STACK(Minimum Stack Size))


RW(.data) stands for Read and Write data. (with pre-define value)

ZI.(bss) stands for Zero initialized data. (user don't give any value to it)

STACK stands for the number you set in CUBEMX.


Let's come to life.

1. CUBEMX Settings

2. KEIL settings

3. build the project and open the .map file.

      From the picture above, we can see the 0x1000 (4096) bytes allocate to heap_1.o, is exactly we set in FreeRTOS settings. STACK is exactly we set Minimum Stack Size in CUBEMX Settings.

4. test the formula

    __initial_sp(MSP) = 0x2000 4000 + ... + 0x400 = 0x20005618

    Enter the Debug mode, if we see the value in 0x0000 0000 or 0x0800 0000 or 0x2000 0000 or R13(SP) is 0X20005618, Our formula is correct.

    I got the SP , So the formula is correct!