STM32 时钟 、中断、定时器使用
函数RCC_APB1PeriphClockCmd() 和RCC_APB2PeriphClockCmd(),RCC_AHBPeriphClockCmd()
第一个参数形式如下RCC_APB2Periph_GPIOA 或者RCC_APB1Periph_TIM3
/** @defgroup APB2_peripheral
AFIO GPIOA GPIOB GPIOC ....GPIOG ADC1 ADC2 ADC3 SPI1 UART1 TIM1 TIM8 TIM9~11 TIM15~17
注意:AFIO当事件控制、重映射、外部中断需要使能AFIO时钟。
/** @defgroup APB1_peripheral
TIM2~7 TIM12~14 WWDG USB CAN1 CAN2 PWR DAC SPI2 SPI3 UART2~5 I2C1 I2C2
中断优先级分组
一般使用NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);设置一次。
以PE2为例,使用外部中断。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//初始化代码 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE,ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;//KEY2 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; //上拉输入 GPIO_Init(GPIOE, &GPIO_InitStructure);// RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //使能复用时钟 GPIO_EXTILineConfig(GPIO_PortSourceGPIOE,GPIO_PinSource2); EXTI_InitTypeDef EXTI_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitStructure.EXTI_Line=EXTI_Line2; //KEY2 EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;//下降沿触发 EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); NVIC_InitStructure.NVIC_IRQChannel = EXTI2_IRQn;//使能外部中断2通道 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x02; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); //中断相应函数 void EXTI2_IRQHandler(void) { delay_ms(10);//消抖 if(KEY2==0) //按键PE2 { LED0=!LED0; } EXTI_ClearITPendingBit(EXTI_Line2); //清除line2上的中断标志位 }
定时器
使用内部时钟
以TIM3为例子,使用定时器中断。
//arr自动装载值 //psc时钟预分频数 void TIM3_Int_Init(u16 arr,u16 psc) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //使能时钟 TIM_TimeBaseStructure.TIM_Period = arr; TIM_TimeBaseStructure.TIM_Prescaler =psc; TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分割TDTS = Tck_tim TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数 TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); // TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //允许更新中断 //中断优先级设置 NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; // NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); TIM_Cmd(TIM3, ENABLE); //使能TIM3 } //中断服务程序 void TIM3_IRQHandler(void) //TIM3ÖÐ¶Ï { if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查Tim3中断发生与否 { TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //清除标志 LED1=!LED1; } }
在主函数中,比如500ms中断一次
TIM3_Int_Init(4999,7199);//10Kh计数频率,计数5000为500ms