Search code examples
stackrtosfreertos

Calculation of stack size in FreeRtos or TI rtos


Recently I was working with FreeRTOS and created some tasks to perform my required actions. Although it seems like every time when I create a new task with xTaskCreate() or TI GUI configuration, I simply try to keep my stack size as large as required so as to not have a stack overflow.

Is there any way to calculate the maximum stack size used by my tasks with respect to the following events?

  1. Stack used by global and local variable
  2. Stack used by the maximum number of recursion of the function
  3. Including the interrupt context switching

Solution

  • The compiler, compiler optimisation level, CPU architecture, local variable allocations and function call nesting depth all have a large impact on the stack size. The RTOS has minimal impact. For example, FreeRTOS will add approximately 60 bytes to the stack on a Cortex-M - which is used to store the task's context when the task is not running. Whichever method you use to calculate stack usage in your non-RTOS project can be used in your RTOS project too - then add approximately 60 bytes.

    You can calculate these things, and that can be important in safety critical applications, but in other cases a more pragmatic approach is to try it and see - use the features of the RTOS to measure how much stack is actually being used and use the stack overflow detection - then adjust until you find something optimal. http://www.freertos.org/Stacks-and-stack-overflow-checking.html http://www.freertos.org/uxTaskGetStackHighWaterMark.html