蓝桥杯STM32G431学习记录3——KEY的CubeMX配置及使用

基于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();  
  }
}
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lzya.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值