0
0
FreeRTOSprogramming~5 mins

vTaskDelayUntil() for precise timing in FreeRTOS

Choose your learning style9 modes available
Introduction

vTaskDelayUntil() helps tasks run at exact time intervals. It keeps timing steady even if the task takes different amounts of time to run.

You want a task to run every 100 milliseconds exactly.
You need to blink an LED at a steady rate without drift.
You want to sample a sensor at fixed time intervals.
You want to avoid timing errors building up over many cycles.
Syntax
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.

Examples
This example runs the task every 100 milliseconds precisely.
FreeRTOS
TickType_t xLastWakeTime;
xLastWakeTime = xTaskGetTickCount();

for(;;) {
    // Task code here
    vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(100));
}
Delays the task to run every 50 ticks from the last wake time.
FreeRTOS
TickType_t xLastWakeTime = xTaskGetTickCount();
vTaskDelayUntil(&xLastWakeTime, 50);
Sample Program

This program creates a task that prints the current tick count every 500 milliseconds exactly, using vTaskDelayUntil() for precise timing.

FreeRTOS
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.