STM32F407 tick timer

Introduces the STM32F407 tick timer configuration method and usage method, and encapsulates the delay function to obtain accurate time.

[1] The chapter introducing the tick timer

Chapter 10 of the STM32F407 Reference Manual describes the calibration values ​​for the tick timer.

img

The M4 Authoritative Guide introduces the chapter of the tick timer, and the introduction in the M3 Authoritative Guide is the same as that in the M4 Authoritative Guide.

img

img

【2】Sample code of tick timer

Add the tick timer code in the sys.c file

#include "sys.h"
/*
函数功能:设置NVIC中断控制器优先级
函数形参:
		IRQn_Type IRQn:中断线
		uint32_t PreemptPriority:抢占优先级
		uint32_t SubPriority:次优先级
*/
void SetNVICPriorityGrouping(IRQn_Type IRQn,uint32_t PreemptPriority, uint32_t SubPriority)
{
    
    
	 uint32_t Priority;
	 NVIC_SetPriorityGrouping(NVIC_PriorityGroup_2); //设置优先级分组,每个工程只能设置一次
   Priority=NVIC_EncodePriority(NVIC_PriorityGroup_2,PreemptPriority,SubPriority); //编码优先级
   NVIC_SetPriority(IRQn,Priority); //设置优先级
   NVIC_EnableIRQ(IRQn);
}

/*
函数功能:滴答时钟初始化配置
注意:SysTick->LOAD是一个24位的寄存器,单次最大延时时间为894.7848ms
说明:18750是滴答定时器的校准值。当重载值为18750时,滴答定时器刚好产生1ms的中断
*/
void SysTickInit(void)
{
    
    	
	SysTick->CTRL&=~(1<<2); //选择外部时钟源	
	SysTick->CTRL|=1<<1;    //开启中断
	SysTick->LOAD=18750*800;//重装载寄存器,最大24位,最大值:16777215
	SysTick->VAL=0; 			  //清除CNT计数值
	SysTick->CTRL|=1<<0;    //SysTick 定时器的使能位
}

/*
函数功能:滴答时钟中断服务函数
*/
void SysTick_Handler(void)
{
    
    
	  LED0=!LED0;
		LED1=!LED1;
}

[3] Write a delay function using a tick timer

Add the following code to the delay.c file

#include "delay.h"

/*
功能  :毫秒级别的延时函数
参数  :填入延时的时间
返回值:无
说  明:频率在168MHZ情况下使用
*/
void DelayMs_168M(u32 time)
{
    
    
	u32 a,b,c;
	for(a=0;a<time;a++)
		for(b=0;b<100;b++)
			for(c=0;c<450;c++);
}


/*
功能  :微秒级别的延时函数
参数  :填入延时的时间
返回值:无
说  明:频率在168MHZ情况下使用
*/
void DelayUs_168M(u32 time)
{
    
    
	u32 k;
	while(time--)
	{
    
    
		k=40;
		while(k--);
	}
}

/*
函数功能:延时函数初始化
*/
void DelayInit(void)
{
    
    
	SysTick->CTRL&=~(1<<2);  //选择外部时钟源	
	SysTick->CTRL&=~(1<<1);  //关闭中断
}


/*
函数功能:延时毫秒的函数
函数参数:毫秒的时间
*/
void DelayMs(u32 time)
{
    
    
	u32 stat;
	SysTick->LOAD=18750*time; //重装载寄存器,最大24位,最大值:16777215
	SysTick->VAL=0; 			   //清除CNT计数值
	SysTick->CTRL|=1<<0;     //SysTick 定时器的使能位
	do
	{
    
    
			stat=SysTick->CTRL;  //获取状态位
	}while((!(stat&1<<16))&&(stat&1<<0));
	SysTick->CTRL=0x0; 
}


/*
函数功能:延时微秒的函数
函数参数:毫秒的时间
*/
void DelayUs(u32 time)
{
    
    
	u32 stat;
	SysTick->LOAD=18.750*time; //重装载寄存器,最大24位,最大值:16777215
	SysTick->VAL=0; 			   //清除CNT计数值
	SysTick->CTRL|=1<<0;     //SysTick 定时器的使能位
	do
	{
    
    
			stat=SysTick->CTRL;  //获取状态位
	}while((!(stat&1<<16))&&(stat&1<<0));
	SysTick->CTRL=0x0; 
}


Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/131458233