l 使能定时器时钟。
RCC_APB1PeriphClockCmd();
l 初始化定时器,配置ARR,PSC。
TIM_TimeBaseInit();
l 开启定时器中断,配置NVIC。
void TIM_ITConfig();
NVIC_Init();
l 使能定时器。
TIM_Cmd();
l 编写中断服务函数。
TIMx_IRQHandler();
l 源代码:
1 //Tout(溢出时间)=(ARR+1)(PSC+1)/Tclk 2 //500ms -> (4999+1)( 7199+1)/72000000 = 0.5s = 500ms 3 void TIM3_Int_Init(u16 arr,u16 psc) 4 { 5 TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; 6 NVIC_InitTypeDef NVIC_InitStructure; 7 8 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能 9 10 //定时器TIM3初始化 11 TIM_TimeBaseStructure.TIM_Period = arr; //设置更新装载值 12 TIM_TimeBaseStructure.TIM_Prescaler =psc;//设置预分频值 13 TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割 14 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式 15 TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); 16 17 TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //允许更新中断 18 19 //中断优先级NVIC设置 20 NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3中断 21 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //0抢占优先级 22 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //响应优先级 23 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道势能 24 NVIC_Init(&NVIC_InitStructure); //初始化NVIC寄存器 25 26 27 TIM_Cmd(TIM3, ENABLE); //使能TIM 28 } 29 //定时器3中断服务程序 30 void TIM3_IRQHandler(void) 31 { 32 if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查是否更新中断 33 { 34 TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //清楚更新中断 35 LED1=!LED1; 36 } 37 } 38 int main(void) 39 { 40 delay_init(); 41 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//抢占和响应优先级的范围0~3 42 uart_init(115200); 43 LED_Init(); 44 TIM3_Int_Init(4999,7199); 45 while(1) 46 { 47 LED0=!LED0; 48 delay_ms(200); 49 } 50 }