stm32f103按键中断实现方法

(基于奋斗stm32_v5开发板)

#include"stm32f10x.h"

void LED_GPIO_Config()
{
	/*定义一个GPIO_InitTypeDef类型的结构体*/
	GPIO_InitTypeDef GPIO_InitStructure;
	
	/*开启GPIOB的外设时钟*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	
	/*选择要控制的GPIOB引脚*/
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	
	/*设置引脚模式为通用推挽输出*/
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	
	/*设置引脚速率为50MHz*/
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	
	/*调用库函数,初始化GPIOB*/
	GPIO_Init(GPIOB, &GPIO_InitStructure);
	
	/*关闭LED灯*/
	GPIO_SetBits(GPIOB, GPIO_Pin_5);	
}

void EXTI_PC5_Config()
{
	static void NVIC_Configuration();
	
	/*定义一个GPIO_InitTypeDef类型的结构体*/
	GPIO_InitTypeDef GPIO_InitStructure;
	/*定义一个EXTI_InitTypeDef类型的结构体*/
	EXTI_InitTypeDef EXTI_InitStructure;
	
	/*开启GPIOC的外设时钟和AFIO时钟*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE);
	
	/*配置NVIC(PC5)*/
	NVIC_Configuration();
	
	/*EXTI GPIO(PC5)线配置*/
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; /*设置上拉输入*/
	GPIO_Init(GPIOC, &GPIO_InitStructure); /*调用库函数,初始化GPIOC*/
	
	/*EXTI线(PE5)模式配置*/
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOC, GPIO_PinSource5);
	EXTI_InitStructure.EXTI_Line = EXTI_Line5;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; /*下降沿中断*/
	
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);
}

static void NVIC_Configuration()
{
	/*定义一个NVIC_InitTypeDef类型的结构体*/
	NVIC_InitTypeDef NVIC_InitStructure;
	
	/*为抢占优先级配置一位*/
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
	
	/*配置P[A|B|C|D|E]5为中断源*/
	NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
}

void Delay(uint32_t uCount)
{
    for(;uCount>0;uCount--);
}

void EXTI9_5_IRQHandler()
{
	if(EXTI_GetITStatus(EXTI_Line5) != RESET) /*确保是否产生了EXTI Line中断*/
	{
		/*消抖*/
		Delay(1000);
		/*LED取反*/
		GPIO_WriteBit(GPIOB, GPIO_Pin_5, (BitAction)((~GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_5))));
		/*清除中断标志位*/
		EXTI_ClearITPendingBit(EXTI_Line5);
	}
}

int main(void)
{
	/*初始化LED*/
	LED_GPIO_Config();
	/*EXTI线配置*/
	EXTI_PC5_Config();
	
	GPIO_SetBits(GPIOB, GPIO_Pin_5);/*置高*/
	
	while(1);
}

发布了9 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/T_zty_Y/article/details/79854621