freertos中prvSampleTimeNow函数
时间: 2023-07-08 14:48:08 浏览: 320
在FreeRTOS中,prvSampleTimeNow函数用于获取当前系统时间。它使用了FreeRTOS的时钟节拍计数器来计算当前时间。具体实现如下:
```
static TickType_t prvSampleTimeNow( BaseType_t xTimeInTicks )
{
TickType_t xTime;
const TickType_t xMaxBusyTime = pdMS_TO_TICKS( 2UL );
/* This is called from a critical section so is itself automatically
protected from interrupts. */
/* Wait until xTickCount is not being updated. */
while( xTickCount != xTickCountUpdated )
{
taskYIELD();
}
/* Obtain the tick count value as it was when xTickCount was last updated.
This cannot be changed by an interrupt. */
xTime = xTickCount;
/* Is the task requesting the time now or after the tick count has
incremented? */
if( xTimeInTicks != pdFALSE )
{
/* The time is being requested after the tick count has incremented,
but before the scheduler has executed to process the increment. In this
case xTime has already been incremented, but the tick interrupt that
caused the increment has not yet executed. As the tick interrupt will
update xTickCountUpdated when it does execute, but has not yet done so,
we need to determine if the tick interrupt will execute before the
scheduler processes the request or after. If it is before then we must
return xTime + 1, otherwise we can return xTime. */
if( xTickCountUpdated == xTime )
{
xTime++;
}
}
/* Return the time, ensuring it is not too far ahead of the tick count
obtained above. */
if( ( xTickCountUpdated - xTime ) > xMaxBusyTime )
{
xTime = xTickCountUpdated - xMaxBusyTime;
}
return xTime;
}
```
该函数首先等待xTickCount不再被更新,然后获取xTickCount的值作为当前时间。如果xTimeInTicks参数为pdTRUE,则表示当前时间是在一个tick计数器增加但调度程序还未执行的时间点。在这种情况下,prvSampleTimeNow函数需要判断tick中断是否在调度程序处理请求之前或之后执行。如果在之前执行,当前时间需要加1。如果tick中断在处理请求之后执行,则返回xTime。
最后,该函数确保返回的时间不会超过xTickCountUpdated减去一个最大繁忙时间的值。
阅读全文