一个ch455实现4x5矩阵键盘灯光,具体实现代码
时间: 2024-01-31 13:04:03 浏览: 75
以下是一个使用CH455芯片实现4x5矩阵键盘灯光的示例代码:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
uchar code KeyTab[] = "123A456B789C*0#D"; // 键值表
uchar code LEDTab[] = { // LED 灯光表
0x3f, 0x06, 0x5b, 0x4f, 0x66, // 0-4
0x6d, 0x7d, 0x07, 0x7f, 0x6f, // 5-9
0x77, 0x7c, 0x39, 0x5e, 0x79, // A-D
0x71, 0x40, 0x76, 0x06, 0x00 // * 0 # 空
};
sbit K1 = P1^0; // 行列引脚定义
sbit K2 = P1^1;
sbit K3 = P1^2;
sbit K4 = P1^3;
sbit C1 = P1^4;
sbit C2 = P1^5;
sbit C3 = P1^6;
sbit C4 = P1^7;
sbit L1 = P2^0; // LED 引脚定义
sbit L2 = P2^1;
sbit L3 = P2^2;
sbit L4 = P2^3;
sbit L5 = P2^4;
sbit L6 = P2^5;
sbit L7 = P2^6;
sbit L8 = P2^7;
void Delay(uint t) { // 延时函数
uint i, j;
for (i = 0; i < t; i++) {
for (j = 0; j < 125; j++);
}
}
void KeyScan() { // 键盘扫描函数
uchar i, j, k, key, led;
for (i = 0; i < 4; i++) { // 行扫描
switch (i) {
case 0: K1 = 0; K2 = 1; K3 = 1; K4 = 1; break;
case 1: K1 = 1; K2 = 0; K3 = 1; K4 = 1; break;
case 2: K1 = 1; K2 = 1; K3 = 0; K4 = 1; break;
case 3: K1 = 1; K2 = 1; K3 = 1; K4 = 0; break;
}
for (j = 0; j < 4; j++) { // 列扫描
if (C1 == 0) k = i*4+j;
else if (C2 == 0) k = i*4+j+1;
else if (C3 == 0) k = i*4+j+2;
else if (C4 == 0) k = i*4+j+3;
else continue;
key = KeyTab[k]; // 获取键值
led = LEDTab[k]; // 获取灯光值
P2 = ~led; // 显示 LED 灯光
Delay(20); // 延时稳定
if (key != '*') { // 控制 LED 灯光
switch (led) {
case 0x3f: L1 = !L1; break;
case 0x06: L2 = !L2; break;
case 0x5b: L3 = !L3; break;
case 0x4f: L4 = !L4; break;
case 0x66: L5 = !L5; break;
case 0x6d: L6 = !L6; break;
case 0x7d: L7 = !L7; break;
case 0x07: L8 = !L8; break;
}
}
while (C1 == 0 || C2 == 0 || C3 == 0 || C4 == 0); // 等待键释放
}
}
}
void main() {
while (1) {
KeyScan(); // 执行键盘扫描
}
}
```
需要注意的是,该示例代码使用了P1和P2口作为键盘和LED显示的引脚,如果需要使用其他引脚,请根据自己的实际情况进行修改。同时,该代码使用了延时函数来稳定键盘扫描和LED显示,建议在实际应用中使用定时器等更加稳定的方法。
阅读全文