stm32定时器定时中断
- 项目:使用定时器内部时钟实现计数功能。
- 代码:
- Timer.c
#include "stm32f10x.h" extern uint16_t Num; //定时器初始化函数 void Timer_Init(void) { //打开TIM2外设时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //配置TIM2内部时钟源 TIM_InternalClockConfig(TIM2); //定义TIM_TimeBaseInit初始化结构体 TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //不分频 TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数 /*计数器溢出频率: CK_CNT_OV = CK_CNT/(ARR + 1) = CK_PSC/(PSC + 1)/ (ARR + 1)*/ /*定时1s, 即定时频率为1Hz(CK_CNT_OV); CK_PSC = 72MHz => 设置PSC= 7200-1, 则ARR = 10000 - 1*/ TIM_TimeBaseInitStructure.TIM_Period = 10000 - 1; //ARR TIM_TimeBaseInitStructure.TIM_Prescaler = 7200 - 1; //PSC TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; // TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure); // TIM_ClearFlag(TIM2, TIM_FLAG_Update); //清除更新标志位,解决刚开始上电就进入中断(即从1开始计数问题) TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE); //开启更新中断到NVIC的通路 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //配置抢占优先级和子优先级分组 NVIC_InitTypeDef NVIC_InitStructure; // NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn; //TIM2 全局中断 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //指定在NVIC_IRQChannel中定义的IRQ通道是否启用或禁用 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; // NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; // NVIC_Init(&NVIC_InitStructure); // TIM_Cmd(TIM2, ENABLE); //打开指定的定时器(TIM2)外设 } //TIM2中断处理函数 void TIM2_IRQHandler(void) { if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET) //判断更新标志 { Num++; TIM_ClearITPendingBit(TIM2, TIM_IT_Update); //清除标志位 } }
- Timer.h
#ifndef __TIMER_H #define __TIMER_H void Timer_Init(void); #endif
- main.c
#include "stm32f10x.h" #include "Delay.h" #include "OLED.h" #include "Timer.h" uint16_t Num; int main(void) { OLED_Init(); Timer_Init(); OLED_ShowString(1,1, "Num:"); while(1) { OLED_ShowNum(1,5, Num, 5); // OLED_ShowNum(2,5,TIM_GetCounter(TIM2), 5); } }
- 参考资料
- 定时器中断基本结构
-
-
执行结果
-