提示:INCLUDE_vTaskDelayUntil以及INCLUDE_xTaskDelayUntil不可同时定义,具体问题在FreeRTOS.h文件中。
1.void vTaskDelay( const TickType_t xTicksToDelay );
首先,该函数必须预先在FreeRTOSConfig.h中将INCLUDE_vTaskDelay定义为1,该函数才可用。
vTaskDelay() 会指定任务想要取消阻塞的时间,该时间是相对于 vTaskDelay() 被调用的时间。 例如,如果指定 时间块为 100 个 tick,那么在调用 vTaskDelay() 100 个 tick 后任务会取消阻塞。 vTaskDelay() 并不会因此提供一种 控制周期性任务频率的好办法,因为途径代码的路径以及其他任务和中断活动将影响 vTaskDelay() 被调用的频率,进而会影响下一个任务执行的时间。
示例代码:
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 );
}
}
2.**void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, **
const TickType_t xTimeIncrement );
首先,该函数必须预先在FreeRTOSConfig.h中将INCLUDE_vTaskDelayUntil定义为1,该函数才可用。
此函数与 vTaskDelay() 在一个重要的方面有所不同: vTaskDelay() 会指定 任务想要取消阻塞的时间,该时间是相对于 vTaskDelay() 被调用的时间, 而 vTaskDelayUntil() 会指定任务希望取消阻塞的绝对时间。
应注意,如果 vTaskDelayUntil() 被用于指定已过去的唤醒时间, 该函数将立即返回(不阻塞)。 因此,使用 vTaskDelayUntil() 定期执行的任务,在周期性执行因任何原因停止 (例如,任务被暂停),而导致任务错过一个或多个周期性执行时, 必须重新计算其所需的唤醒 时间。 这可以通过检查由引用传递的变量来发现, 该变量是针对当前 tick 计数的 pxPreviousWakeTime 参数。 但是,这在大多数使用场景下 并非必要。
当调用了 vTaskSuspendAll() 暂停 RTOS 调度器时,不得调用此函数。
示例代码:
// 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.
}
}
3.BaseType_t xTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );
首先,该函数必须预先在FreeRTOSConfig.h中将INCLUDE_xTaskDelayUntil定义为1,该函数才可用。
该函数与vTaskDelayUntil()函数不同的地方在于,该函数返回值为BaseType_t类型(long类型),而vTaskDelayUntil()函数返回值为void类型。
除此之外,其它方面与vTaskDelayUntil()函数无异。
示例代码:
// 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.
}
}