一个4*4矩阵按键行引脚是PB0,PB1,PB2,PB3.列引脚是PB4,PB5,PB6,PB7.要求按下对应的按钮给字母n赋上对应的值。只许用HAL库函数。
时间: 2024-03-03 15:50:53 浏览: 70
好的,根据您的需求,下面是实现的代码:
```c
#include "main.h"
#include <stdio.h>
#define ROW_PIN_0 GPIO_PIN_0
#define ROW_PIN_1 GPIO_PIN_1
#define ROW_PIN_2 GPIO_PIN_2
#define ROW_PIN_3 GPIO_PIN_3
#define COL_PIN_0 GPIO_PIN_4
#define COL_PIN_1 GPIO_PIN_5
#define COL_PIN_2 GPIO_PIN_6
#define COL_PIN_3 GPIO_PIN_7
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
while (1)
{
uint8_t key_value = 0; //保存按键值的变量
uint8_t key_state = 0; //保存按键状态的变量
//扫描矩阵键盘是否有按键按下
for (uint8_t i = 0; i < 4; i++)
{
HAL_GPIO_WritePin(GPIOB, 1 << i, GPIO_PIN_RESET); //将第i行拉低
for (uint8_t j = 0; j < 4; j++)
{
key_state = HAL_GPIO_ReadPin(GPIOB, 1 << (j + 4)); //读取第j列的状态
if (key_state == GPIO_PIN_RESET) //如果第j列被按下
{
key_value = i * 4 + j + 1; //计算按键值
break;
}
}
HAL_GPIO_WritePin(GPIOB, 1 << i, GPIO_PIN_SET); //将第i行拉高
}
if (key_value != 0) //如果有按键按下
{
printf("您按下了%d号按键\n", key_value);
}
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 8;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 7;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pins : PB0 PB1 PB2 PB3
PB4 PB5 PB6 PB7 */
GPIO_InitStruct.Pin = ROW_PIN_0|ROW_PIN_1|ROW_PIN_2|ROW_PIN_3|COL_PIN_0|COL_PIN_1|COL_PIN_2|COL_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, ROW_PIN_0|ROW_PIN_1|ROW_PIN_2|ROW_PIN_3, GPIO_PIN_SET);
}
```
在上面的代码中,我们使用了HAL库函数来初始化GPIO口,并且使用了HAL库函数来读取矩阵键盘的按键状态。同时,我们还使用了printf函数将按键值输出到终端。请注意在使用printf函数之前需要添加相应的头文件和初始化,具体可以参考您所使用的开发板相关的文档。
阅读全文