#include <stdint.h>
// 假设你有一个适当的 delay 函数
void delay(uint16_t ms);
// 假设 P1 和 P1_x (x = 0, 1, 2, 3, 4, 5, 6, 7) 已经被定义并连接到相应的硬件
#define ROW_COUNT 4
#define COL_COUNT 4
// 矩阵键盘扫描函数
unsigned char matrix_keydown()
{
uint8_t row, col;
static const uint8_t rowPins[] = {P1_0, P1_1, P1_2, P1_3};
static const uint8_t colPins[] = {P1_4, P1_5, P1_6, P1_7};
static const uint8_t keyMap[ROW_COUNT][COL_COUNT] = {
{1, 5, 9, 13},
{2, 6, 10, 14},
{3, 7, 11, 15},
{4, 8, 12, 16}
};
for (row = 0; row < ROW_COUNT; ++row)
{
P1 = 0xFF; // 设置所有列为高电平
rowPins[row] = 0; // 将当前行设为低电平
for (col = 0; col < COL_COUNT; ++col)
{
if (colPins[col] == 0) // 检查是否有列被拉低
{
delay(3); // 消抖
while (colPins[col] == 0); // 等待按键释放
delay(3); // 消抖
return keyMap[row][col]; // 返回按键值
}
}
rowPins[row] = 1; // 恢复当前行为高电平,为下一行做准备
}
return 0; // 没有按键被按下
}
可以尝试一下这个方法,没验证过, |