uC/OS-II Task Stack

This section refers to the following sample application(s):

  • 00-uc_stack

When creating a task, you have to choose the amount of stack space you reserve in memory for it. To help you assess the maximum amount of stack space your task has been using so far, uC/OS-II provides the OSTaskStkChk() utility.

How it works is explained in the diagram below. When creating a task, you need to specify the OS_TASK_OPT_STK_CHK and OS_TASK_OPT_STK_CLR. This forces uC/OS-II to clear the stack memory upon initialization. When your stack grows, the stack pointer is changed, and data is written in the stack. Even when the stack usage shrinks (the stack pointer is move "down" in the figure below), the now unused stack space is not cleared. As your task continues executing, a "watermark" is left at the interface between stack space that was never used, and stack space that was.

The OSTaskStkChk() utility looks for that watermark, i.e. it walks "down" the stack space until it finds memory which is different from 0x00. This allows your application to check how much stack space the different tasks of you application have already used. You might use this information to decide to allocate less or more space to a task's stack. 


The 00-uc_stack Sample Application

The 00-uc_stack sample application creates a task and defines a CLI command. It runs without connecting to a 

SmartMesh

 network.

Every 2 seconds, the task calls a function, then prints its own stack usage. The function called calculates the sum of a series of numbers, recursively. While recursion is not efficient, it is used in this sample application precisely because each extra recursion level increases stack usage.

The number of recursion levels is configurable using the iter CLI command. By default, the number of iterations is 0, and the application prints the "base" stack usage, as obtained by the OSTaskStkChk() utility.

iteration 0
sum       0
stack usage: 296 bytes / 1024 bytes
iteration 0
sum       0
stack usage: 296 bytes / 1024 bytes
iteration 0
sum       0
stack usage: 296 bytes / 1024 bytes

You can increase the recursion level and see the stack usage increase.

> iter 10
> iteration 10
iteration 9
iteration 8
iteration 7
iteration 6
iteration 5
iteration 4
iteration 3
iteration 2
iteration 1
iteration 0
sum       55
stack usage: 404 bytes / 1024 bytes

Setting the recursion level back to 0 does not change the stack usage measured, since that value represents the maximum (rather than the current) stack usage.

> iter 1
> iteration 0
sum       0
stack usage: 404 bytes / 1024 bytes

You can also use the OSTaskStkChk() utility to measure the stack usage of a different task. You could, for example, implement a task which periodically measures the stack usage of the different tasks in your application. This might help you fine-tune the stack space allocated.