Learn Ucos for a long time, never understand how the task in the OS saves local variables in its own stack. I finally figured it out today.
1. How the task saves local variables when there is no OS
In my knowledge system, I always thought that there is only one stack in the microcontroller, take Stm32 as an example, in the boot file there is how a paragraph:
; Amount of Memory (in bytes) allocated for Stack
; Tailor this value to your application needs
;
; <o> Stack Size (in Bytes) <0x0-0xFFFFFFFF:8>
;
Stack_size EQU 0x00000400
Area STACK, Noinit, READWRITE, align=3
Stack_mem SPACE Stack_size
__initial_sp
Assuming that the stm32 memory has 16Kb, the starting address is, the stack grows downward, from the boot file can be seen, the size of the stack is 0x400, I call the system stack, the scope of the system stack is 0x0x20000000~0x20000400. In applications without an OS (bare-Ben), the CPU actually has two tasks, one for the interrupt task and one for the background task in the main function. When a function call or interrupt occurs, the system stack is used to hold the local variable and register state, that is, the SP points to 0x0x20000000~0x20000400.
How to save local variables in 2.ucos
In fact, there are no operating systems are the same, all the tasks in the local variables and the current register state in the stack, in the Ucos a task is allocated a stack, assuming that there are two tasks, the application allocation of the corresponding task stack is as follows:
Static OS_STK task1stk[128]; Assuming that the stack address for Task 1 is 0x20000500, then the local variables and register states in task 1 are saved in the 0x20000500~0x20000580
Static OS_STK task2stk[256]; Assuming that the stack address for Task 1 is 0x20000600, then the local variables and register states in task 2 are saved in the 0x20000600~0x20000700
When Task 1 runs, the stack used by the system is no longer 0x0x20000000~0x20000400, but 0x20000500~0x20000580, while task 2 runs, the stack in the system points to 0x20000600~0x20000700. So how do I switch the SP? Suppose you switch to task 1SP:
; Save Task 1SP
LDR R1, =TASK1STK; The SP exists in R1, and in Task 1 R1 equals 0x20000500~0x20000580
LDR R1, [R1]
STR R0, [R1]; R0 is SP's process being switched out
; Switch to SP for Task 1
MSR PSP, R0; Load PSP with new process SP
In this way, in the Ucos simulation system stack, generate the task stack, local variables in the task stack allocation, rather than in the system stack. My previous confusion was that the local variables in the task were assigned to the system stack, and the contents of the system stack were responsible for the task stack when the task was switched.
Ucos How to save local variables to the task stack