基于CubeMX生成的初始化代码配置KEY的模块化
基于CubeMX生成的初始化代码配置KEY的模块化
硬件连接图
由图可知按键按下输入为低电平
CubeMX按键配置
在LED CubeMX的配置中添加按键的配置后生成初始化代码
key.c文件配置
#include "key.h"
void KEY_init(void) //将CubeMX中的初始化按键部分代码复制在此函数中
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin : PA0 */
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PB0 PB1 PB2 */
GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_2;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
unsigned char KEY_Scan(void) //带有返回值的按键扫描函数
{
unsigned char ucKey_value; //定义一个按键值的变量
if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_0) == GPIO_PIN_RESET) //按键B1按下键值返回为1
ucKey_value=1;
else if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_1) == GPIO_PIN_RESET) //按键B2按下键值返回为2
ucKey_value=2;
else if(HAL_GPIO_ReadPin(GPIOB,GPIO_PIN_2) == GPIO_PIN_RESET) //按键B3按下键值返回为3
ucKey_value=3;
else if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0) == GPIO_PIN_RESET) //按键B4按下键值返回为4
ucKey_value=4;
else
ucKey_value=0; //无按键按下键值返回为0
return ucKey_value;
}
key.h文件配置
#ifndef __KEY_H
#define __KEY_H
#include "main.h"
void KEY_init(void);
unsigned char KEY_Scan(void);
#endif
使用按键经典的三行代码实现按键处理函数
void KEY_Proc(void) //独立按键处理函数对按键的简单控制
{
/*沿用uwTick的变量定义方式定义滴答定时器按键打点变量*/
__IO uint32_t uwTick_State_Pointer;
unsigned char ucKey_value,ucKey_Dwon,ucKey_Up;
static unsigned char ucKey_Old; //静态变量上一次的键值
//利用滴答计时器定义按键扫描时间100ms
if(uwTick-uwTick_State_Pointer<100) return;
uwTick_State_Pointer=uwTick;
ucKey_value = KEY_Scan();
ucKey_Dwon = ucKey_value & ( ucKey_value ^ ucKey_Old ); //按下为按键值,其它为0
ucKey_Up = ~ucKey_value & ( ucKey_value ^ ucKey_Old ); //松手为抬起前的按键值,其他为0
ucKey_Old = ucKey_value;
if(ucKey_Dwon == 4)
{
LED_Display(0x01); //按键4按下LED1点亮
}
if(ucKey_Dwon == 3)
{
LED_Display(0x00); //按键3按下LED熄灭
}
if(ucKey_Dwon == 2)
{
LED_Display(0xFF); //按键2按下LED1~8点亮
}
if(ucKey_Dwon == 1)
{
for(i=0;i<8;i++)
{
LED_Display(0x01<<i); //按键1按下实现流水灯的效果
HAL_Delay(500);
}
}
main.c文件
#include "main.h"
#include "led.h"
#include "key.h"
void SystemClock_Config(void);
void KEY_Proc(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
LED_Init();
KEY_init();
while (1)
{
KEY_Proc();
}
}