keil软件中实现3*4矩阵键盘读取键值的代码程序和数码管实现程序
时间: 2024-02-15 22:03:32 浏览: 173
以下是基于Keil软件的3x4矩阵键盘读取键值和数码管实现程序的示例代码:
1. 3x4矩阵键盘读取键值程序:
``` c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit S0 = P1^0; //定义矩阵键盘的4个引脚
sbit S1 = P1^1;
sbit S2 = P1^2;
sbit S3 = P1^3;
sbit D1 = P2^0; //定义数码管的8个引脚
sbit D2 = P2^1;
sbit D3 = P2^2;
sbit D4 = P2^3;
sbit D5 = P2^4;
sbit D6 = P2^5;
sbit D7 = P2^6;
sbit D8 = P2^7;
uchar code KeyValue[3][4] = {{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'}}; //定义键值矩阵
uchar KeyValueScan() //扫描键盘函数
{
uchar i,j,k;
for(i=0;i<4;i++)
{
switch(i)
{
case 0: S0 = 0;S1 = 1;S2 = 1;S3 = 1;break;
case 1: S0 = 1;S1 = 0;S2 = 1;S3 = 1;break;
case 2: S0 = 1;S1 = 1;S2 = 0;S3 = 1;break;
case 3: S0 = 1;S1 = 1;S2 = 1;S3 = 0;break;
}
k = 0;
for(j=0;j<4;j++)
{
if(P1 & (0x01<<j)) k++;
}
if(k==1)
{
if(!(P1 & 0x01))
{
return KeyValue[0][i];
}
else if(!(P1 & 0x02))
{
return KeyValue[1][i];
}
else if(!(P1 & 0x04))
{
return KeyValue[2][i];
}
else if(!(P1 & 0x08))
{
return 'D'; //第四行第四列是D键
}
}
}
return 0;
}
void main()
{
uchar key;
while(1)
{
key = KeyValueScan(); //扫描键盘
if(key) P0 = key; //在P0口输出键值
}
}
```
2. 数码管实现程序:
``` c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar led[10] = {0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f}; //定义数码管显示0~9的编码
sbit D1 = P2^0; //定义数码管的8个引脚
sbit D2 = P2^1;
sbit D3 = P2^2;
sbit D4 = P2^3;
sbit D5 = P2^4;
sbit D6 = P2^5;
sbit D7 = P2^6;
sbit D8 = P2^7;
void Delay(uint i) //延时函数
{
while(i--);
}
void main()
{
uchar i = 0;
while(1)
{
D1 = 0;D2 = 1;D3 = 1;D4 = 1; //第一个数码管显示
P0 = led[i%10];
Delay(50000);
D1 = 1;D2 = 0;D3 = 1;D4 = 1; //第二个数码管显示
P0 = led[i/10];
Delay(50000);
D1 = 1;D2 = 1;D3 = 0;D4 = 1; //第三个数码管显示
P0 = led[i/100];
Delay(50000);
D1 = 1;D2 = 1;D3 = 1;D4 = 0; //第四个数码管显示
P0 = led[i/1000];
Delay(50000);
i++;
}
}
```
这两个程序可以结合使用,实现读取键盘输入的数字,并在数码管上显示出来。
阅读全文