| Task API Function | Description |
|---|---|
| xTaskCreate() | Creates a task dynamically |
| xTaskCreateStatic() | Creates a task statically |
| vTaskDelete() | Deletes a specified task |
| xTaskGetHandle() | Finds and returns a task handle by the task name |
| xTaskGetIdleTaskHandle() | Gets the handle of the Idle task |
| xTaskGetCurrentTaskHandle() | Gets the handle of the currently running task |
| vTaskPrioritySet() | Changes the priority of a specified task |
| uxTaskPriorityGet() | Gets the priority of a specified task |
| vTaskSuspend() | Suspends a specified task |
| vTaskResume() | Resumes a suspended task |
| xTaskResumeFromISR() | Resumes a suspended task from an ISR |
| vTaskDelayUntil() | Delays a task until a specified periodic wake time |
| xTaskGetTickCount() | Gets the current system tick count |
| xTaskGetTickCountFromISR() | Gets the current system tick count from an ISR |
| vTaskSetApplicationTaskTag() | Sets the application tag value of a specified task |
| xTaskGetApplicationTaskTag() | Gets the application tag value of a specified task |
| SetThreadLocalStoragePointer() | Sets a thread-local storage pointer |
| GetThreadLocalStoragePointer() | Gets a thread-local storage pointer |
| pcTaskGetName() | Gets the name of a specified task |
| uxTaskGetNumberOfTasks() | Gets the number of tasks currently existing |
| vTaskGetInfo() | Retrieves information about a specified task |
| uxTaskGetSystemState() | Retrieves the status information of tasks |
| eTaskGetState() | Gets the state of a task, returned of type eTaskState |
| xTaskGetSchedulerState() | Gets the current state of the task scheduler |
| vTaskGetRunTimeStats() | Gets the execution-time statistics of each task |
| vTaskList() | Lists information of all tasks in a table |
| uxTaskGetStackHighWaterMark() | Gets the minimum amount of stack space that has remained available since the task started, known as the stack high-water mark. |

