矩阵键盘先扫描行再扫描列如何让数码管显示出0-F的代码
时间: 2023-10-15 08:02:09 浏览: 44
矩阵键盘的扫描可以分为两步,先扫描行,再扫描列。当按下某个按键时,会在某一行和某一列交叉的位置形成一个矩阵,可以通过判断行和列的状态来确定按下的是哪个按键。
以下是一个简单的示例代码,演示如何通过矩阵键盘输入0-F,并显示在数码管上:
```c
#include <reg52.h>
// 数码管段选IO口定义
sbit SegA = P1^0;
sbit SegB = P1^1;
sbit SegC = P1^2;
sbit SegD = P1^3;
sbit SegE = P1^4;
sbit SegF = P1^5;
sbit SegG = P1^6;
sbit SegDP = P1^7;
// 矩阵键盘行列IO口定义
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;
// 数码管显示0-F的数组
unsigned char digit[16] = {
0x3F, 0x06, 0x5B, 0x4F,
0x66, 0x6D, 0x7D, 0x07,
0x7F, 0x6F, 0x77, 0x7C,
0x39, 0x5E, 0x79, 0x71
};
// 获取按下的键值
unsigned char GetKey(void)
{
unsigned char key = 0xFF; // 默认没有按键按下
// 扫描第一行
Row1 = 0;
if (Col1 == 0) key = 1;
if (Col2 == 0) key = 2;
if (Col3 == 0) key = 3;
if (Col4 == 0) key = 0;
Row1 = 1;
// 扫描第二行
Row2 = 0;
if (Col1 == 0) key = 4;
if (Col2 == 0) key = 5;
if (Col3 == 0) key = 6;
if (Col4 == 0) key = 0;
Row2 = 1;
// 扫描第三行
Row3 = 0;
if (Col1 == 0) key = 7;
if (Col2 == 0) key = 8;
if (Col3 == 0) key = 9;
if (Col4 == 0) key = 0;
Row3 = 1;
// 扫描第四行
Row4 = 0;
if (Col1 == 0) key = 0x0A; // A
if (Col2 == 0) key = 0x0B; // B
if (Col3 == 0) key = 0x0C; // C
if (Col4 == 0) key = 0x0D; // D
Row4 = 1;
return key;
}
// 数码管显示函数
void ShowDigit(unsigned char num)
{
SegA = (digit[num] & 0x01) ? 0 : 1;
SegB = (digit[num] & 0x02) ? 0 : 1;
SegC = (digit[num] & 0x04) ? 0 : 1;
SegD = (digit[num] & 0x08) ? 0 : 1;
SegE = (digit[num] & 0x10) ? 0 : 1;
SegF = (digit[num] & 0x20) ? 0 : 1;
SegG = (digit[num] & 0x40) ? 0 : 1;
SegDP = (digit[num] & 0x80) ? 0 : 1;
}
void main()
{
unsigned char key;
while (1) {
key = GetKey();
if (key != 0xFF) {
ShowDigit(key);
}
}
}
```
以上代码中,`GetKey()`函数用于获取按下的键值,`ShowDigit()`函数用于将键值对应的数字显示在数码管上。在`main()`函数中,不断循环调用`GetKey()`函数,如果有按键按下,则将对应的数字显示在数码管上。其中,`digit[]`数组中存储了0-F各个数字的段选状态,通过位运算控制每个数码管的每个段的亮灭状态。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)