与6_1相似,但是6_2不使用内部时钟,而调用外部时钟
#include "stm32f10x.h" // Device header
void Timer_Init(void)
{
//1.开启TIM2时钟外设
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//有外部计时器,需配置GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//2.选择时基单元的时钟(外部时钟)
//无分频,不反向,无滤波器
TIM_ETRClockMode2Config(TIM2,TIM_ExtTRGPSC_OFF,TIM_ExtTRGPolarity_NonInverted,0x00);
//3.配置时基单元
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 = 1HZ = CK_PSC(72MHZ)/ (PSC + 1) / (ARR + 1)
最后保证PSC和ARR取值在0~65535
*/
//ARR多,PSC少 即高频率记比较多的数,反之亦然;
TIM_TimeBaseInitStructure.TIM_Period = 10-1;//ARR自动重装器的值
TIM_TimeBaseInitStructure.TIM_Prescaler = 1-1;//PSC预分频器的值
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;//重复计数器的值(高级计数器)
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
TIM_ClearFlag(TIM2,TIM_FLAG_Update); //手动清除更新位,可以避免刚初始化玩就中断
//4.使能中断
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);//更新中断
//5.配置NVIC
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//在模块里要保证是同一个分组
NVIC_InitTypeDef NVIC_InitStructure;
//指定中断通道开启或关闭
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;//定时器2在NVIC里的中断通道
//指定中断通道是ENABLE还是DISABLE
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
/*抢占优先级和响应优先级看到是NVIC的分组 ,NVIC_PriorityGroup_2只能在0~3*/
//指定抢占优先级
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
//指定响应优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
//6.启动定时器
TIM_Cmd(TIM2,ENABLE);
}
uint16_t Timer_GetCounter(void)
{
return TIM_GetCounter(TIM2);
}
/*
中断函数模板
//7.中断函数
void TIM2_IRQHandler(void)
{
//检查中断位
if(TIM_GetITStatus(TIM2,TIM_IT_Update) == SET)
{
//清除标志位
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
}
}*/
主函数
#include "stm32f10x.h" // Device header
#include "Delay.h"
#include "OLED.h"
#include "Timer.h"
uint16_t Num;
int main(void)
{
OLED_Init();
Timer_Init();
OLED_ShowString(1, 1, "Num = ");
OLED_ShowString(2, 1, "CNT = ");
while (1)
{
OLED_ShowNum(1,7,Num,3);
OLED_ShowNum(2,5,Timer_GetCounter(),5);//无预分频,形如计数器
}
}