What will be the output timing behavior of the following FreeRTOS task code snippet?
void vTaskFunction(void *pvParameters) {
for (;;) {
// Task code here
vTaskDelay(pdMS_TO_TICKS(1000));
// Print or toggle an LED
}
}Assuming the tick rate is 1ms, how often does the task unblock?
void vTaskFunction(void *pvParameters) {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(1000));
// action
}
}Remember that vTaskDelay() delays the task for the specified tick count.
The function vTaskDelay(pdMS_TO_TICKS(1000)) causes the task to enter the Blocked state for 1000 ticks. Since the tick rate is 1ms, this equals 1000 milliseconds or 1 second. After this delay, the task unblocks and runs again.
Consider a FreeRTOS task that performs some work taking 200ms and then calls vTaskDelay(pdMS_TO_TICKS(1000)). How often will the task run?
void vTaskFunction(void *pvParameters) {
for (;;) {
// Work taking 200ms
vTaskDelay(pdMS_TO_TICKS(1000));
}
}Think about how vTaskDelay() affects the task after the work is done.
The task does 200ms of work, then calls vTaskDelay() for 1000ms. So the total cycle time is 200ms + 1000ms = 1200ms.
A developer writes this FreeRTOS task to run every 1000ms:
void vTaskFunction(void *pvParameters) {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(1000));
// Do work
}
}But the task execution drifts over time, running later and later. Why?
Consider when the delay starts counting relative to the work done.
vTaskDelay() delays the task for a fixed time starting from when it is called. Since the work is done before the delay, the total period is work time + delay time. This causes the task to drift later each cycle.
Which code snippet correctly implements a task that runs exactly every 1000ms without drift?
Use the function designed for fixed periodic delays.
vTaskDelayUntil() uses a reference time to ensure the task runs at fixed intervals, preventing drift. Option B correctly initializes xLastWakeTime and uses vTaskDelayUntil().
Why might vTaskDelay() be unsuitable for tasks that require precise periodic execution?
Think about how the delay start time relates to task execution time.
vTaskDelay() delays the task for a fixed time starting from the call moment. If the task execution time varies, the delay accumulates causing drift. For precise periodic timing, vTaskDelayUntil() is preferred.