51单片机矩阵按键控制数字并显示在数码管上代码
时间: 2024-03-05 20:53:26 浏览: 68
【51程序】矩阵按键控制数码管显示
5星 · 资源好评率100%
以下是一个简单的51单片机矩阵按键控制数字并显示在数码管上的代码:
```c
#include <reg51.h>
unsigned char code numCode[] = { // 数码管显示字符编码
0x3F, 0x06, 0x5B, 0x4F, 0x66,
0x6D, 0x7D, 0x07, 0x7F, 0x6F
};
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;
void delay(unsigned int t) { // 延时函数
unsigned int i, j;
for(i = 0; i < t; i++)
for(j = 0; j < 125; j++);
}
unsigned char getKey() { // 获取按下的按键值
unsigned char key = 0;
ROW1 = 0; ROW2 = ROW3 = ROW4 = 1;
if(COL1 == 0) { delay(5); if(COL1 == 0) key = 1; }
if(COL2 == 0) { delay(5); if(COL2 == 0) key = 2; }
if(COL3 == 0) { delay(5); if(COL3 == 0) key = 3; }
if(COL4 == 0) { delay(5); if(COL4 == 0) key = 10; }
ROW1 = ROW2 = 0; ROW3 = ROW4 = 1;
if(COL1 == 0) { delay(5); if(COL1 == 0) key = 4; }
if(COL2 == 0) { delay(5); if(COL2 == 0) key = 5; }
if(COL3 == 0) { delay(5); if(COL3 == 0) key = 6; }
if(COL4 == 0) { delay(5); if(COL4 == 0) key = 11; }
ROW1 = ROW3 = 0; ROW2 = ROW4 = 1;
if(COL1 == 0) { delay(5); if(COL1 == 0) key = 7; }
if(COL2 == 0) { delay(5); if(COL2 == 0) key = 8; }
if(COL3 == 0) { delay(5); if(COL3 == 0) key = 9; }
if(COL4 == 0) { delay(5); if(COL4 == 0) key = 12; }
ROW1 = ROW2 = ROW3 = 0; ROW4 = 1;
if(COL1 == 0) { delay(5); if(COL1 == 0) key = 15; }
if(COL2 == 0) { delay(5); if(COL2 == 0) key = 0; }
if(COL3 == 0) { delay(5); if(COL3 == 0) key = 14; }
if(COL4 == 0) { delay(5); if(COL4 == 0) key = 13; }
return key;
}
void main() {
unsigned char key = 0, num = 0;
while(1) {
key = getKey();
if(key != 0) {
if(key < 10) num = key; // 数字键
else if(key == 12) num = 10; // A键
else if(key == 9) num = 11; // B键
else if(key == 13) num = 12; // C键
else if(key == 14) num = 13; // D键
else if(key == 15) num = 14; // *键
else if(key == 11) num = 15; // #键
P0 = numCode[num]; // 数码管显示数字
}
}
}
```
这个代码使用了一个4x4的矩阵按键来输入数字,然后将数字转换成对应的数码管字符编码进行显示。其中,getKey()函数用来获取按下的按键值,numCode[]数组用来存储数码管字符编码,delay()函数用来进行延时。在主函数中,读取按键值后将其转换成对应的数字,然后将数字的字符编码输出到数码管中进行显示。
阅读全文