0
0
FreeRTOSprogramming~5 mins

Priority-based scheduling in FreeRTOS

Choose your learning style9 modes available
Introduction

Priority-based scheduling helps decide which task runs first based on how important it is. This way, important tasks get done quickly.

When you have multiple tasks and some must finish before others.
When a critical task needs immediate attention over less important ones.
When you want to make sure your system responds fast to urgent events.
Syntax
FreeRTOS
BaseType_t xTaskCreate(TaskFunction_t pxTaskCode, const char * const pcName, configSTACK_DEPTH_TYPE usStackDepth, void *pvParameters, UBaseType_t uxPriority, TaskHandle_t *pxCreatedTask);

uxPriority is the task priority number; higher means more important.

FreeRTOS runs the highest priority task that is ready to run.

Examples
This creates Task1 with priority 2.
FreeRTOS
xTaskCreate(Task1, "Task1", 1000, NULL, 2, NULL);
This creates Task2 with priority 5, which is higher than Task1.
FreeRTOS
xTaskCreate(Task2, "Task2", 1000, NULL, 5, NULL);
Sample Program

This program creates two tasks. The high priority task runs more often because it has a higher priority (3) than the low priority task (1). You will see the high priority task message more frequently.

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

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

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

int main(void) {
    xTaskCreate(TaskLowPriority, "LowPriority", 1000, NULL, 1, NULL);
    xTaskCreate(TaskHighPriority, "HighPriority", 1000, NULL, 3, NULL);
    vTaskStartScheduler();
    for(;;);
    return 0;
}
OutputSuccess
Important Notes

Higher priority tasks can interrupt lower priority tasks.

If two tasks have the same priority, FreeRTOS switches between them to share CPU time.

Use priorities carefully to avoid starving lower priority tasks.

Summary

Priority-based scheduling runs the most important task first.

Set task priority when creating tasks with xTaskCreate.

Higher priority tasks run more often and can interrupt lower priority ones.