#include "stm32f10x.h" // Device header
#include "OLED.h"
#include "timer2.h"
/***************************************************/定时器2
#include "stm32f10x.h"
#include "timer2.h"
extern int num;
void timer2_init(void)
{
//**1.打开总的RCC,要配置GPIO从而传入外部时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);//因为定时器2是通用定时器,在APB1总线上
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
//**2.配置定时器接入外部时钟 同时配置外部时钟输入的引脚
//TIM_InternalClockConfig(TIM2);//设置定时器2使用内部时钟,可不写,上电默认
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;
GPIO_InitStruct.GPIO_Pin=GPIO_Pin_12;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStruct);
TIM_ETRClockMode2Config(TIM2, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0x00);//第二个设置分频,第三个设置触发方式,第四个设置采样频率(滤波器)
//**3.配置时基单元
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;//设置分频
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;//设置向上计数
// TIM_TimeBaseInitStruct.TIM_Period=10000-1;//设置预装载值 //外部时钟的话用不了这么高的频率
// TIM_TimeBaseInitStruct.TIM_Prescaler=7200-1;//设置预分频值
TIM_TimeBaseInitStruct.TIM_Period=10-1;//设置预装载值
TIM_TimeBaseInitStruct.TIM_Prescaler=2-1;//设置预分频值
TIM_TimeBaseInitStruct.TIM_RepetitionCounter=0;//高级计数器功能,重复计数器
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);//初始化时基单元
TIM_ClearFlag(TIM2,TIM_FLAG_Update);//初始化时会产生标志位,需要清除
//**4.使能时基单元的中断
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
//**5.配置NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//分组
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_InitStruct.NVIC_IRQChannel=TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStruct);
//**6.开始计数
TIM_Cmd(TIM2,ENABLE);
}
//**配置中断函数
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET)
{
num++;
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
/***************************************************/主函数
int num;
int main(void)
{
OLED_Init();
timer2_init();
OLED_ShowString(1,1,"Hello,my honey");
// OLED_ShowString(2,1,"Hello WangFang");
// OLED_ShowString(3,1,"Hello Tomorrow");
// OLED_ShowString(4,1,"I miss you");
while(1)
{
OLED_ShowString(2,1,"NUM:");
OLED_ShowNum(2,5,num,5);
OLED_ShowString(3,1,"Prescaler:");
OLED_ShowNum(3,11,TIM_GetPrescaler(TIM2),5);
OLED_ShowString(4,1,"Counter:");
OLED_ShowNum(4,9,TIM_GetCounter(TIM2),5);
}
}
|