decadenza
decadenza

Reputation: 2588

ESP32 task priority with respect to main loop

The function xTaskCreate allows to specify a uxPriority number, higher for higher priority as specified at https://www.freertos.org/a00125.html.

But how is this priority considered with respect to the main loop, e.g.:

void myTask(void *p) {
//
// Doing stuff...
//
}

void init() {

xTaskCreate(myTask, "myStuff", 8*1024, NULL, 1, NULL); // Priority 1 or any other number.

}

void app_main() {
    
    init();


    while (1) { 
    //
    // **myTaskMain** doing other stuff.
    //
    }
}

What will have high priority? The function myTask running via xTaskCreate or myTaskMain running inside the main loop?

Upvotes: 0

Views: 3766

Answers (2)

Peter Andela
Peter Andela

Reputation: 466

Your program is more than incomplete. Normaly "doing other stuff" is just there looping.

Maiby this simple program wil help you to schedule 2 tasks:

#include <stdio.h>

#include "pico/stdlib.h"

#include "FreeRTOS.h"
#include "FreeRTOSConfig.h"
#include "task.h"

void GreenLEDTask(void *param)
{
    while (true) {
        printf("Green ON\n");
        vTaskDelay(1000);
        
        printf("Green OFF\n");
        vTaskDelay(1000);
    }
}

void RedLEDTask(void *param)
{
    while (true) {
        printf("    RED ON\n");
        vTaskDelay(100);
        
        printf("    RED OFF\n");
        vTaskDelay(100);
    }
}

int main() 
{
    stdio_init_all();
    for (int i = 0; i < 3; i++) {
        printf("Wait %d\n", i);
        sleep_ms(1000);
    }
    TaskHandle_t gLEDtask = NULL;
    TaskHandle_t rLEDtask = NULL;

    uint32_t status = xTaskCreate(
                    GreenLEDTask,
                    "Green LED",
                    1024,
                    NULL,
                    tskIDLE_PRIORITY,
                    &gLEDtask);

    uint32_t status2 = xTaskCreate(
                     RedLEDTask,
                     "Red LED",
                     1024,
                     NULL,
                     1,
                     &rLEDtask);

        vTaskStartScheduler();
    
        for( ;; )
        {
            //should never get here
        }
        printf("Cannot reach, end of main\n");
    }

The output will generate something like: Green ON RED OFF RED ON RED OFF RED ON RED OFF RED ON RED OFF RED ON RED OFF RED ON Green OFF RED OFF RED ON RED OFF RED ON RED OFF RED ON RED OFF RED ON RED OFF

Upvotes: 0

Arco
Arco

Reputation: 145

According to this table in de documentation, the app_main task has priority 1, so in your example the tasks will have the same priority.

Another way to get the priority of the app_main task is by calling uxTaskPriorityGet(NULL) (docs here) from app_main. If you want to change the priority of the app_main task you can do that by calling vTaskPrioritySet(NULL, uxNewPriority) (docs here) from app_main.

Upvotes: 3

Related Questions