0
0
FreeRTOSprogramming~5 mins

Choosing priorities for real applications in FreeRTOS

Choose your learning style9 modes available
Introduction

We choose task priorities to decide which task runs first when many tasks want to run. This helps important tasks finish quickly.

When you have multiple tasks and want the most important one to run first.
When some tasks must respond quickly, like reading a sensor or handling user input.
When you want to avoid delays in critical parts of your program.
When you want less important tasks to run only when the system is free.
When you want to balance work so the system stays responsive.
Syntax
FreeRTOS
xTaskCreate(TaskFunction, "TaskName", StackSize, Parameters, Priority, TaskHandle);

Priority is a number where higher means more important.

Priorities usually start at 0 (lowest) up to configMAX_PRIORITIES - 1.

Examples
This creates a task named SensorTask with priority 3, which is quite important.
FreeRTOS
xTaskCreate(Task1, "SensorTask", 1000, NULL, 3, NULL);
This creates a LoggerTask with priority 1, less important than SensorTask.
FreeRTOS
xTaskCreate(Task2, "LoggerTask", 1000, NULL, 1, NULL);
This creates an IdleTask with the lowest priority 0, running only when others are idle.
FreeRTOS
xTaskCreate(Task3, "IdleTask", 1000, NULL, 0, NULL);
Sample Program

This program creates two tasks: SensorTask with higher priority 3 and LoggerTask with lower priority 1. SensorTask prints "Sensor reading" every second. LoggerTask prints "Logging data" every two seconds. Because SensorTask has higher priority, it runs first whenever ready.

FreeRTOS
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>

void SensorTask(void *pvParameters) {
    for (;;) {
        printf("Sensor reading\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void LoggerTask(void *pvParameters) {
    for (;;) {
        printf("Logging data\n");
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}

int main(void) {
    xTaskCreate(SensorTask, "SensorTask", 1000, NULL, 3, NULL);
    xTaskCreate(LoggerTask, "LoggerTask", 1000, NULL, 1, NULL);
    vTaskStartScheduler();
    for (;;) {}
    return 0;
}
OutputSuccess
Important Notes

Higher priority tasks can interrupt lower priority ones.

Be careful to avoid priority inversion where a low priority task blocks a high priority one.

Use priorities to keep your system responsive and efficient.

Summary

Task priority decides which task runs first in FreeRTOS.

Higher number means higher priority and more importance.

Set priorities based on how fast tasks must respond.