51单片机两个数码管通过矩阵按键显示0-15代码
时间: 2024-03-22 10:36:51 浏览: 118
51单片机程序通过矩阵按键与数码管-C语言版.zip
以下是一个基于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 LSA1 = P2^2;
sbit LSB1 = P2^3;
sbit LSC1 = P2^4;
sbit LSA2 = P2^5;
sbit LSB2 = P2^6;
sbit LSC2 = P2^7;
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, uchar flag) {
if (flag == 1) { // 第一个数码管
switch(pos) {
case 0:
LSA1 = 0; LSB1 = 0; LSC1 = 0;
break;
case 1:
LSA1 = 1; LSB1 = 0; LSC1 = 0;
break;
case 2:
LSA1 = 0; LSB1 = 1; LSC1 = 0;
break;
case 3:
LSA1 = 1; LSB1 = 1; LSC1 = 0;
break;
case 4:
LSA1 = 0; LSB1 = 0; LSC1 = 1;
break;
case 5:
LSA1 = 1; LSB1 = 0; LSC1 = 1;
break;
case 6:
LSA1 = 0; LSB1 = 1; LSC1 = 1;
break;
case 7:
LSA1 = 1; LSB1 = 1; LSC1 = 1;
break;
}
} else { // 第二个数码管
switch(pos) {
case 0:
LSA2 = 0; LSB2 = 0; LSC2 = 0;
break;
case 1:
LSA2 = 1; LSB2 = 0; LSC2 = 0;
break;
case 2:
LSA2 = 0; LSB2 = 1; LSC2 = 0;
break;
case 3:
LSA2 = 1; LSB2 = 1; LSC2 = 0;
break;
case 4:
LSA2 = 0; LSB2 = 0; LSC2 = 1;
break;
case 5:
LSA2 = 1; LSB2 = 0; LSC2 = 1;
break;
case 6:
LSA2 = 0; LSB2 = 1; LSC2 = 1;
break;
case 7:
LSA2 = 1; LSB2 = 1; LSC2 = 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, val1, val2;
while(1) {
// 显示第一个数码管
for (i = 0; i < 8; i++) {
selectPos(i, 1);
P0 = numCode[i];
for (j = 0; j < 50; j++); // 延时
P0 = 0x00;
}
// 显示第二个数码管
for (i = 0; i < 8; i++) {
selectPos(i, 2);
P0 = numCode[i];
for (j = 0; j < 50; j++); // 延时
P0 = 0x00;
}
// 读取按键值
val1 = getKey();
if (val1 != 0xff) {
selectPos(0, 1);
P0 = numCode[val1];
while(getKey() != 0xff); // 等待按键松开
}
val2 = getKey();
if (val2 != 0xff) {
selectPos(0, 2);
P0 = numCode[val2];
while(getKey() != 0xff); // 等待按键松开
}
}
}
```
这个程序使用了两个8位数码管矩阵和4个按键,每次循环先遍历第一个数码管的每一位,并在每一位上显示相应的数字,然后再遍历第二个数码管的每一位。同时,程序会不断地读取按键值,如果有按键按下,则在相应的数码管上显示相应的数字。需要注意的是,这个程序只能显示0-7这8个数字,如果想要显示更多数字,还需要对`numCode`数组进行扩展。
阅读全文