矩阵键盘编程keil代码,带有防抖的
时间: 2023-08-13 19:07:39 浏览: 184
以下是一个使用 Keil μVision 编写的带有防抖功能的矩阵键盘驱动程序代码示例:
```c
#include <reg52.h>
// 定义行列数
#define ROWS 4
#define COLS 4
// 定义行列引脚
sbit row1 = P2^0;
sbit row2 = P2^1;
sbit row3 = P2^2;
sbit row4 = P2^3;
sbit col1 = P2^4;
sbit col2 = P2^5;
sbit col3 = P2^6;
sbit col4 = P2^7;
// 定义键盘矩阵
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// 延时函数
void delay(unsigned int n) {
unsigned int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < 125; j++);
}
}
// 扫描键盘矩阵
char scan_keypad() {
char key = ' ';
row1 = 0; row2 = 1; row3 = 1; row4 = 1;
if (col1 == 0) { delay(10); if (col1 == 0) { key = keys[0][0]; } }
if (col2 == 0) { delay(10); if (col2 == 0) { key = keys[0][1]; } }
if (col3 == 0) { delay(10); if (col3 == 0) { key = keys[0][2]; } }
if (col4 == 0) { delay(10); if (col4 == 0) { key = keys[0][3]; } }
row1 = 1; row2 = 0; row3 = 1; row4 = 1;
if (col1 == 0) { delay(10); if (col1 == 0) { key = keys[1][0]; } }
if (col2 == 0) { delay(10); if (col2 == 0) { key = keys[1][1]; } }
if (col3 == 0) { delay(10); if (col3 == 0) { key = keys[1][2]; } }
if (col4 == 0) { delay(10); if (col4 == 0) { key = keys[1][3]; } }
row1 = 1; row2 = 1; row3 = 0; row4 = 1;
if (col1 == 0) { delay(10); if (col1 == 0) { key = keys[2][0]; } }
if (col2 == 0) { delay(10); if (col2 == 0) { key = keys[2][1]; } }
if (col3 == 0) { delay(10); if (col3 == 0) { key = keys[2][2]; } }
if (col4 == 0) { delay(10); if (col4 == 0) { key = keys[2][3]; } }
row1 = 1; row2 = 1; row3 = 1; row4 = 0;
if (col1 == 0) { delay(10); if (col1 == 0) { key = keys[3][0]; } }
if (col2 == 0) { delay(10); if (col2 == 0) { key = keys[3][1]; } }
if (col3 == 0) { delay(10); if (col3 == 0) { key = keys[3][2]; } }
if (col4 == 0) { delay(10); if (col4 == 0) { key = keys[3][3]; } }
return key;
}
int main() {
char key = ' ';
while (1) {
key = scan_keypad();
if (key != ' ') {
// 处理按键事件
}
delay(10);
}
return 0;
}
```
以上代码在扫描按键时加入了延时和防抖功能,可以有效避免按键抖动造成的误触。具体实现可以根据实际需要进行修改。
阅读全文