STM32按鍵掃描/按鍵中斷/外部中斷
接觸STM32有一段時(shí)間了,也算是簡(jiǎn)單入了門,但由于一些原因,今天才來(lái)寫本應(yīng)該是入門級(jí)的按鍵相關(guān)程序,分為掃描模式和中斷模式
MCU:STM32F334C8
1.掃描模式首先配置按鍵引腳為上拉輸入模式,根據(jù)原理圖按鍵接PA0,按鍵沒(méi)有按下的時(shí)候引腳輸入為低電平0,按鍵按下輸入高電平1,松開(kāi)又回到低電平0
然后在死循環(huán)中不斷讀取相應(yīng)引腳的輸入狀態(tài),并根據(jù)返回結(jié)果判斷按鍵是否按下,做出相應(yīng)處理
下面的代碼完成的功能是:按鍵第一次按下,點(diǎn)亮燈,再按一次,熄滅,重復(fù)。
#include"Userkey.h"u8flag=0;voidkey_GPIO_Config(void){GPIO_InitTypeDefGPIO_InitStructure;RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE);GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0;GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN;GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);}voidkey_scanmode(void){key_GPIO_Config();while(1){if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0)){flag=~flag;if(flag)//第1?3?5,,次按下{GPIO_SetBits(GPIOB,GPIO_Pin_6);}else//第2?4?6,,,次按下{GPIO_ResetBits(GPIOB,GPIO_Pin_6);}}}}
第一步和上面相同,將接按鍵的引腳配置為上拉輸入,然后配置相應(yīng)中斷,PA0對(duì)應(yīng)外部中斷0
功能:按鍵按下,點(diǎn)亮LED并向串口發(fā)送按鍵按下到PC,按鍵松開(kāi),關(guān)掉LED并發(fā)送按鍵松開(kāi)
voidkey_interruptmode(void){EXTI_InitTypeDefEXTI_InitStructure;NVIC_InitTypeDefNVIC_InitStruct;key_GPIO_Config();NVIC_InitStruct.NVIC_IRQChannel=EXTI0_IRQn;NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=0;NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;NVIC_Init(&NVIC_InitStruct);SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA,EXTI_PinSource0);EXTI_ClearITPendingBit(EXTI_Line0);EXTI_InitStructure.EXTI_Line=EXTI_Line0;EXTI_InitStructure.EXTI_LineCmd=ENABLE;EXTI_InitStructure.EXTI_Mode=EXTI_Mode_Interrupt;EXTI_InitStructure.EXTI_Trigger=EXTI_Trigger_Rising_Falling;EXTI_Init(&EXTI_InitStructure);}voidEXTI0_IRQHandler(void){if(EXTI_GetITStatus(EXTI_Line0)){if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_0))//按鍵按下{GPIO_SetBits(GPIOB,GPIO_Pin_6);printf("按鍵按下n");//串口打印狀態(tài)}else//按鍵松開(kāi){GPIO_ResetBits(GPIOB,GPIO_Pin_6);printf("按鍵松開(kāi)n");}}EXTI_ClearITPendingBit(EXTI_Line0);}
注:如果要實(shí)現(xiàn)和1一樣的功能,將EXTI_Trigger改為上升沿或者下降沿,再改一下中斷處理函數(shù)即可