003 - STM32学习笔记 - 按键操作
1、创建板级支持包
延续上节的程序,在User目录下创建KEY文件夹,包含bsp_key.c及头文件bsp_key.h,之后在Keil中将bsp_key.c加入
2、程序
bsp_key.h
#ifndef __BSP_KEY_H__
#define __BSP_KEY_H__
#include "stm32f4xx.h"
#include "stm32f4xx_rcc.h"
#define KEY1_PIN GPIO_Pin_0
#define KEY1_PORT GPIOA
#define KEY1_CLK RCC_AHB1Periph_GPIOA
#define KEY2_PIN GPIO_Pin_13
#define KEY2_PORT GPIOC
#define KEY2_CLK RCC_AHB1Periph_GPIOC
#define KEY_ON 1
#define KEY_OFF 0
void Key_Config(void);
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin);
#endif /* __BSP_KEY_H__ */
bsp_key.c
#include ".\KEY\bsp_key.h"
void Key_Config(void)
{
//创建GPIO_InitTypeDef结构体变量
GPIO_InitTypeDef KEY_InitStructure;
//使能按键所在端口时钟
RCC_AHB1PeriphClockCmd(KEY1_CLK|KEY2_CLK,ENABLE);
//设置端口模式为输入
KEY_InitStructure.GPIO_Mode = GPIO_Mode_IN;
//设置端口上下拉模式为浮空模式
KEY_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//配置为输入模式,OType、PuPd、Speed寄存器无需配置
//选择按键引脚key1
KEY_InitStructure.GPIO_Pin = KEY1_PIN;
//初始化引脚
GPIO_Init(KEY1_PORT,&KEY_InitStructure);
//选择按键引脚key2
KEY_InitStructure.GPIO_Pin = KEY2_PIN;
//初始化引脚
GPIO_Init(KEY2_PORT,&KEY_InitStructure);
}
uint8_t Key_Scan(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin)
{
//判断按键是否按下
if(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON)
{
//消抖,等待按键释放
while(GPIO_ReadInputDataBit(GPIOx,GPIO_Pin) == KEY_ON); //调用库函数读取按键输入
return KEY_ON;
}
else
return KEY_OFF;
}
main.c
#include "stm32f4xx.h"
#include ".\LED\bsp_led.h"
#include ".\KEY\bsp_key.h"
int main(void)
{
Led_Config();
Key_Config();
while(1)
{
if(Key_Scan(KEY1_PORT,KEY1_PIN) == KEY_ON)
LED_R_TOGGLE;
if(Key_Scan(KEY2_PORT,KEY2_PIN) == KEY_ON)
LED_G_TOGGLE;
}
}
下载测试!
注:
1、这节因为跟上节是上节写完后测试的(上班摸鱼没带板子,只能下班回家后再测),所以也有标准库中LED端口时钟使能宏复制错的问题;
2、bsp_key板级支持包写完后,在main函数中没有调用Led和Key的配置函数,结果也是调试结果与预期不同。