Task handles let you keep track of tasks you create in FreeRTOS. They help you control and communicate with tasks easily.
0
0
Task handle usage in FreeRTOS
Introduction
When you want to delete a task after creating it.
When you need to suspend or resume a specific task.
When you want to check or change the state of a task.
When you want to send notifications or messages to a task.
When you want to get information about a task, like its priority.
Syntax
FreeRTOS
TaskHandle_t xHandle = NULL;
xTaskCreate(
TaskFunction_t pvTaskCode,
const char * const pcName,
configSTACK_DEPTH_TYPE usStackDepth,
void *pvParameters,
UBaseType_t uxPriority,
TaskHandle_t *pxCreatedTask
);The TaskHandle_t is a pointer type used to identify tasks.
Passing the address of a TaskHandle_t variable to xTaskCreate stores the created task's handle.
Examples
This creates a task named "Task1" and saves its handle in
xTaskHandle.FreeRTOS
TaskHandle_t xTaskHandle = NULL;
xTaskCreate(
vTaskCode,
"Task1",
1000,
NULL,
1,
&xTaskHandle
);This suspends the task identified by
xTaskHandle.FreeRTOS
vTaskSuspend(xTaskHandle);
This deletes the task using its handle.
FreeRTOS
vTaskDelete(xTaskHandle);
Sample Program
This program creates a task and saves its handle. It runs the task printing a message every second. Then it suspends the task for 2 seconds, resumes it for 2 seconds, and finally deletes it.
FreeRTOS
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> TaskHandle_t xTaskHandle = NULL; void vTaskFunction(void *pvParameters) { for (;;) { printf("Task is running\n"); vTaskDelay(pdMS_TO_TICKS(1000)); } } int main(void) { xTaskCreate( vTaskFunction, "MyTask", 1000, NULL, 1, &xTaskHandle ); vTaskDelay(pdMS_TO_TICKS(3000)); printf("Suspending task...\n"); vTaskSuspend(xTaskHandle); vTaskDelay(pdMS_TO_TICKS(2000)); printf("Resuming task...\n"); vTaskResume(xTaskHandle); vTaskDelay(pdMS_TO_TICKS(2000)); printf("Deleting task...\n"); vTaskDelete(xTaskHandle); for (;;) {} return 0; }
OutputSuccess
Important Notes
Always check if the task handle is not NULL before using it.
Deleting a task frees its resources, so use vTaskDelete carefully.
Task handles are useful for controlling tasks after creation.
Summary
Task handles identify tasks and let you control them.
Use task handles to suspend, resume, or delete tasks.
Store the handle when creating a task to use it later.