用过STM32CUBEMX的童鞋们都知道,代码生成的时候默认HAL_Delay延时单位为ms,当程序中要用到us延时的时候该怎么办呢!
最终评估下来,感觉原子的思路比较靠谱,不带OS的设计理念是搞清楚SYSTICK的RELOAD寄存器的数值代表什么,代码生成时默认为47999,也就是说
定时器从47999减1减到0的时候,时间过了1000us,换算后得出数值从47减到1的时候时间过了1us.
void HAL_Delay_us(__IO uint32_t delay_us)
{
uint32_t first_value = 0;
uint32_t current_value = 0;
uint32_t reload = SysTick ->LOAD;
uint32_t nus_number = delay_us * ((reload + 1) / 1000);
uint32_t change_number = 0;
first_value = SysTick ->VAL;
while(1)
{
current_value = SysTick ->VAL;
if(current_value != first_value)
{
if(current_value < first_value)
{
change_number += first_value - current_value;
//change_number = first_value - current_value + change_number;
}
else
{
change_number += reload - current_value + first_value;
}
first_value = current_value;
if(change_number >= nus_number)
{
break;
}
}
}
}
|