stm32定时器资源虽然丰富,但是在一些项目中,我们任然希望不借助传统定时器实现精确延时,这样在面对一些对定时器资源需求多的项目我们剩下资源用来做该做事情。STM32用的是ARM Cortex-Mx系列的内核,该核心具有一个滴答时钟,这个滴答时钟大意就是在配置完时钟源和使能以后能进入到中断处理函数中。是为了方便一些操作系统,诸如ucOS等系统,的移植,作为任务调用的同步节拍。以下是在stm32f103上利用SysTick来实现精确延时的步骤。
第一步:配置时钟源
- void SysTick_Configuration(void)
- {
- /* Setup SysTick Timer for 1 uS interrupts */
- /* SystemCoreClock isdefined in ¡°system_stm32f10x.h¡± and equal to HCLK frequency */
- if (SysTick_Config(72))
- {
- /* Capture error */
- while (1);
- }
- NVIC_SetPriority (SysTick_IRQn, 3); // the highest priority */
- }
void SysTick_Configuration(void)
{
/* Setup SysTick Timer for 1 uS interrupts */
/* SystemCoreClock isdefined in ¡°system_stm32f10x.h¡± and equal to HCLK frequency */
if (SysTick_Config(72))
{
/* Capture error */
while (1);
}
NVIC_SetPriority (SysTick_IRQn, 3); // the highest priority */
}
第二步:写中断处理函数
- void SysTick_Handler(void)
- {
- if(TimingDelay != 0)
- TimingDelay --;
- }
void SysTick_Handler(void)
{
if(TimingDelay != 0)
TimingDelay --;
}
第三步:写延时函数
- volatile unsigned int TimingDelay = 0;
- void Delay_mS(unsigned int n)
- {
- TimingDelay = n * 1000;
- while(TimingDelay !=0);
- }
- void Delay_uS(unsigned int n)
- {
- TimingDelay = n;
- while(TimingDelay !=0);
- }
volatile unsigned int TimingDelay = 0;
void Delay_mS(unsigned int n)
{
TimingDelay = n * 1000;
while(TimingDelay !=0);
}
void Delay_uS(unsigned int n)
{
TimingDelay = n;
while(TimingDelay !=0);
}
完成