timer_interrupt.c文件
/*
初始化函数编写步骤:
1.打开时钟
2.选择时基单元的时钟源(内部时钟源)
3.配置时基单元
4.NVIC配置
5.启动定时器
*/
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "timer_interrupt.h"
extern uint16_t num;
//初始化函数
void Timer_Init(void)
{
//开启TIM2的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//选择时基单元的时钟为内部时钟
TIM_InternalClockConfig(TIM2);
//时基单元初始化配置
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1; //指定时钟分频为1分频即不分频
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up; //配置计数器的模式为向上计数
TIM_TimeBaseInitStruct.TIM_Period= 10000 - 1; //设置周期值即ARR自动重装器的值
TIM_TimeBaseInitStruct.TIM_Prescaler= 720 - 1; //设置PSC预分频器的值
TIM_TimeBaseInitStruct.TIM_RepetitionCounter= 0; //设置重复计数器的值
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);
//清除中断标志位
TIM_ClearFlag(TIM2,TIM_FLAG_Update);
//TIM2使能,更新中断
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
//NVIC配置
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //指定中断分组为分组2(2位抢占2位响应)
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel=TIM2_IRQn; //设置指定中断通道为TIM2_IRQn
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE; //设置指定中断通道使能
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=2; //设置抢占优先级
NVIC_InitStruct.NVIC_IRQChannelSubPriority=1; //设置响应优先级
NVIC_Init(&NVIC_InitStruct);
//启动定时器
TIM_Cmd(TIM2,ENABLE);
}
//中断函数
void TIM2_IRQHandler(void)
{
//判断中断线14的中断标志位是不是1
if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET)
{
num++;
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);//清除中断标志位
}
}
timer_interrupt.h文件
#ifndef __TIMER_INTERRUPT_H
#define __TIMER_INTERRUPT_H
void Timer_Init(void);
void TIM2_IRQHandler(void);
#endif
main.c文件
#include "stm32f10x.h"
#include "stm32f10x_tim.h"
#include "delay.h"
#include "OLED.h"
#include "timer_interrupt.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);
OLED_ShowNum(3,5,TIM_GetPrescaler(TIM2),5);
}
}