0
0
FreeRTOSprogramming~5 mins

Why priority design matters in FreeRTOS

Choose your learning style9 modes available
Introduction

Priority design helps decide which task runs first in a program. It keeps important jobs fast and smooth.

When you have multiple tasks and some must finish quickly, like reading sensors.
When you want to avoid delays in critical actions, like stopping a machine.
When you want your program to respond fast to user input.
When some tasks can wait while others run immediately.
When you want to save power by running tasks efficiently.
Syntax
FreeRTOS
In FreeRTOS, you set priority when creating a task:

xTaskCreate(
  TaskFunction,      // Function that implements the task
  "TaskName",       // Name of the task
  StackDepth,        // Stack size in words, not bytes
  Parameters,        // Parameters to the task
  Priority,          // Priority number (higher means more important)
  &TaskHandle        // Task handle
);

Priority is a number; higher means the task runs before lower priority tasks.

Tasks with the same priority share CPU time fairly.

Examples
This creates a task named SensorTask with priority 3.
FreeRTOS
xTaskCreate(Task1, "SensorTask", 1000, NULL, 3, NULL);
This creates a LoggerTask with lower priority 1, so it runs after higher priority tasks.
FreeRTOS
xTaskCreate(Task2, "LoggerTask", 1000, NULL, 1, NULL);
Sample Program

This program creates two tasks: one high priority and one low priority. The high priority task runs first and prints its message every second. The low priority task runs only when the high priority task is waiting.

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

void HighPriorityTask(void *pvParameters) {
    for (;;) {
        printf("High priority task running\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

void LowPriorityTask(void *pvParameters) {
    for (;;) {
        printf("Low priority task running\n");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

int main(void) {
    xTaskCreate(HighPriorityTask, "HighTask", 1000, NULL, 3, NULL);
    xTaskCreate(LowPriorityTask, "LowTask", 1000, NULL, 1, NULL);
    vTaskStartScheduler();
    return 0;
}
OutputSuccess
Important Notes

If a high priority task never waits, lower priority tasks may never run.

Design priorities carefully to avoid blocking important tasks.

Summary

Priority design controls which tasks run first.

Higher priority tasks get CPU time before lower ones.

Good priority design keeps your program fast and responsive.