接触STM32有一段时间了,也算是简单入了门,但由于一些原因,今天才来写本应该是入门级的按键相关程序,分为扫描模式和中断模式
MCU:STM32F334C8 1.扫描模式首先配置按键引脚为上拉输入模式,根据原理图按键接PA0,按键没有按下的时候引脚输入为低电平0,按键按下输入高电平1,松开又回到低电平0 然后在死循环中不断读取相应引脚的输入状态,并根据返回结果判断按键是否按下,做出相应处理 下面的代码完成的功能是:按键第一次按下,点亮灯,再按一次,熄灭,重复。
- #include "Userkey.h"
- u8 flag=0;
- void key_GPIO_Config(void)
- {
- GPIO_InitTypeDef GPIO_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);
- }
- void key_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);
- }
- }
- }
- }
复制代码
2.中断模式第一步和上面相同,将接按键的引脚配置为上拉输入,然后配置相应中断,PA0对应外部中断0
功能:按键按下,点亮LED并向串口发送按键按下到PC,按键松开,关掉LED并发送按键松开
void key_interruptmode(void){ EXTI_InitTypeDef EXTI_InitStructure; NVIC_InitTypeDef NVIC_InitStruct; RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG,ENABLE); 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);}void EXTI0_IRQHandler(void){ if(EXTI_GetITStatus(EXTI_Line0)) { if(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_0))//按键按下 { GPIO_SetBits(GPIOB, GPIO_Pin_6); printf("按键按下\n"); //串口打印状态 } else //按键松开 { GPIO_ResetBits(GPIOB, GPIO_Pin_6); printf("按键松开\n"); } } EXTI_ClearITPendingBit(EXTI_Line0);}
|