I was reading the STM32 Programming manual and somewhere on "page 18 " i see these two kind of stack pointers. I always think that there is only ONE stack and therefore only ONE stack pointer to that exists in MCUs and now i'm confused of what these pointers are and what's the difference between theme and each of these is used for what?
Electronic – Main Stack Pointer(MSP) vs Process Stack Pointer(PSP)
stackstack-pointerstm32
Related Topic
- STM32 dev kit: Which power pin, APP or EMU
- Electronic – What are the differences between rand() function and RNG (Random number generator) peripheral
- Electronic – How to start with STM32F103C8T6 board
- Electronic – Bare-metal start-up code for Cortex M3 .bss region initialization
- Electronic – STM32 L4 HAL_FLASH Writes in one function but not another
Best Answer
You are correct in a way, in the cortex m (which your stm32 is, though I can't say which variant unless you specify a part) there is one active stack pointer
r13
, this can however be either theMSP
orPSP
.The reason for two is to enable the user to easily implement a multi tasking 'operating system'.
The idea is that the
PSP
or process stack pointer is used by the individual tasks, and the kernel uses theMSP
.When an exception happens, a stack frame gets pushed to the currently active stack pointer, and then switches to use the
MSP
for the exception handler. In a multi tasking system, if the scheduler caused the exception, it is at this point that you change where thePSP
is pointing to be the stack pointer for the next task, and return from the exception. The destacking of the new stack pointer then returns execution to the next task.If you wish to see an example of code using both, a scheduler I wrote for the Cortex M4f is available on BitBucket, it's not documented, but it is fairly straight forward. A
svc
instruction is used to start the scheduler, and thenpendsv
exceptions handle the task switching, theTick
function should be called from a timer to ensure task switching.