1 通用定时器中断的初始化(Time2)
1.1 开启RCC的TimxCLK时钟,
由于Time2是由APB1总线的外设控制的
RccAPB1PeriphClockCmd(RCC_APB1PeriPh_TIM2,ENABLE);//使能APB1总线
1.2 选择时基单元时钟
选择时基单元内部时钟
TIM_InteralClockConfig(IIM2);//内部时钟驱动,单片机上电默认使用内部时钟
1.3 配置时基单元
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 0xF;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, & TIM_TimeBaseStructure);
1.3.1 TIM_TimeBaseStructure.TIM_ClockDivision
TIM_ClockDivision;//的作用:指定时钟分频;
指定时钟分频的原理
在定时器的外部输入引脚一般有一个滤波器,滤波器可以消除信号的抖动干扰;基本的工作原理,在固定的时钟频率F下进行采样,如果连续N个采样点为相同的电平,代表输入信号稳定;采样频率F一般有内部时钟而来或者由内部时钟加一个时钟分频来的,分频的参数由TIM_ClockDivision决定的;这个参数和外部输入时钟的滤波电容有关和时基单元无关;
1.3.2 TIM_TimeBaseStructure.TIM_CounterMode
计数模式的选择
/** @defgroup TIM_Counter_Mode
* @{
*/
#define TIM_CounterMode_Up ((uint16_t)0x0000)
#define TIM_CounterMode_Down ((uint16_t)0x0010)
#define TIM_CounterMode_CenterAligned1 ((uint16_t)0x0020)
#define TIM_CounterMode_CenterAligned2 ((uint16_t)0x0040)
#define TIM_CounterMode_CenterAligned3 ((uint16_t)0x0060)
#define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_CounterMode_Up) || \
((MODE) == TIM_CounterMode_Down) || \
((MODE) == TIM_CounterMode_CenterAligned1) || \
((MODE) == TIM_CounterMode_CenterAligned2) || \
((MODE) == TIM_CounterMode_CenterAligned3))
1.3.3 决定定时时间参数
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 10000-1;
TIM_TimeBaseStructure.TIM_Prescaler = 7200-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);//第二定义定时器基本参数
举例,这里以定时1S为例
1.4 开启TIM2定时器
TIM_ITConfig(TIM2, TIM_IT_CC1, ENABLE );//第三是能TIM2定时器
1.5 开启NVIC中断(NVIC是控制所有的中断的``)
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitTypeDef NVIC_InitStruct
NVIC_InitStruct.IRQChannel = TIM2_IRQChannel;
NVIC_InitStruct.IRQChannelPreemptionPriority = 0;
NVIC_InitStruct.IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct)//初始化NVIC
1.6 启动定时器
TIM_Cmd(TIM2, ENABLE);//启动定时器2的库函数;
以上就是整个定时器中断初始化的代码;
2 写中断函数
void TIM2_IRQHandler(void)//编写中断函数
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET);//获取中断标志位,查看是否有中断;
{
TIM_ClearFlag(TIM2, TIM_FLAG_Update); //清除标志位,无论是否有标志位都要清楚
}
}
2.1 STM32中断标志:先清理后清理的区别
中断清除标志位,详细解释