最近要在stm32f103上写一个pwm编解码程序,要对pwm脉宽进行精确计时,无意间发现使用HAL库自带延时函数产生的延时存在+1ms的误差,即:
HAL_Delay(x);
实际延时时间为(x+1)ms
比如在主循环中加入程序:
HAL_Delay(1);
HAL_GPIO_TogglePin(LED_GPIO_Port, GPIO_PIN_13);
烧录程序后使用示波器观察方波波形:
可以看到方波周期为4ms,相邻跳变之间的时间差为2ms,存在+1ms的误差
实际使用中如果延时时间为几百ms或几s,1ms的误差并没有太大影响,而遇到延时时间非常短的情况则会产生巨大影响。
分析HAL_Delay函数定义
观察HAL_Delay函数在stm32f1xx_hal.c中的定义:
/**
* @brief This function provides minimum 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(uint32_t Delay)