vTaskDelay() helps pause a task for a set time. This makes tasks run regularly, like a clock ticking.
0
0
vTaskDelay() for periodic tasks in FreeRTOS
Introduction
When you want a task to run every 1 second to read a sensor.
To blink an LED on and off at a steady rate.
When you need to check a button press every 100 milliseconds.
To send data over a network at fixed intervals.
When you want to save power by pausing a task between actions.
Syntax
FreeRTOS
void vTaskDelay(const TickType_t xTicksToDelay);
xTicksToDelay is the number of tick periods to delay the task.
The tick period depends on your FreeRTOS configuration (usually 1ms or 10ms).
Examples
Delays the task for 1000 milliseconds (1 second).
FreeRTOS
vTaskDelay(1000 / portTICK_PERIOD_MS);Delays the task for 500 milliseconds using a helper macro.
FreeRTOS
vTaskDelay(pdMS_TO_TICKS(500));Sample Program
This program creates a task that prints a message every 1 second using vTaskDelay(). The delay makes the task run periodically.
FreeRTOS
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void vPeriodicTask(void *pvParameters) { const TickType_t xDelay = pdMS_TO_TICKS(1000); // 1 second delay for (;;) { printf("Task running at regular interval\n"); vTaskDelay(xDelay); // Delay for 1 second } } int main(void) { xTaskCreate(vPeriodicTask, "PeriodicTask", 1000, NULL, 1, NULL); vTaskStartScheduler(); for(;;); // Should never reach here return 0; }
OutputSuccess
Important Notes
vTaskDelay() delays from the time it is called, so small variations can add up over time.
For precise periodic timing, consider using vTaskDelayUntil() instead.
Always convert milliseconds to ticks using pdMS_TO_TICKS() for portability.
Summary
vTaskDelay() pauses a task for a set number of ticks.
Use it to make tasks run at regular intervals.
Convert milliseconds to ticks with pdMS_TO_TICKS() for accuracy.