这次主要是展示TIM2的以内部时钟源为基准,进行1s的计数。
1.TIMER.c的代码
#include "stm32f10x.h" // Device header
uint16_t Num=0;
void Timer_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE );//开启APB1总线(TIM2是在APB1上)
TIM_InternalClockConfig(TIM2);//开启TIM2为内部时钟72M
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;//配置时基单元
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;//是否分频
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上计数模式
TIM_TimeBaseInitStructure.TIM_Period = 10000 - 1;//ARR
TIM_TimeBaseInitStructure.TIM_Prescaler = 7200 - 1;//PSC
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;//计算频率=72M/ARR/PSC
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);//1M=10的6次方
TIM_ClearFlag(TIM2, TIM_FLAG_Update);//清除标志位
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);//使能中断
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//配置NVIC
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init (&NVIC_InitStructure);
TIM_Cmd(TIM2,ENABLE);
}
void TIM2_IRQHandler(void)//配置Num可以在每次1s后向上计数
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET)
{
Num++;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
2.timer.h的代码
#ifndef __Timer_H
#define __Timer_H
void Timer_Init(void);
void TIM2_IRQHandler(void);
#endif
3.主函数代码
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Timer.h"
extern uint16_t Num;
int main(void)
{
OLED_Init();
Timer_Init();
TIM2_IRQHandler();
OLED_ShowString(1, 1, "Num:");//显示字符串
while (1)
{
OLED_ShowNum(1, 1, Num,5);//显示数字
}
}