myKeyBoardSecond.c

#include <reg52.h>
#include "utilities.h"

sbit KEY_OUT_3 = P2^0;
sbit KEY_OUT_2 = P2^1;
sbit KEY_OUT_1 = P2^2;
sbit KEY_OUT_0 = P2^3;
sbit KEY_IN_0 = P2^4;
sbit KEY_IN_1 = P2^5;
sbit KEY_IN_2 = P2^6;
sbit KEY_IN_3 = P2^7;

uchar code keyCodeMap[4][4] = { //矩阵按键编号到标准键盘键码的映射表
    {0x31, 0x32, 0x33, 0x26}, //数字键1、数字键2、数字键3、向上键
    {0x34, 0x35, 0x36, 0x25}, //数字键4、数字键5、数字键6、向左键
    {0x37, 0x38, 0x39, 0x28}, //数字键7、数字键8、数字键9、向下键
    {0x30, 0x1B, 0x0D, 0x27}  //数字键0、ESC键、  回车键、 向右键
};

extern void keyAction(uchar keyCode);

void keyScan() {
    static uchar i = 0;
    static uchar keyBuf[4][4] = {
        {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF},
        {0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF}
    };
    static uchar backupState[4][4] = {
        {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}, {1, 1, 1, 1}
    };
    uchar j;

    keyBuf[i][0] = (keyBuf[i][0] << 1) | KEY_IN_0;
    keyBuf[i][1] = (keyBuf[i][1] << 1) | KEY_IN_1;
    keyBuf[i][2] = (keyBuf[i][2] << 1) | KEY_IN_2;
    keyBuf[i][3] = (keyBuf[i][3] << 1) | KEY_IN_3;
    for (j=0; j<4; j++) {
        if (keyBuf[i][j] == 0x00) {
            if (backupState[i][j] == 1) {
                keyAction(keyCodeMap[i][j]);
            }
            backupState[i][j] = 0;
        }
        else if (keyBuf[i][j] == 0xFF) {
            backupState[i][j] = 1;
        }
    }
    switch (i) {
        case 0: KEY_OUT_0 = 1; KEY_OUT_1 = 0; break;
        case 1: KEY_OUT_1 = 1; KEY_OUT_2 = 0; break;
        case 2: KEY_OUT_2 = 1; KEY_OUT_3 = 0; break;
        case 3: KEY_OUT_3 = 1; KEY_OUT_0 = 0; break;
        default : break;
    }
    i = ++i & 0x03;
}
 

你可能感兴趣的:(myKeyBoardSecond.c)