STM32F429IGT6 矩阵键盘按键检测 For 循环代码示例
#include "stm32f4xx.h"
#define ROWS 4 #define COLS 4
// 矩阵键盘的行和列引脚 GPIO_TypeDef* row_ports[ROWS] = {GPIOA, GPIOB, GPIOC, GPIOD}; uint16_t row_pins[ROWS] = {GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3};
GPIO_TypeDef* col_ports[COLS] = {GPIOE, GPIOE, GPIOE, GPIOE}; uint16_t col_pins[COLS] = {GPIO_PIN_0, GPIO_PIN_1, GPIO_PIN_2, GPIO_PIN_3};
uint8_t keypad[ROWS][COLS] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };
void init_keypad() { // 初始化行引脚为输入模式,上拉 for (int i = 0; i < ROWS; i++) { GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = row_pins[i]; GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_PULLUP; HAL_GPIO_Init(row_ports[i], &GPIO_InitStruct); }
// 初始化列引脚为输出模式,高电平
for (int i = 0; i < COLS; i++) {
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = col_pins[i];
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(col_ports[i], &GPIO_InitStruct);
HAL_GPIO_WritePin(col_ports[i], col_pins[i], GPIO_PIN_SET);
}
}
uint8_t read_keypad() { uint8_t key = 0;
for (int i = 0; i < ROWS; i++) {
HAL_GPIO_WritePin(col_ports[i], col_pins[i], GPIO_PIN_RESET);
for (int j = 0; j < COLS; j++) {
if (HAL_GPIO_ReadPin(row_ports[j], row_pins[j]) == GPIO_PIN_RESET) {
key = keypad[i][j];
break;
}
}
HAL_GPIO_WritePin(col_ports[i], col_pins[i], GPIO_PIN_SET);
if (key != 0) {
break;
}
}
return key;
}
int main(void) { // 初始化矩阵键盘 init_keypad();
while (1) {
uint8_t key = read_keypad();
if (key != 0) {
// 按键被按下
// 执行相应的操作
}
// 延时
HAL_Delay(100);
}
}
原文地址: https://www.cveoy.top/t/topic/pjzz 著作权归作者所有。请勿转载和采集!