51单片机数码管矩阵按键显示0-15代码
时间: 2024-03-22 19:36:49 浏览: 268
以下是一个基于51单片机的数码管矩阵按键显示0-15的代码:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
// 数码管显示的数字编码
uchar code numCode[16] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71
};
sbit LSA = P2^2;
sbit LSB = P2^3;
sbit LSC = P2^4;
sbit keyIn1 = P3^2;
sbit keyIn2 = P3^3;
sbit keyIn3 = P3^4;
sbit keyIn4 = P3^5;
sbit keyOut1 = P3^6;
sbit keyOut2 = P3^7;
// 数码管位选函数
void selectPos(uchar pos) {
switch(pos) {
case 0:
LSA = 0; LSB = 0; LSC = 0;
break;
case 1:
LSA = 1; LSB = 0; LSC = 0;
break;
case 2:
LSA = 0; LSB = 1; LSC = 0;
break;
case 3:
LSA = 1; LSB = 1; LSC = 0;
break;
case 4:
LSA = 0; LSB = 0; LSC = 1;
break;
case 5:
LSA = 1; LSB = 0; LSC = 1;
break;
case 6:
LSA = 0; LSB = 1; LSC = 1;
break;
case 7:
LSA = 1; LSB = 1; LSC = 1;
break;
}
}
// 读取键值函数
uchar getKey() {
uchar val = 0xff;
keyOut1 = 0;
if (keyIn1 == 0) { val = 0; }
if (keyIn2 == 0) { val = 1; }
if (keyIn3 == 0) { val = 2; }
if (keyIn4 == 0) { val = 3; }
keyOut1 = 1;
keyOut2 = 0;
if (keyIn1 == 0) { val = 4; }
if (keyIn2 == 0) { val = 5; }
if (keyIn3 == 0) { val = 6; }
if (keyIn4 == 0) { val = 7; }
keyOut2 = 1;
return val;
}
void main() {
uchar i, j, val;
while(1) {
for (i = 0; i < 8; i++) {
selectPos(i);
P0 = numCode[i];
for (j = 0; j < 50; j++); // 延时
P0 = 0x00;
}
val = getKey(); // 读取按键值
if (val != 0xff) {
P0 = numCode[val];
while(getKey() != 0xff); // 等待按键松开
}
}
}
```
这个程序使用了一个8位数码管矩阵和4个按键,每次循环遍历数码管的每一位,并在每一位上显示相应的数字。同时,程序会不断地读取按键值,如果有按键按下,则在数码管上显示相应的数字。需要注意的是,这个程序只能显示0-7这8个数字,如果想要显示更多数字,还需要对`numCode`数组进行扩展。
阅读全文