STM32G474之TIM1能产生如下的中断:
1、捕获比较1个事件(Capture compare 1 event)
用来获取"捕获输入脉冲的时间",其次用来输出"比较输出波形";
2、捕获比较2个事件(Capture compare 2 event)
3、捕获比较3个事件(Capture compare 3 event)
4、捕获比较4个事件(Capture compare 4 event)
5、TIM更新事件(TIM Update event)
定时器计数器溢出,产生更新事件
6、TIM刹车输入事件(TIM Break input event)
当刹车信号到达时,则产生刹车输入事件
7、TIM刹车2输入事件TIM Break2 input event
8、TIM触发器检测事件(TIM Trigger detection event)
9、TIM换向事件(TIM commutation event)
10、TIM编码器索引事件(TIM Encoder index event)
11、TIM方向更改事件(TIM Direction change event)
12、TIM索引错误事件(TIM Index error event)
13、TIM转换错误事件(TIM Transition error event)
定时器的功能太多了,从简单入手,先学习定时器计数器溢出产生中断。这个功能是比较常用,所以先学习。
测试程序如下:
#include "Timer1.h"
#include "LED.h"
#include "stm32g4xx_hal.h"
void Timer1_Init(void);
void Timer1_Init(void)
{
TIM_HandleTypeDef htim1; //TIM1句柄
RCC_ClkInitTypeDef clkconfig;
uint32_t uwTimclock = 0;
uint32_t pFLatency;
uint32_t uwPrescalerValue = 0;
__HAL_RCC_TIM1_CLK_ENABLE();//使能"定时器1"的时钟,Enable TIM1 clock
HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);//Get clock configuration
uwTimclock = HAL_RCC_GetPCLK2Freq();
//读取PCLK2的时钟频率,Return the PCLK2 frequency
//若PCLK2的分频器值为1,则和SystemCoreClock的值相等
//uwTimclock=170000000Hz
uwPrescalerValue = (uint32_t) ((uwTimclock / 10000U) - 1U);
//uwPrescalerValue=17000
htim1.Instance = TIM1;
htim1.Init.Period = (1000000U / 1000U) - 1U;
//定时器周期999
htim1.Init.Prescaler = uwPrescalerValue;
//设置TIM1预分频器为uwPrescalerValue
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
//设置时钟分频系数,TIM1_CR1中的CKD[9:8]=00b,tDTS=ttim_ker_ck;
//溢出时间为(990+1)*1*17000/170000000/1=0.1秒
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.RepetitionCounter = 0;//重复计数(1-0)次,产生1次中断,比较重要
htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
//使能"自动重装载"
HAL_TIM_Base_Init(&htim1);
HAL_TIM_Base_Start_IT(&htim1);
HAL_NVIC_EnableIRQ(TIM1_UP_TIM16_IRQn);//使能TIM1产生中断
HAL_NVIC_SetPriority(TIM1_UP_TIM16_IRQn, 5, 0U);
//设置NVIC中断分组4:4位抢占优先级,0位响应优先级
//选择中断优先级组4,即抢占优先级为4位,取值为0~15,响应优先级组为0位,取值为0
//这里设置TIM1中断优先级为5
}
//TIM1"更新中断"和TIM16中断,共用一个中断源,TIM1每0.1秒中断一次
void TIM1_UP_TIM16_IRQHandler(void)
{
if( (TIM1->SR & TIM_FLAG_UPDATE) == TIM_FLAG_UPDATE)
{//读取TIM1状态寄存器TIMx_SR的bit0(UIF),UIF=1表示产生了"TIM1更新事件"
if( (TIM1->DIER & TIM_IT_UPDATE) == TIM_IT_UPDATE )
{//读取TIM1中断使能寄存器TIMx_DIER的bot0(UIE),查看UIE=1?
TIM1->SR = ~(TIM_IT_UPDATE);
LED1_Toggle(); //LED1引脚输出电平翻转
}
}
}
测试结果: