Edgar
Edgar

Reputation: 2767

Is it important to set the perfect usStackDepth in xtaskcreate?

I am learning to program the ESP32 with ESP32-IDF

To start a task we need the method xtaskcreate which uses the parameter usStackDepth

This is what is written about usStackDepth in the documentation:

The size of the task stack specified as the number of variables the stack can hold - not the number of bytes. For example, if the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes will be allocated for stack storage.

Here is some more info: https://www.freertos.org/FAQMem.html#StackSize

I wrote a small application which reads the date and time from a DS3231 chip 1000 times. I start the task like this:

void app_main(){
    //2 * configMINIMAL_STACK_SIZE does not work,  3 * works
    if ( xTaskCreate(&task_loop1, "loop1_task", 3 * configMINIMAL_STACK_SIZE, NULL, 5, NULL) != pdPASS ) {
        printf("Creation of task failed\r\n");
    }
}

configMINIMAL_STACK_SIZE is also in the manual. If I use configMINIMAL_STACK_SIZE the program does not run, if I use 2 * configMINIMAL_STACK_SIZE it still does not run. If I use 3 * or higher (I tried maximum with 100 * configMINIMAL_STACK_SIZE it works fine.

Now my question: Is it important that I set the "correct" size for this parameter? Or does it not really matter as long as the parameter is high enough?

Do you think hard to know which size you use? Or do you just try something and if it works it's fine and if not then you try a higher value?

Upvotes: 0

Views: 2800

Answers (1)

tofro
tofro

Reputation: 6063

As long as there is memory available, you can set a task's stack size as large as you want - there's no downsides (except wasted memory).

As you have seen, you can easily set a task's stack size too small, this will typically make your system crash (but can also have even worse side effects like altered data, so never assume "it doesn't crash, so must be large enough").

How much stack your task actually needs depends on various aspects like number and size of local variables used, function call nesting,... You might want to use the FreeRTOS function

uxHighWaterMark = uxTaskGetStackHighWaterMark( NULL );

which returns the amount of stack items that were unused up to this point in the task and adapt your stack size accordingly.

Upvotes: 4

Related Questions