在使用FreeRTOS应用程序项目创建STM32CubeMx时,可以使用两种方法引入延迟,即osDelay和HAL_Delay。
他们之间有什么区别,哪一个应该被优先考虑?
osDelay代码:
/*********************** Generic Wait Functions *******************************/
/**
* @brief Wait for Timeout (Time Delay)
* @param millisec time delay value
* @retval status code that indicates the execution status of the function.
*/
osStatus osDelay (uint32_t millisec)
{
#if INCLUDE_vTaskDelay
TickType_t ticks = millisec / portTICK_PERIOD_MS;
vTaskDelay(ticks ? ticks : 1); /* Minimum delay = 1 tick */
return osOK;
#else
(void) millisec;
return osErrorResource;
#endif
}
HAL_Delay代码:
/**
* @brief This function provides accurate delay (in milliseconds) based
* on variable incremented.
* @note In the default implementation , SysTick timer is the source of time base.
* It is used to generate interrupts at regular time intervals where uwTick
* is incremented.
* @note ThiS function is declared as __weak to be overwritten in case of other
* implementations in user file.
* @param Delay: specifies the delay time length, in milliseconds.
* @retval None
*/
__weak void HAL_Delay(__IO uint32_t Delay)
{
uint32_t tickstart = 0;
tickstart = HAL_GetTick();
while((HAL_GetTick() - tickstart) < Delay)
{
}
}
发布于 2022-10-31 09:56:04
答案很简单,如果您的项目是赤裸裸的(意味着没有os),您应该(或者可以)使用HAL_Delay。
“弱”符号实现使用如下代码。如果需要,可以声明自己的函数。
__weak void HAL_Delay(uint32_t Delay)
{
uint32_t tickstart = HAL_GetTick();
uint32_t wait = Delay;
/* Add a period to guaranty minimum wait */
if (wait < HAL_MAX_DELAY)
{
wait += (uint32_t)(uwTickFreq);
}
while((HAL_GetTick() - tickstart) < wait)
{
}
}
但是,如果您的项目有os (比如FreeRTOS或Keil)或其他任何操作系统,那么您应该使用osDelay。这是因为,正如@ as 4579所解释的,如果您在上面的函数定义中使用hal_delay,那么上面的函数就是一个阻塞调用,这意味着这只是一个消耗周期。使用osDelay,调用方任务将进入阻塞状态,当滴答声完成时,任务将再次处于就绪状态。所以在这里你不消耗任何周期。这是一个非阻塞的呼叫。
https://stackoverflow.com/questions/42276313
复制相似问题