使用库3.2.0时,自己的延时函数会造成芯片跑飞,串口漏打印。我测试以前库1.21时,发现没问题,具体原因不知道为什么。库2.2.0也会造成这样的问题。下面给出了嘀嗒延时初始化和毫秒延时函数,我在STM32F1的HAL库使用也没问题。
void delay_init(void)
{
SysTick->LOAD = (uint32_t)(SystemCoreClock / 1000); // 设置重装载值1ms
NVIC_SetPriority(SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); // 设置中断
SysTick->VAL = 0UL; // 计数值清零
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; // 选择系统时钟,使能中断、时钟
}
void delay_ms(uint32_t u32Cnt)
{
uint32_t ticks;
uint32_t told, tnow, tcnt = 0;
uint32_t reload = SysTick->LOAD; // 读取重装载值
ticks = u32Cnt * (SystemCoreClock / 1000); // 转换成1ms基本单位的节拍
told = SysTick->VAL;
while (1)
{
tnow = SysTick->VAL;
if (tnow != told)
{
if (tnow < told)
tcnt += told - tnow;
else
tcnt += reload - tnow + told;
told = tnow;
if(tcnt >1000000)
{
continue;
}
if (tcnt >= ticks)
break;
}
}
}
|