STM32F407 basic timer use

Introduce the configuration method of the STM32F407 basic timer, respectively introduce the polling mode and the interrupt mode using the timer to complete the timing.

【1】Timer introduction

The timer-related chapters are in chapters 14, 15, 16, and 17 of the STM32F4xx reference manual.

img

img

img

img

img

【2】Basic timer configuration example

Add a Timer.c file, the code is as follows

#include "timer.h"
/*
函数功能:基本定时器7初始化配置
函数形参:
			psc  :预分频系数
			arr  :重载值
说明:定时器的视频频率为84MHZ ,是APB1时钟频率的2倍
*/
void Time7_InitConfig(u16 psc,u16 arr)
{
    
    
	  /*1. 开时钟*/
	  RCC->APB1ENR|=1<<5;    //开启定时器7的时钟
	  RCC->APB1RSTR|=1<<5;   //开启复位时钟  
	  RCC->APB1RSTR&=~(1<<5);//关闭  
	
	  /*2. 配置定时器的核心寄存器*/
	  TIM7->PSC=psc-1;     //预分频
	  /*计数器的时钟频率CK_CNT等于fCK_PSC/(PSC[15:0]+1)*/
	  TIM7->ARR=arr;       //重装载寄存器
	  TIM7->CR1|=1<<0;     //使能计数器
}

The code in the Main.c file is as follows

#include "stm32f4xx.h" // Device header
#include "led.h"
#include "delay.h"
#include "key.h"
#include "usart.h"
#include "sys.h"
#include "exti.h"
#include "timer.h"

int main(void)
{
    
    
		LED_Init();
		KEY_Init();
		USART1_Init(84,115200);
		KEY_EXTI_Init();
	  /*
			1/84000000得到定时器加的1的时间单位us
			1/84000得到定时器加的1的时间单位ms
			1/84得到定时器加的1的时间单位s   =0.0119047619047619
	  */	
		Time7_InitConfig(84,1000); //定时器7初始化
		/*
	    分频84,最终频率1HMZ  计数器CNT+1的时间是1us
		*/
	  while(1)
		{
    
    
			  if(TIM7->SR&1<<0)       //判断时间是否到达
				{
    
    
					  TIM7->SR&=~(1<<0);  //清除标志位
						LED0=!LED0;
						LED1=!LED1;
				}
		}
}


【3】Basic timer interrupt configuration example

Add the following code to the timer.c file

#include "timer.h"
/*
函数功能:基本定时器7初始化配置
函数形参:
  		psc  :预分频系数
  		arr  :重载值
说明:定时器的视频频率为84MHZ ,是APB1时钟频率的2倍
*/
void Time7_InitConfig(u16 psc,u16 arr)
{
    
    
    /*1. 开时钟*/
    RCC->APB1ENR|=1<<5;    //开启定时器7的时钟
    RCC->APB1RSTR|=1<<5;   //开启复位时钟  
    RCC->APB1RSTR&=~(1<<5);//关闭  
  	
    /*2. 配置定时器的核心寄存器*/
  	TIM7->DIER|=1<<0; //开启中断
    SetNVICPriorityGrouping(TIM7_IRQn,1,1);  //设置中断优先级
  	TIM7->PSC=psc-1;     //预分频
    /*计数器的时钟频率CK_CNT等于fCK_PSC/(PSC[15:0]+1)*/
    TIM7->ARR=arr;       //重装载寄存器
    TIM7->CR1|=1<<0;     //使能计数器
}

/*
函数功能:定时器中断服务函数
*/
void TIM7_IRQHandler(void)
{
    
    
  		TIM7->SR=0x0;
      LED0=!LED0;
  		LED1=!LED1;
}


Main.c file code is as follows

#include "stm32f4xx.h" // Device header
#include "led.h"
#include "delay.h"
#include "key.h"
#include "usart.h"
#include "sys.h"
#include "exti.h"
#include "timer.h"

int main(void)
{
    
    
		LED_Init();
		KEY_Init();
		USART1_Init(84,115200);
		KEY_EXTI_Init();
	  /*
			1/84000000得到定时器加的1的时间单位us
			1/84000得到定时器加的1的时间单位ms
			1/84得到定时器加的1的时间单位s   =0.0119047619047619
	  */	
		Time7_InitConfig(84,65000); //定时器7初始化
	
		/*
	    分频84,最终频率1HMZ  计数器CNT+1的时间是1us
		*/
	  while(1)
		{
    
    
			  
		}
}


Guess you like

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