06 STM32F429 按键检测
原理图
电路分析:
常态时端口接地为低电位,若悬空输入时按钮打开则为高电位.
该寄存器的库函数是怎么实现读入的?源码如下
即输出位与输出端进行与运算,若算出结果不为0则有输入信号为1,若为0则无输入信号.
代码
main.c
int main(){
LED_GPIO_Config();
Key_GPIO_Config();
while(1){
if(Key_Scan(KEY1_GPIO_PORT,KEY1_GPIO_PIN) == KEY_ON){
LED_R_TOGGLE();
}
}
}
bsp_led.c
#include"bsp_led.h"
//1- 先确定引脚号
//2- 确定是输入还是输出 MODER
//3- 如果是输出,那么是推挽还是开漏输出
void LED_GPIO_Config(void){
//变量需要定义在函数前
GPIO_InitTypeDef GPIO_InitStruct;
//打开时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOH,ENABLE);
//初始化GPIO结构体
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed = GPIO_Fast_Speed;
GPIO_Init(GPIOH,&GPIO_InitStruct);
}
void LED_R_TOGGLE(void){
//翻转 输出位异或,1与1异或为0,0与1异或为1
GPIOH->ODR ^= GPIO_Pin_10;
}
bcp_led.h
#ifndef _BSP_LED_H
#define _BSP_LED_H
#include "stm32f4xx_gpio.h"
void LED_R_TOGGLE(void);
void LED_GPIO_Config(void);
void RCC_AHB1PeriphClockCmd(uint32_t RCC_AHB1Periph, FunctionalState NewState);
#include "stm32f4xx_rcc.h"
#endif /* BSP_LED_PACK*/
bsp_key.c
#include"bsp_key.h"
void Key_GPIO_Config(void){
//变量需要定义在函数前
GPIO_InitTypeDef GPIO_InitStruct;
//打开时钟
RCC_AHB1PeriphClockCmd(KEY1_GPIO_CLK,ENABLE);
//初始化GPIO结构体
GPIO_InitStruct.GPIO_Pin = KEY1_GPIO_PIN;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
//GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;不需要输出
//配置为浮空
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
//GPIO_InitStruct.GPIO_Speed = GPIO_Fast_Speed;输入不用
GPIO_Init(KEY1_GPIO_PORT,&GPIO_InitStruct);
}
uint8_t Key_Scan(GPIO_TypeDef* GPIOx,uint16_t GPIO_Pin){
//如果检测到输入信号则进入
if(GPIO_ReadInputDataBit(GPIOx,KEY1_GPIO_PIN) == KEY_ON){
//放开按钮循环结束,若不加while死循环会导致灯闪烁频率过快,且无法控制开关.
while(GPIO_ReadInputDataBit(GPIOx,KEY1_GPIO_PIN) == KEY_ON);
//做相应的动作
return KEY_ON;
}
return KEY_OFF;
}
bsp_key.h
#ifndef __KEY_H
#define __KEY_H
#include "stm32f4xx.h"
//引脚定义
/*******************************************************/
#define KEY1_PIN GPIO_Pin_0
#define KEY1_GPIO_PORT GPIOA
#define KEY1_GPIO_CLK RCC_AHB1Periph_GPIOA
#define KEY2_PIN GPIO_Pin_13
#define KEY2_GPIO_PORT GPIOC
#define KEY2_GPIO_CLK RCC_AHB1Periph_GPIOC
/*******************************************************/
/** 按键按下标置宏
* 按键按下为高电平,设置 KEY_ON=1, KEY_OFF=0
* 若按键按下为低电平,把宏设置成KEY_ON=0 ,KEY_OFF=1 即可
*/
#define KEY_ON 1
#define KEY_OFF 0
void Key_GPIO_Config(void);
uint8_t Key_Scan(GPIO_TypeDef* GPIOx,u16 GPIO_Pin);
#endif /* __LED_H */
#define KEY_ON 1
#define KEY_OFF 0
void Key_GPIO_Config(void);
uint8_t Key_Scan(GPIO_TypeDef* GPIOx,u16 GPIO_Pin);
#endif /* __LED_H */