4x4的矩阵键盘防鬼键51单片机示例
时间: 2024-03-09 09:38:23 浏览: 66
以下是一个基于51单片机的4x4矩阵键盘防鬼键示例程序:
```c
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit ROW1 = P1^0;
sbit ROW2 = P1^1;
sbit ROW3 = P1^2;
sbit ROW4 = P1^3;
sbit COL1 = P1^4;
sbit COL2 = P1^5;
sbit COL3 = P1^6;
sbit COL4 = P1^7;
uchar code keycode[] = {0xEE, 0xED, 0xEB, 0xE7, 0xDE, 0xDD, 0xDB, 0xD7, 0xBE, 0xBD, 0xBB, 0xB7, 0x7E, 0x7D, 0x7B, 0x77}; //键值表
uchar KeyScan() //矩阵键盘扫描函数
{
uchar row, col;
uchar key = 0xFF;
ROW1 = 0; ROW2 = 1; ROW3 = 1; ROW4 = 1; //第一行扫描
col = COL1 & COL2 & COL3 & COL4;
if (col == 0) {
if (COL1 == 0) key = 0; else if (COL2 == 0) key = 1; else if (COL3 == 0) key = 2; else key = 3;
}
ROW1 = 1; ROW2 = 0; ROW3 = 1; ROW4 = 1; //第二行扫描
col = COL1 & COL2 & COL3 & COL4;
if (col == 0) {
if (COL1 == 0) key = 4; else if (COL2 == 0) key = 5; else if (COL3 == 0) key = 6; else key = 7;
}
ROW1 = 1; ROW2 = 1; ROW3 = 0; ROW4 = 1; //第三行扫描
col = COL1 & COL2 & COL3 & COL4;
if (col == 0) {
if (COL1 == 0) key = 8; else if (COL2 == 0) key = 9; else if (COL3 == 0) key = 10; else key = 11;
}
ROW1 = 1; ROW2 = 1; ROW3 = 1; ROW4 = 0; //第四行扫描
col = COL1 & COL2 & COL3 & COL4;
if (col == 0) {
if (COL1 == 0) key = 12; else if (COL2 == 0) key = 13; else if (COL3 == 0) key = 14; else key = 15;
}
return key;
}
void main()
{
uchar key, prevKey = 0xFF;
while (1) {
key = KeyScan();
if (key != 0xFF && prevKey == 0xFF) { //检测到按键按下
P2 = keycode[key]; //输出对应键值
}
prevKey = key;
}
}
```
该程序采用轮询方式扫描矩阵键盘,当检测到按键按下时,输出对应的键值。同时,为了防止按键抖动和多次触发,使用了“防鬼键”技术。具体来说,当检测到按键按下时,必须等到按键释放后才能再次检测到按键按下。这样可以保证每次按键只被检测到一次,避免了按键的误触发。
阅读全文