/* Task control block. A task control block (TCB) is allocated for each task,
* and stores task state information, including a pointer to the task's context
* (the task's run time environment, including register values)
*/
typedef struct tskTaskControlBlock
{
volatile StackType_t *pxTopOfStack;
#if ( portUSING_MPU_WRAPPERS == 1 )
xMPU_SETTINGS xMPUSettings;
#endif
ListItem_t xStateListItem;
ListItem_t xEventListItem;
UBaseType_t uxPriority;
StackType_t *pxStack;
char pcTaskName[ configMAX_TASK_NAME_LEN ];
#if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
StackType_t *pxEndOfStack;
#endif
#if ( portCRITICAL_NESTING_IN_TCB == 1 )
UBaseType_t uxCriticalNesting;
#endif
#if ( configUSE_TRACE_FACILITY == 1 )
UBaseType_t uxTCBNumber;
UBaseType_t uxTaskNumber;
#endif
#if ( configUSE_MUTEXES == 1 )
UBaseType_t uxBasePriority;
UBaseType_t uxMutexesHeld;
#endif
#if ( configUSE_APPLICATION_TASK_TAG == 1 )
TaskHookFunction_t pxTaskTag;
#endif
#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
#endif
#if( configGENERATE_RUN_TIME_STATS == 1 )
uint32_t ulRunTimeCounter;
#endif
#if ( configUSE_NEWLIB_REENTRANT == 1 )
struct _reent xNewLib_reent;
#endif
#if( configUSE_TASK_NOTIFICATIONS == 1 )
volatile uint32_t ulNotifiedValue;
volatile uint8_t ucNotifyState;
#endif
#if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
uint8_t ucStaticallyAllocated;
#endif
#if( INCLUDE_xTaskAbortDelay == 1 )
uint8_t ucDelayAborted;
#endif
#if( configUSE_POSIX_ERRNO == 1 )
int iTaskErrno;
#endif
} tskTCB;xTaskCreate() creates a new FreeRTOS task using dynamically allocated memory. It specifies the task function, task name, stack size, input parameter, priority, and an optional task handle for controlling the task later. The function returns pdPASS when the task is created successfully or an error value when memory allocation fails.
#define configSUPPORT_DYNAMIC_ALLOCATION 1
BaseType_t xTaskCreate(
TaskFunction_t pxTaskCode, // Task function to execute
const char * const pcName, // Task name
const uint16_t usStackDepth, // Task stack size
void * const pvParameters, // Parameter passed to the task
UBaseType_t uxPriority, // Task priority
TaskHandle_t * const pxCreatedTask // Stores the created task handle
)
// ---------------------- Example ----------------------
#define TASK1_TASK_PRIO 2
#define TASK1_STK_SIZE 256
TaskHandle_t Task1Task_Handler;
void vTask1Task(void * pvParameters) {
while(1) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
#define TASK2_TASK_PRIO 3
#define TASK2_STK_SIZE 256
TaskHandle_t Task2Task_Handler;
void vTask2Task(void * pvParameters) {
while(1) {
vTaskDelay(pdMS_TO_TICKS(500));
}
}
xReturn = xTaskCreate((TaskFunction_t ) vTask1Task,
(const char * ) "Task1 Task",
(uint16_t ) TASK1_STK_SIZE,
(void * ) NULL,
(UBaseType_t ) TASK1_TASK_PRIO,
(TaskHandle_t * ) &Task1Task_Handler);
if (pdPASS == xReturn) {
printf("Create vTask1Task successfully.\r\n");
}
xReturn = xTaskCreate((TaskFunction_t ) vTask2Task,
(const char * ) "Task2 Task",
(uint16_t ) TASK2_STK_SIZE,
(void * ) NULL,
(UBaseType_t ) TASK2_TASK_PRIO,
(TaskHandle_t * ) &Task2Task_Handler);
if (pdPASS == xReturn) {
printf("Create vTask2Task successfully.\r\n");
}xTaskCreateStatic() creates a new FreeRTOS task using memory supplied by the application instead of the FreeRTOS heap. The caller provides the task stack buffer and task control block, making memory usage fixed and deterministic. The function returns the created task handle when successful or NULL if task creation fails.
#define configSUPPORT_STATIC_ALLOCATION 1
TaskHandle_t xTaskCreateStatic(
TaskFunction_t pxTaskCode, // Task function to execute
const char * const pcName, // Task name
const uint32_t ulStackDepth, // Task stack depth
void * const pvParameters, // Parameter passed to the task
UBaseType_t uxPriority, // Task priority
StackType_t * const puxStackBuffer, // User-provided stack buffer
StaticTask_t * const pxTaskBuffer // User-provided task control block
)
// ---------------------- Example ----------------------
#define TASK1_TASK_PRIO 2
#define TASK1_STK_SIZE 256
StackType_t Task1TaskStack[TASK1_STK_SIZE];
StaticTask_t Task1TaskTCB;
TaskHandle_t Task1Task_Handler;
void vTask1Task(void * pvParameters) {
while(1) {
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
#define TASK2_TASK_PRIO 3
#define TASK2_STK_SIZE 256
StackType_t Task2TaskStack[TASK2_STK_SIZE];
StaticTask_t Task2TaskTCB;
TaskHandle_t Task2Task_Handler;
void vTask2Task(void * pvParameters) {
while(1) {
vTaskDelay(pdMS_TO_TICKS(500));
}
}
static StackType_t IdleTaskStack[configMINIMAL_STACK_SIZE];
static StaticTask_t IdleTaskTCB;
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer,
StackType_t **ppxIdleTaskStackBuffer,
uint32_t *pulIdleTaskStackSize ) {
*ppxIdleTaskTCBBuffer=&IdleTaskTCB;
*ppxIdleTaskStackBuffer=IdleTaskStack;
*pulIdleTaskStackSize=configMINIMAL_STACK_SIZE;
}
static StackType_t TimerTaskStack[configTIMER_TASK_STACK_DEPTH];
static StaticTask_t TimerTaskTCB;
void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer,
StackType_t **ppxTimerTaskStackBuffer,
uint32_t *pulTimerTaskStackSize ) {
*ppxTimerTaskTCBBuffer=&TimerTaskTCB;
*ppxTimerTaskStackBuffer=TimerTaskStack;
*pulTimerTaskStackSize=configMINIMAL_STACK_SIZE;
}vTaskDelete() permanently removes a specified FreeRTOS task from the scheduler. Passing a task handle deletes that task, while passing NULL deletes the currently running task.
#define INCLUDE_vTaskDelete 1
void vTaskDelete(TaskHandle_t xTaskToDelete)
// Delete the currently running task
vTaskDelete(NULL);
vTaskDelete(xTaskGetCurrentTaskHandle());
// ---------------------- Example ----------------------
TaskHandle_t Task2Handle = NULL;
void Task1(void *argument) {
if (Task2Handle != NULL) {
vTaskDelete(Task2Handle);
Task2Handle = NULL;
}
while(1) {
printf("Task1 running\n");
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void Task2(void *argument) {
while(1) {
printf("Task2 running\n");
vTaskDelay(pdMS_TO_TICKS(500));
}
}xTaskGetIdleTaskHandle()
xTaskGetCurrentTaskHandle()
These functions retrieve handles for different tasks in FreeRTOS. xTaskGetHandle() searches for a task by its name and returns its handle, or NULL if no matching task is found. xTaskGetIdleTaskHandle() returns the handle of idle task, while xTaskGetCurrentTaskHandle() returns the handle of the task that is currently executing. The returned handles can be used with other task-management APIs to suspend, resume, delete, notify, or inspect the corresponding task.
#define INCLUDE_xTaskGetHandle 1
TaskHandle_t xTaskGetHandle(const char * pcNameToQuery)
#define INCLUDE_xTaskGetIdleTaskHandle 1
TaskHandle_t xTaskGetIdleTaskHandle(void)
#define INCLUDE_xTaskGetCurrentTaskHandle 1
TaskHandle_t xTaskGetCurrentTaskHandle(void)
// ---------------------- Example ----------------------
TestHandle = xTaskGetHandle("Query Task");
printf("TestHandle = %#x\r\n", TestHandle);vTaskPrioritySet() changes the priority of an existing FreeRTOS task. The xTask argument specifies the handle of the task whose priority will be changed; passing NULL changes the priority of the currently running task. The uxNewPriority argument specifies the new priority level, which must be between 0 and configMAX_PRIORITIES – 1, where a larger value represents a higher priority. Changing a task’s priority may cause an immediate context switch if another task becomes the highest-priority task that is ready to run.
#define INCLUDE_vTaskPrioritySet 1
// uxNewPriority: 0 to configMAX_PRIORITIES-1
void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority)
// Set current task priority to 1
vTaskPrioritySet(NULL, 1);
// ---------------------- Example ----------------------
TaskHandle_t red_handle, green_handle;
xTaskCreate(vRedLedControllerTask,
"Red Led Controller",
100,
NULL,
1, // task priority
&red_handle);
xTaskCreate(vGreenLedControllerTask,
"Green Led Controller",
100,
NULL,
1, // task priority
&green_handle);
// Red Led Controller Task
void vRedLedControllerTask(void *pvParamters) {
while(1){
HAL_GPIO_TogglePin(GPIOD, RED);
RedTaskProfiler++;
vTaskDelay(pdMS_TO_TICKS(1000));
// Set green task with priority of 3
vTaskPrioritySet(green_handle, 3);
}
}
// Green Led Controller Task
void vGreenLedControllerTask(void *pvParamters) {
while(1){
HAL_GPIO_TogglePin(GPIOD, GREEN);
GreenTaskProfiler++;
vTaskDelay(pdMS_TO_TICKS(500));
}
}uxTaskPriorityGet() returns the current priority of a FreeRTOS task. The xTask argument is the handle of the task whose priority is requested; passing NULL returns the priority of the currently running task. The function returns the task’s priority as a value of type UBaseType_t, where a larger value represents a higher priority.
#define INCLUDE_uxTaskPriorityGet 1
UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask)
// ---------------------- Example ----------------------
TaskHandle_t green_handle;
uint32_t green_priority;
// Get priority green LED task
green_priority = uxTaskPriorityGet(green_handle);vTaskSuspend() suspends a FreeRTOS task, preventing it from being scheduled until it is resumed using vTaskResume() or xTaskResumeFromISR(). The xTaskToSuspend argument specifies the handle of the task to suspend; passing NULL suspends the currently running task. A suspended task does not consume CPU time and remains suspended indefinitely until explicitly resumed.
#define INCLUDE_vTaskSuspend 1
void vTaskSuspend(TaskHandle_t xTaskToSuspend)
// ---------------------- Example ----------------------
vTaskSuspend(NULL);
vTaskSuspend(blue_handle);
void vBlueLedControllerTask(void *pvParamters) {
while(1) {
HAL_GPIO_TogglePin(GPIOD, BLUE);
BlueTaskProfiler++;
vTaskDelay(pdMS_TO_TICKS(500));
vTaskSuspend(NULL); // Suspend task itself
}
}vTaskResume() resumes a task that was previously suspended using vTaskSuspend(), allowing it to return to the Ready state and be scheduled again. The xTaskToResume argument is the handle of the suspended task to resume. If the resumed task has a higher priority than the currently running task, a context switch may occur immediately.
void vTaskResume(TaskHandle_t xTaskToResume)
// ---------------------- Example ----------------------
TaskHandle_t xTaskHandle;
vTaskResume(xTaskHandle);xTaskResumeFromISR() resumes a task that was previously suspended by vTaskSuspend() and is specifically designed to be called from an interrupt service routine. The xTaskToResume argument is the handle of the task to resume. The function returns pdTRUE when resuming the task causes a higher-priority task to become ready, indicating that a context switch should be requested before leaving the ISR; otherwise, it returns pdFALSE.
BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume)
// ---------------------- Example ----------------------
void EXTI0_IRQHandler(void) {
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0);
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
BaseType_t YieldRequired = pdFALSE;
if (GPIO_Pin == GPIO_PIN_0) {
YieldRequired = xTaskResumeFromISR(Task1Task_Handler);
if(YieldRequired == pdTRUE) {
portYIELD_FROM_ISR(YieldRequired);
}
}
}vTaskDelayUntil() blocks a task until a specified absolute wake time, making it useful for creating tasks that execute at a fixed and consistent period. The pxPreviousWakeTime argument points to a variable containing the task’s previous wake time; it is automatically updated after each call. The xTimeIncrement argument specifies the period between executions in system ticks. Unlike vTaskDelay(), this function compensates for task execution time and helps prevent timing drift.
#define INCLUDE_vTaskDelayUntil 1
void vTaskDelayUntil(
TickType_t * const pxPreviousWakeTime,
const TickType_t xTimeIncrement
)
// ---------------------- Example ----------------------
const TickType_t xPeriod = pdMS_TO_TICKS(500);
// Blue Led Controller Task
void vBlueLedControllerTask(void *pvParamters) {
TickType_t xLastWakeTime = xTaskGetTickCount();
while(1) {
// xLastWakeTime value will be updated automatically
vTaskDelayUntil(&xLastWakeTime, xPeriod);
HAL_GPIO_TogglePin(GPIOD, BLUE);
BlueTaskProfiler++;
}
}xTaskGetApplicationTaskTag()
vTaskSetApplicationTaskTag() assigns a hook-function pointer or custom tag to a specified task, while xTaskGetApplicationTaskTag() retrieves the assigned value. Passing NULL as the task handle refers to the calling task.
#define configUSE_APPLICATION_TASK_TAG 1
TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask)
void vTaskSetApplicationTaskTag(TaskHandle_t xTask,
TaskHookFunction_t pxHookFunction)
// ---------------------- Example ----------------------
TaskHookFunction_t currentTag = xTaskGetApplicationTaskTag(NULL); GetThreadLocalStoragePointer()
These functions provide each FreeRTOS task with its own array of task-specific void * values. The setter stores a pointer in a selected array slot, while the getter retrieves it. The task handle identifies which task’s storage is accessed; passing NULL selects the calling task. These pointers are useful for storing per-task context structures, buffers, library state, or other task-specific data without using separate global variables. FreeRTOS stores only the pointer, so the application remains responsible for allocating, maintaining, and freeing the referenced memory.
void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet,
BaseType_t xIndex,
void * pvValue)
void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery,
BaseType_t xIndex)
// ---------------------- Example ----------------------
#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 2
TaskContext_t xContext;
// Store the address in slot 0 of the current task
vTaskSetThreadLocalStoragePointer(NULL, 0, &xContext);
// Retrieve it later
TaskContext_t *pxContext =
(TaskContext_t *)pvTaskGetThreadLocalStoragePointer(NULL, 0);pcTaskGetName() retrieves the text name assigned to a FreeRTOS task when it was created. The xTaskToQuery parameter specifies the task handle; passing NULL returns the name of the currently running task. Task names are mainly used for debugging, logging, tracing, and task-status displays, and their maximum length is controlled by configMAX_TASK_NAME_LEN.
char *pcTaskGetName(TaskHandle_t xTaskToQuery)
// ---------------------- Example ----------------------
char *pcName = pcTaskGetName(xTaskHandle);
char *pcCurrentName = pcTaskGetName(NULL);uxTaskGetNumberOfTasks() returns the total number of tasks currently managed by the FreeRTOS kernel. This includes tasks in the Running, Ready, Blocked, and Suspended states, as well as the automatically created Idle task and any other kernel-created tasks, such as the timer service task when software timers are enabled. The function takes no parameters and returns the task count as a value of type UBaseType_t. It is commonly used to determine the required size of a TaskStatus_t array before calling uxTaskGetSystemState(). Because tasks may be created or deleted after the count is obtained, extra array space may be allocated when collecting system information.
UBaseType_t uxTaskGetNumberOfTasks(void)
// ---------------------- Example ----------------------
UBaseType_t uxTaskCount = uxTaskGetNumberOfTasks();vTaskGetInfo() retrieves detailed information about a single FreeRTOS task and stores it in a TaskStatus_t structure. The returned information can include the task handle, name, current state, current and base priorities, runtime counter, and stack usage details. Passing NULL as xTask queries the calling task. Setting xGetFreeStackSpace to pdTRUE calculates the stack high-water mark, while passing eInvalid as eState makes FreeRTOS determine the task’s current state automatically. This function is mainly useful for debugging, diagnostics, and system-monitoring tools.
#define configUSE_TRACE_FACILITY 1
void vTaskGetInfo(
TaskHandle_t xTask,
TaskStatus_t * pxTaskStatus,
BaseType_t xGetFreeStackSpace,
eTaskState eState
)
// ---------------------- Example ----------------------
printf("/************ vTaskGetInfo() **************/\r\n");
TaskHandle_t TaskHandle;
TaskStatus_t TaskStatus;
TaskHandle = xTaskGetHandle("Task1 Task");
vTaskGetInfo((TaskHandle_t ) TaskHandle,
(TaskStatus_t* ) &TaskStatus,
(BaseType_t ) pdTRUE,
(eTaskState ) eInvalid);
printf("TaskName: %s\r\n", TaskStatus.pcTaskName);
printf("TaskNumber: %d\r\n", (int)TaskStatus.xTaskNumber);
printf("TaskState: %d\r\n", TaskStatus.eCurrentState);
printf("TaskCurrentPriority: %d\r\n", (int)TaskStatus.uxCurrentPriority);
printf("TaskBasePriority: %d\r\n", (int)TaskStatus.uxBasePriority);
printf("TaskStackBase: %#x\r\n", (int)TaskStatus.pxStackBase);
printf("TaskStackHighWaterMark: %d\r\n", TaskStatus.usStackHighWaterMark);
/************ vTaskGetInfo() **************
TaskName: Task1 Task
TaskNumber: 4
TaskState: 2
TaskCurrentPriority: 2
TaskBasePriority: 2
TaskStackBase: 0x200018c8
TaskStackHighWaterMark: 102
*******************************************/uxTaskGetSystemState() captures a snapshot of every FreeRTOS task and stores the results in an array of TaskStatus_t structures. Each structure contains information such as the task handle, name, state, priority, runtime counter, and stack high-water mark. The array must be large enough to hold one entry per task, typically using uxTaskGetNumberOfTasks() to determine its required size. The optional pulTotalRunTime parameter receives the system’s total runtime when runtime statistics are enabled. The function returns the number of structures populated, or 0 if the array is too small. It is mainly intended for debugging because it suspends the scheduler while collecting the information.
#define configUSE_TRACE_FACILITY 1
UBaseType_t uxTaskGetSystemState(
TaskStatus_t * const pxTaskStatusArray,
const UBaseType_t uxArraySize,
uint32_t * const pulTotalRunTime
)
// ---------------------- Example ----------------------
printf("/******** uxTaskGetSystemState() **********/\r\n");
uint32_t TotalRunTime;
UBaseType_t ArraySize, x;
TaskStatus_t *StatusArray;
ArraySize = uxTaskGetNumberOfTasks();
StatusArray = pvPortMalloc(ArraySize*sizeof(TaskStatus_t));
if(StatusArray != NULL)
{
ArraySize = uxTaskGetSystemState((TaskStatus_t* ) StatusArray,
(UBaseType_t ) ArraySize,
(uint32_t* ) &TotalRunTime);
printf("TaskName\t\tPriority\t\tTaskNumber\t\t\r\n");
for(x = 0; x < ArraySize; x++)
{
printf("%s\t\t%d\t\t\t%d\t\t\t\r\n",
StatusArray[x].pcTaskName,
(int)StatusArray[x].uxCurrentPriority,
(int)StatusArray[x].xTaskNumber);
}
}
vPortFree(StatusArray);
/******** uxTaskGetSystemState() **********
TaskName Priority TaskNumber
Query Task 3 5
Start Task 1 1
IDLE 0 2
Task1 Task 2 4
Tmr Svc 55 3
*******************************************/eTaskGetState() returns the current state of the task identified by xTask as an eTaskState value. Possible states include eRunning, eReady, eBlocked, eSuspended, eDeleted, and eInvalid. The task handle must be valid.
#define INCLUDE_eTaskGetState 1
eTaskState eTaskGetState(TaskHandle_t xTask)
// ---------------------- Example ----------------------
eTaskState xState = eTaskGetState(xTaskHandle);
if (xState == eBlocked)
{
/* The task was blocked when its state was checked. */
}
printf("/************ eTaskGetState() *************/\r\n");
eTaskState TaskState;
char TaskInfo[10];
TaskHandle = xTaskGetHandle("Query Task");
TaskState = eTaskGetState(TaskHandle);
memset(TaskInfo, 0, 10);
switch((int)TaskState)
{
case 0:
sprintf(TaskInfo, "Running");
break;
case 1:
sprintf(TaskInfo, "Ready");
break;
case 2:
sprintf(TaskInfo, "Suspend");
break;
case 3:
sprintf(TaskInfo, "Delete");
break;
case 4:
sprintf(TaskInfo, "Invalid");
break;
}
printf("TaskState: %d, TaskStatus: %s\r\n", TaskState, TaskInfo);
/************ eTaskGetState() *************/
TaskState: 0, TaskStatus: RunningxTaskGetSchedulerState() returns the current operating state of the FreeRTOS scheduler. It is useful for diagnostic code or library functions that need to check whether the scheduler is available before calling scheduler-dependent APIs.
- taskSCHEDULER_NOT_STARTED: the scheduler has not yet been started
- taskSCHEDULER_RUNNING: normal task scheduling is active
- taskSCHEDULER_SUSPENDED: after vTaskSuspendAll() has been called and before xTaskResumeAll() restores scheduling
#define INCLUDE_xTaskGetSchedulerState 1
BaseType_t xTaskGetSchedulerState(void)
// ---------------------- Example ----------------------
BaseType_t xState = xTaskGetSchedulerState();
if (xState == taskSCHEDULER_RUNNING)
{
/* The scheduler is running normally. */
}vTaskGetRunTimeStats() generates a human-readable table showing how much processor time each FreeRTOS task has spent in the Running state. For each task, it reports the task name, accumulated runtime-counter value, and percentage of total processor time. The function writes the formatted text into the caller-provided buffer, which must be large enough to hold the complete report approximately 40 bytes per task is commonly recommended.
#define configUSE_TRACE_FACILITY 1
#define configGENERATE_RUN_TIME_STATS 1
#define configUSE_STATS_FORMATTING_FUNCTIONS 1
#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() ConfigureTimeForRunTimeStats()
#define portGET_RUN_TIME_COUNTER_VALUE() FreeRTOSRunTimeTicks
void vTaskGetRunTimeStats(char * pcWriteBuffer)
// ---------------------- Example ----------------------
volatile unsigned long long FreeRTOSRunTimeTicks;
/* vTaskStartScheduler()
* └── portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()
* └── ConfigureTimeForRunTimeStats()
* └── TIM3_init()
*/
void ConfigureTimeForRunTimeStats(void) {
FreeRTOSRunTimeTicks = 0;
// void TIM3_init(uint16_t arr, uint16_t psc,
// uint32_t PreemptPriority)
TIM3_init(50-1, 84-1, 1);
}
void TIM3_IRQHandler(void) {
if (__HAL_TIM_GET_FLAG(&htim3, TIM_FLAG_UPDATE) == SET)
{
FreeRTOSRunTimeTicks++;
}
__HAL_TIM_CLEAR_IT(&htim3, TIM_IT_UPDATE);
}
char RunTimeInfo[500];
void vRunTimeStatsTask(void *pvParameters)
{
while(1) {
memset(RunTimeInfo, 0, 500);
vTaskGetRunTimeStats(RunTimeInfo);
printf("Task Name\tRun Time\tRun Time Percentage\r\n");
printf("%s\r\n", RunTimeInfo);
vTaskDelay(_2000ms);
}
}
/*************************************************
Task Name Run Time Run Time Percentage
Runtime Stats T 1077 <1%
IDLE 159960 99%
Task1 Task 0 <1%
Task2 Task 0 <1%
Tmr Svc 0 <1%
**************************************************/vTaskList() generates a human-readable table containing information about every task managed by FreeRTOS. Each row shows the task name, current state, priority, stack high-water mark, and unique task number. State characters include X for Running, R for Ready, B for Blocked, S for Suspended, and D for Deleted. The formatted table is written into the buffer supplied through pcWriteBuffer, which must be large enough approximately 40 bytes per task is a useful estimate.
#define configUSE_TRACE_FACILITY 1
#define configUSE_STATS_FORMATTING_FUNCTIONS 1
void vTaskList(char *pcWriteBuffer);
// ---------------------- Example ----------------------
char pcTaskList[512];
vTaskList(pcTaskList);
printf("Name\tState\tPriority\tStack\tNumber\r\n");
printf("%s\r\n", pcTaskList);
/*************** vTaskList() **************/
Name State Priority Stack Number
Query Task X 3 118 5
Start Task R 1 212 1
IDLE R 0 118 2
Task1 Task B 2 102 4
Tmr Svc B 55 215 3uxTaskGetStackHighWaterMark() returns the smallest amount of unused stack that has remained for a task since the task started running. This value is the task’s stack high-water mark, not its current free stack space. A large value indicates that the task has plenty of unused stack, while a value close to 0 indicates that the task may be close to a stack overflow. Passing NULL checks the calling task. The result is measured in stack words, on an STM32 with 32-bit StackType_t, one word normally equals four bytes.
#define INCLUDE_uxTaskGetStackHighWaterMark 1
UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask)
// ---------------------- Example ----------------------
UBaseType_t uxRemainingWords;
uint32_t ulRemainingBytes;
uxRemainingWords = uxTaskGetStackHighWaterMark(NULL);
ulRemainingBytes = uxRemainingWords * sizeof(StackType_t);
printf("Minimum unused stack: %lu words (%lu bytes)\r\n",
(unsigned long)uxRemainingWords,
(unsigned long)ulRemainingBytes);Back to top of the page