利用矩阵键盘扫描法、线反法的原理编写一段程序实现以下功能: 依次按下4*4 矩阵键盘上从第1 到第20 个键,同时在六位数码管上依次显示0、1、2、3、4、5、6、7、8、9、A、B、C、D、E、F。
时间: 2023-09-17 12:13:01 浏览: 80
以下是一个基于51单片机的程序,实现矩阵键盘扫描和六位数码管显示:
```
#include <reg51.h>
// 定义数码管控制端口
sbit DIG1 = P3^2;
sbit DIG2 = P3^3;
sbit DIG3 = P3^4;
sbit DIG4 = P3^5;
sbit DIG5 = P3^6;
sbit DIG6 = P3^7;
// 定义数码管段选端口(共阴极)
unsigned char code LED[16] = {
0xC0, // '0'
0xF9, // '1'
0xA4, // '2'
0xB0, // '3'
0x99, // '4'
0x92, // '5'
0x82, // '6'
0xF8, // '7'
0x80, // '8'
0x90, // '9'
0x88, // 'A'
0x83, // 'B'
0xC6, // 'C'
0xA1, // 'D'
0x86, // 'E'
0x8E // 'F'
};
// 定义矩阵键盘端口
sbit ROW1 = P2^0;
sbit ROW2 = P2^1;
sbit ROW3 = P2^2;
sbit ROW4 = P2^3;
sbit COL1 = P2^4;
sbit COL2 = P2^5;
sbit COL3 = P2^6;
sbit COL4 = P2^7;
// 定义变量
unsigned char key; // 按键值
unsigned char digit[6] = {0}; // 数码管显示值
// 延时函数
void delay(unsigned int t) {
unsigned int i, j;
for (i = 0; i < t; i++) {
for (j = 0; j < 125; j++);
}
}
// 数码管扫描函数
void display(unsigned char *digit) {
unsigned char i, j, temp;
unsigned char code DIG[6] = {DIG1, DIG2, DIG3, DIG4, DIG5, DIG6};
for (i = 0; i < 6; i++) {
temp = digit[i];
for (j = 0; j < 8; j++) {
if (temp & 0x01) {
DIG[i] = 1;
} else {
DIG[i] = 0;
}
temp >>= 1;
}
}
}
// 矩阵键盘扫描函数
unsigned char scan() {
unsigned char i, j, k;
unsigned char code table[4][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 0xA, 0xB},
{0xC, 0xD, 0xE, 0xF}
};
ROW1 = 0; ROW2 = 1; ROW3 = 1; ROW4 = 1;
if (COL1 == 0) {delay(10); if (COL1 == 0) {i = 0; j = 0;}}
if (COL2 == 0) {delay(10); if (COL2 == 0) {i = 0; j = 1;}}
if (COL3 == 0) {delay(10); if (COL3 == 0) {i = 0; j = 2;}}
if (COL4 == 0) {delay(10); if (COL4 == 0) {i = 0; j = 3;}}
ROW1 = 1; ROW2 = 0; ROW3 = 1; ROW4 = 1;
if (COL1 == 0) {delay(10); if (COL1 == 0) {i = 1; j = 0;}}
if (COL2 == 0) {delay(10); if (COL2 == 0) {i = 1; j = 1;}}
if (COL3 == 0) {delay(10); if (COL3 == 0) {i = 1; j = 2;}}
if (COL4 == 0) {delay(10); if (COL4 == 0) {i = 1; j = 3;}}
ROW1 = 1; ROW2 = 1; ROW3 = 0; ROW4 = 1;
if (COL1 == 0) {delay(10); if (COL1 == 0) {i = 2; j = 0;}}
if (COL2 == 0) {delay(10); if (COL2 == 0) {i = 2; j = 1;}}
if (COL3 == 0) {delay(10); if (COL3 == 0) {i = 2; j = 2;}}
if (COL4 == 0) {delay(10); if (COL4 == 0) {i = 2; j = 3;}}
ROW1 = 1; ROW2 = 1; ROW3 = 1; ROW4 = 0;
if (COL1 == 0) {delay(10); if (COL1 == 0) {i = 3; j = 0;}}
if (COL2 == 0) {delay(10); if (COL2 == 0) {i = 3; j = 1;}}
if (COL3 == 0) {delay(10); if (COL3 == 0) {i = 3; j = 2;}}
if (COL4 == 0) {delay(10); if (COL4 == 0) {i = 3; j = 3;}}
if (i == 255) {
return 255;
} else {
return table[i][j];
}
}
void main() {
unsigned char i;
while (1) {
for (i = 0; i < 16; i++) {
key = scan(); // 扫描键盘
if (key != 255) {
digit[0] = LED[i];
digit[1] = LED[i];
digit[2] = LED[i];
digit[3] = LED[i];
digit[4] = LED[i];
digit[5] = LED[i];
display(digit); // 显示数字
while (scan() != 255); // 等待按键释放
}
}
}
}
```
程序的原理是每次循环扫描矩阵键盘,如果检测到按键按下,则将相应的数字转换成段码,存储到`digit`数组中,然后调用`display`函数显示在数码管上。程序循环16次,依次显示0~F。
阅读全文