1 硬件设计
- 本开发板来自野火的STM32F429IGTb V2 开发板,资料链接:https://doc.embedfire.com/products/link/zh/latest/mcu/stm32/ebf_stm32f429_tiaozhanzhe_v1_v2/download/stm32f429_tiaozhanzhe_v1_v2.html

2 软件设计
以下代码来源于野火整合:
https://gitee.com/Embedfire-stm32f429-tiaozhanzhe/ebf_stm32f429_tiaozhanzhe_std_code
2.1 前提准备
- 在工程目录下面的USER 文件夹中创建KEY 文件夹,在新创建的KEY 文件夹中创建两个文件key.h 和key.c
- key.h:按键引脚宏定义
- key.c:按键 灯引脚函数程序
- 将key.c 添加进USER 组中
- 前一篇文章程序:http://ckun.fun/index.php/2024/12/03/standard_library_led/


2.2 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 // GPIO 初始化 void Key_GPIO_Config(void); // 按键状态监测 uint8_t Key_Scan(GPIO_TypeDef* GPIOx,u16 GPIO_Pin); #endif
2.3 key.c
#include "./key/key.h" // 不精确的延时 void Key_Delay(__IO u32 nCount) { for (; nCount != 0; nCount--); } void Key_GPIO_Config(void) { GPIO_InitTypeDef GPIO_InitStructure; /*开启按键GPIO口的时钟*/ RCC_AHB1PeriphClockCmd(KEY1_GPIO_CLK | KEY2_GPIO_CLK, ENABLE); /*选择按键的引脚*/ GPIO_InitStructure.GPIO_Pin = KEY1_PIN; /*设置引脚为输入模式*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; /*设置引脚不上拉也不下拉*/ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; /*使用上面的结构体初始化按键*/ GPIO_Init(KEY1_GPIO_PORT, & GPIO_InitStructure); /*选择按键的引脚*/ GPIO_InitStructure.GPIO_Pin = KEY2_PIN; /*使用上面的结构体初始化按键*/ GPIO_Init(KEY2_GPIO_PORT, & GPIO_InitStructure); } /** * @brief 检测是否有按键按下 * @param GPIOx:具体的端口, x可以是(A...K) * @param GPIO_PIN:具体的端口位, 可以是GPIO_PIN_x(x可以是0...15) * @retval 按键的状态 * @arg KEY_ON:按键按下 * @arg KEY_OFF:按键没按下 */ 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; }
2.4 main.c
#include "stm32f4xx.h" #include "./led/bsp_led.h" #include "./key/bsp_key.h" int main(void) { /* LED 端口初始化 */ LED_GPIO_Config(); /*初始化按键*/ Key_GPIO_Config(); /* 轮询按键状态,若按键按下则反转LED */ while (1) { if (Key_Scan(KEY1_GPIO_PORT, KEY1_PIN) == KEY_ON) { /*LED1反转*/ LED1_TOGGLE; } if (Key_Scan(KEY2_GPIO_PORT, KEY2_PIN) == KEY_ON) { /*LED2反转*/ LED2_TOGGLE; } } }