1.main.c(主函数部分)代码:
#include "stm32f10x.h" // Device header #include "Delay.h" #include "OLED.h" #include "Timer.h" uint16_t Num; int main(void) { OLED_Init(); OLED_ShowString(1,1,"Num:"); OLED_ShowString(2,1,"CNT:"); Timer_Init(); while(1) { OLED_ShowNum(1,5,Num,4); OLED_ShowNum(2,5,Timer_GetCounter(),4); } } void TIM2_IRQHandler(void) { if(TIM_GetITStatus(TIM2,TIM_IT_Update)==SET) { Num++; TIM_ClearITPendingBit(TIM2,TIM_IT_Update); } }
2.定时外部中断(Timer.c)代码部分:
#include "stm32f10x.h" // Device header void Timer_Init(void) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU; GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0; GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOA,&GPIO_InitStruct); TIM_ETRClockMode2Config(TIM2,TIM_ExtTRGPSC_OFF,TIM_ExtTRGPolarity_NonInverted,0x00); TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct; TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStruct.TIM_Period=10-1; TIM_TimeBaseInitStruct.TIM_Prescaler=1-1; TIM_TimeBaseInitStruct.TIM_RepetitionCounter=0; TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct); TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE); 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); TIM_Cmd(TIM2,ENABLE); } uint16_t Timer_GetCounter(void) { return TIM_GetCounter(TIM2); }
3.定时器外部中断(Timer.h)代码部分:
#ifndef __TIMER_H #define __TIMER_H void Timer_Init(void); uint16_t Timer_GetCounter(void); #endif