STM32使用systick实现精确延时
扫描二维码
随时随地手机看文章
SYSTICK寄存器初始化
void SysTick_Configuration(void)
{
if (SysTick_Config(SystemCoreClock / 100))
{
while (1);
}
NVIC_SetPriority(SysTick_IRQn, 0x0);
}
SysTick_Config默认时钟为SysTick_CLKSource_HCLK,所以在这之前使用SysTick_CLKSourceConfig()选择系统时钟不会改变systick的时钟
static __INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if (ticks > SysTick_LOAD_RELOAD_Msk)return (1);
SysTick->LOAD= (ticks & SysTick_LOAD_RELOAD_Msk) - 1;
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);
SysTick->VAL= 0;
SysTick->CTRL=SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk|
SysTick_CTRL_ENABLE_Msk;
return (0);
}
systick中断服务程序
void SysTick_Handler(void)
{
systime ++;
}
延时程序
void delay_ms(unsigned int ms)
{
unsigned int temp;
temp = systime;
while((systime - temp) < ms);
}
void SysTick_CLKSourceConfig(uint32_t SysTick_CLKSource)在misc.c文件中定义
static __INLINE uint32_t SysTick_Config(uint32_t ticks)在core_cm3.h中定义