STM32中断定时,控制LED灯

时间:2022-09-22 14:37:28
 1 #include "led.h"
 2 
 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); //设置TIM3时钟使能
 9 
10 
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;  //向上的计数模式
15     TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); //TIM3的初始化
16 
17     TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //TIM3更新中断使能
18 
19 
20     NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;  //TIM3中断
21     NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;  //先占优先0级
22     NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;  //从占优先3级
23     NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
24     NVIC_Init(&NVIC_InitStructure);  //初始化NVIC寄存器
25 
26 
27     TIM_Cmd(TIM3, ENABLE);  //使能TIM3
28 }
29 //定时器3中断服务程序
30 void TIM3_IRQHandler(void)   //TIM3中断
31 {
32     if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)  //检查TIM3更新中断发生与否
33         {
34         TIM_ClearITPendingBit(TIM3, TIM_IT_Update  );  //清除TIMx更新中断标志
35         LED2=!LED2;  //取反
36         }
37 }
 1 #include "stm32f10x_conf.h"
 2 #include "led.h"
 3 #include "key.h"
 4 #include "delay.h"
 5 #include "timer.h"
 6 #include "usart.h"
 7 
 8 int main(void)
 9 {
10 
11     delay_init();
12     LED_Init();
13     NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
14     uart_init(115200);
15     TIM3_Int_Init(4999,7199);
16     //((4999+1)*( 7199+1))/72=500000us=500ms  延时500ms
17   while(1)
18   {
19         LED3=!LED3;
20         delay_ms(1500);
21         /*当数值为2000时,延时时间变快。当数值为1500以下,
22         延时时间为x/1000,只设了几个值。其他值都还没有尝试。
23         */
24   }
25 
26 }