在STM32中有多个定时工具,systick是其中一个与众不同的,称为滴答时钟。
它的时钟源是系统时钟,一般系统初始化SystemInit后为72Mhz
四个寄存器:STK_CSR控制寄存器,STK_LOAD重载寄存器,
思路:将Systick设定为递减计数器,设定重载初值并使能它,
当每到一个时钟周期时自动减一,减到为零时触发中断。
因为用系统时钟作为时钟源是72Mhz,所以设置计数值为72000时,每一次重载的时间为72K*1/72M=1ms,然后循环1000次,则实现定时1s。
流程:
1、设置Systick重载值(SysTick_SetReload)
2、设定NVIC中断优先级(NVIC_SystemHandlerPriorityCon
3、设置Systick时钟源(SysTick_CLKSourceConfig)
4、清零Systick当前值寄存器(SysTick->VAL=0x00)
5、使能Systick中断(SysTick_ITConfig)
6、使能Systick计数器(SysTick_CounterCmd)
7、中断服务程序(SysTickHandler)
可以参考ST固件库的example中的注释流程:
1. The SysTick_Config() function is a CMSIS function which configure:
这部分即是流程。
2. You can change the SysTick Clock source to be HCLK_Div8 by calling the
3. You can change the SysTick IRQ priority by calling the
4. To adjust the SysTick time base, use the following formula:
使用systick查询延时nus的设计思路:
1.计算出产生1us 需要多少个时钟周期 fac_us;
2.计算出RELOAD寄存器的值
(也就是产生相应延时所需要的时钟周期数);
RELOAD=fac_us * nus
3.开启计数;
4.循环检测计数到0的标志位;
5. 清空计数器,关闭定时器;
u32 temp;
SysTick->LOAD=nus*fac_us; //时间加载
SysTick->VAL=0x00; //清空计数器
SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //开始倒数
do
{
temp=SysTick->CTRL;
}
while(temp&0x01&&!(temp&(1<<16)));//等待时间到达
SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //关闭计数器
SysTick->VAL =0X00; //清空计数器