SysTick定时器被捆绑在NVIC中,用于产生SYSTICK异常(异常号:15)。
系统定时器一般用于操作系统,用于产生时基,维持操作系统的心跳。
系统定时器是一个 24bit 的向下递减的计数器,计数器每计数一次的时间为 1/SYSCLK,一般我们设置
系统时钟 SYSCLK 等于 72M。当重装载数值寄存器的值递减到 0 的时候,系统定时器就产
生一次中断,以此循环往复。
SysTick 寄存器
寄存器 描述:
CTRL SysTick 控制和状态寄存器
LOAD SysTick 重装载值寄存器
VAL SysTick 当前值寄存器
CALIB SysTick 校准值寄存器
#include "bsp_SysTick.h"
unsigned int TimingDelay;
void SysTick_Configuration(void)
{
while(SysTick_Config(72));
/* 使能完毕之后,在初始化阶段,先把定时器关闭,就是把CTRL寄存器的第0位清零 */
SysTick->CTRL &= ~(1<<0);
//(与操作置1,然后把1左移0位取反) 暂时初始化后先关闭定时器,使用前开启
}
void Delay_us(unsigned int n)
{
TimingDelay = n; // 全局变量,在“stm32f10x_it.c”中的SysTick_Handler所使用
SysTick->CTRL |= (1<<0); //开启Sys_Tick
while(TimingDelay); // 等待timingDelay=0,跳出循环
SysTick->CTRL &= ~(1<<0);
}
在core_cm3.c中的SysTick_confige函数
/* ################################## SysTick function
############################################ */
#if (!defined (__Vendor_SysTickConfig)) || (__Vendor_SysTickConfig == 0)
/**
* @brief Initialize and start the SysTick counter and its interrupt.
*
* @param ticks number of ticks between two interrupts
* @return 1 = failed, 0 = successful
*
* Initialise the system tick timer and its interrupt and start the
* system tick timer / counter in free running mode to generate
* periodical interrupts.
*/
static __INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if (ticks > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */
SysTick->LOAD = (ticks & SysTick_LOAD_RELOAD_Msk) - 1; /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Cortex-M0 System Interrupts */
SysTick->VAL = 0; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0); /* Function successful */
}
#endif
在“stm32f10x_it.c”中的SysTick_Handler函数
void SysTick_Handler(void)
{
if(TimingDelay != 0)
TimingDelay--;
}