stm32定时器(库函数)学习笔记
定时器的组成:
时钟选择、时基电路、输入捕获、输出比较
1.定时器时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能
2.初始化定时器
void TIM3_Int_Init(u16 arr,u16 psc) //留下arr与psc的参数入口,方便调试
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = arr; //重装载周期
TIM_TimeBaseStructure.TIM_Prescaler =psc; //预分频系数
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //设置向上或者向下或者*靠齐计数
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //将结构体赋值给寄存器
3.指定定时器中断,并进行中断优先级分组
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //允许更新中断,开启中断使能
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
4.使能定时器
TIM_Cmd(TIM3, ENABLE);
5.编写中断服务函数
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //清空标志位
LED1=!LED1;
}
}