由于stm32中的时钟源对应的GPIO口都是ST原厂已经分配好的,可以查看数据手册了解,所以我们要将外部触发信号连接到对应的时钟源GPIO pin口,这样才能起到外部时钟源的作用。
例如:TIM3_ETR外部时钟源是接在PD2口的,如果你连接其他GPIO_Pin口,此时不会进入中断函数,也就没有起到外部时钟源的作用。
Timer.c
#include "stm32f10x.h" extern uint16_t Num; void Timer_Init(void) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); //配置GPIO GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOD,&GPIO_InitStructure); TIM_ETRClockMode2Config(TIM3, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_Inverted,0x00); // TIM_InternalClockConfig(TIM2); //单片机上电自动默认TMI2,可不写 TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period = 10 -1; // 0~65535 TIM_TimeBaseInitStructure.TIM_Prescaler = 1 -1; // 0~65535 TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); TIM_ClearFlag(TIM3, TIM_FLAG_Update); //避免刚好初始化就进入中断 TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); TIM_Cmd(TIM3,ENABLE); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); 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); } uint16_t Timer_GetCounter(void) { return TIM_GetCounter(TIM3); } void TIM2_IRQHandler(void) { if(TIM_GetITStatus(TIM3, TIM_IT_Update) == SET) { Num++; TIM_ClearITPendingBit(TIM3, TIM_IT_Update); } }
Timer.h
#ifndef __TIMER_H #define __TIMER_H void Timer_Init(void); uint16_t Timer_GetCounter(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:"); OLED_ShowString(2, 1, "CNT:"); while(1) { OLED_ShowNum(1, 5, Num, 5); OLED_ShowNum(2, 5, Timer_GetCounter(), 5); } }
标签:ETR,TIM3,TIMx,NVIC,TIM,InitStructure,GPIO,void,时钟 From: https://www.cnblogs.com/kevin-hou1991/p/16967711.html