0
0
FreeRTOSprogramming~5 mins

vTaskPrioritySet() dynamic priority in FreeRTOS

Choose your learning style9 modes available
Introduction

vTaskPrioritySet() lets you change a task's priority while your program is running. This helps your program decide which task should run first based on current needs.

When a task needs to do urgent work and should run before others.
When a task finishes important work and can lower its priority.
To avoid a task blocking others by temporarily lowering its priority.
When system conditions change and task priorities must adjust dynamically.
Syntax
FreeRTOS
void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );

xTask is the handle of the task whose priority you want to change.

uxNewPriority is the new priority level (0 is lowest).

Examples
Change the priority of the currently running task to 3.
FreeRTOS
vTaskPrioritySet(NULL, 3);
Change the priority of the task identified by xTaskHandle to 5.
FreeRTOS
vTaskPrioritySet(xTaskHandle, 5);
Sample Program

This program creates a task with priority 1. Inside the task, it prints its starting priority, then changes its own priority to 3 using vTaskPrioritySet(), and prints the new priority. Finally, the task deletes itself.

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

TaskHandle_t xTask1Handle = NULL;

void vTask1(void *pvParameters) {
    printf("Task1 started with priority %lu\n", (unsigned long)uxTaskPriorityGet(NULL));
    vTaskPrioritySet(NULL, 3); // Change own priority to 3
    printf("Task1 priority changed to %lu\n", (unsigned long)uxTaskPriorityGet(NULL));
    vTaskDelete(NULL);
}

int main(void) {
    xTaskCreate(vTask1, "Task1", configMINIMAL_STACK_SIZE, NULL, 1, &xTask1Handle);
    vTaskStartScheduler();
    return 0;
}
OutputSuccess
Important Notes

Changing a task's priority can cause immediate context switches if a higher priority task becomes ready.

Use NULL as the task handle to change the priority of the currently running task.

Priority values start at 0 (lowest) and go up to configMAX_PRIORITIES - 1.

Summary

vTaskPrioritySet() changes a task's priority while the program runs.

Use it to make tasks more or less important dynamically.

Remember to pass the task handle and the new priority number.