vTaskDelayUntil() helps tasks run at exact time intervals. It keeps timing steady even if the task takes different amounts of time to run.
vTaskDelayUntil() for precise timing in FreeRTOS
void vTaskDelayUntil(TickType_t *pxPreviousWakeTime, TickType_t xTimeIncrement);
pxPreviousWakeTime is a pointer to a variable holding the last wake time.
xTimeIncrement is how many ticks to wait between runs.
TickType_t xLastWakeTime; xLastWakeTime = xTaskGetTickCount(); for(;;) { // Task code here vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(100)); }
TickType_t xLastWakeTime = xTaskGetTickCount();
vTaskDelayUntil(&xLastWakeTime, 50);This program creates a task that prints the current tick count every 500 milliseconds exactly, using vTaskDelayUntil() for precise timing.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void vTaskFunction(void *pvParameters) { TickType_t xLastWakeTime; const TickType_t xFrequency = pdMS_TO_TICKS(500); // 500 ms xLastWakeTime = xTaskGetTickCount(); for(;;) { printf("Task running at tick: %lu\n", xTaskGetTickCount()); vTaskDelayUntil(&xLastWakeTime, xFrequency); } } int main(void) { xTaskCreate(vTaskFunction, "Task", 1000, NULL, 1, NULL); vTaskStartScheduler(); for(;;); return 0; }
Always initialize pxPreviousWakeTime with xTaskGetTickCount() before the first call.
vTaskDelayUntil() helps avoid drift that happens with simple delay functions.
If the task runs longer than the delay period, the next wake time will be in the past, so the task runs immediately to catch up.
vTaskDelayUntil() keeps task timing steady and precise.
Use it when you want tasks to run at fixed intervals without drift.
Initialize the last wake time before the loop and pass it by pointer each time.