Delay functions in FreeRTOS

Delay functions in FreeRTOS

Last time, I talked about the RTOS task state. This time, I'd like to talk about one of the task controls, delay. There are three delay functions are provided; vTaskDelay(), vTaskDelayUntil(), xTaskDelayUntil(). However, to use these functions, you need to define INCLUDE_vTaskDelay, INCLUDE_vTaskDelayUntil and INCLUDE_xTaskDelayUntil as 1 in FreeRTOSConfig.h.

vTaskDelay() is a classic delay function that blocks the task by a given number of RTOS ticks. vTaskDelay() specifies a wake time relative to the time at which the function is called.

Example usage:


 void vTaskFunction( void * pvParameters )
 {
 /* Block for 500ms. */
 const TickType_t xDelay = 500 / portTICK_PERIOD_MS;

     for( ;; )
     {
         /* Simply toggle the LED every 500ms, blocking between each toggle. */
         vToggleLED();
         vTaskDelay( xDelay );
     }
}

vTaskDelayUntil() specifies the absolute time at which it wishes to unblock. To do that, it takes another pointer variable parameter which holds the time at which the task was last unblocked. The second parameter is the same as vTaskDelay()'s parameter. The return type is void.

Example usage:

 // Perform an action every 10 ticks.
 void vTaskFunction( void * pvParameters )
 {
 TickType_t xLastWakeTime;
 const TickType_t xFrequency = 10;

     // Initialise the xLastWakeTime variable with the current time.
     xLastWakeTime = xTaskGetTickCount();

     for( ;; )
     {
         // Wait for the next cycle.
         vTaskDelayUntil( &xLastWakeTime, xFrequency );

         // Perform action here.
     }
 }

xTaskDelayUntil() will cause a task to block for the specified number of ticks from the time specified in the pxPreviousWakeTime parameter. It returns a value that can be used to check whether the task was delayed.

Example usage:

// Perform an action every 10 ticks.
void vTaskFunction( void * pvParameters )
{
TickType_t xLastWakeTime;
const TickType_t xFrequency = 10;
BaseType_t xWasDelayed;

    // Initialise the xLastWakeTime variable with the current time.
    xLastWakeTime = xTaskGetTickCount ();
    for( ;; )
    {
        // Wait for the next cycle.
        xWasDelayed = xTaskDelayUntil( &xLastWakeTime, xFrequency );

        // Perform action here. xWasDelayed value can be used to determine
        // whether a deadline was missed if the code here took too long.
    }
}

In general, xTaskDelayUntil() is useful when a task needs to perform some action periodically at a fixed interval, as it allows the task to be unblocked at precise intervals based on the tick count. vTaskDelayUntil(), on the other hand, is useful when a task simply needs to delay until a specific time has been reached, without needing to calculate or return any values.

More details can be found here.

Did you find this article valuable?

Support Hyunwoo Choi by becoming a sponsor. Any amount is appreciated!