📄 数码管显示4x4键盘矩阵按键.c
字号:
#include <reg52.h>
#define uint unsigned int //宏定义
#define uchar unsigned char
unsigned code duan[] = {0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,
0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71,0}; //单个7段数码管段选编码,最后的0让它一开始显示0
uint count,num;
uchar temp;
void delay() //延时函数大约20毫秒
{
int x=2000;
while(x--);
}
uchar key_scan()
{
P1=0Xef; //第一行置0,扫描第一列
temp=P1;
temp=temp&0x0f; //屏蔽高4位,读取列值
while(temp!=0x0f) //判断键盘是否有按下
{
delay(); //按键防抖动
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
temp=P1;
switch(temp)
{
case 0xee: num=0;
break;
case 0xed: num=1;
break;
case 0xeb: num=2;
break;
case 0xe7: num=3;
break;
}
while(temp!=0x0f) //松手检测
{
temp=P1;
temp=temp&0x0f;
}
}
}
P1=0Xdf; //第2行置0,扫描第2列
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
delay(); //按键防抖动
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
temp=P1;
switch(temp)
{
case 0xde: num=4;
break;
case 0xdd: num=5;
break;
case 0xdb: num=6;
break;
case 0xd7: num=7;
break;
}
while(temp!=0x0f) //松手检测
{
temp=P1;
temp=temp&0x0f;
}
}
}
P1=0Xbf; //第3行置0,扫描第3列
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
delay(); //按键防抖动
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
temp=P1;
switch(temp)
{
case 0xbe: num=8;
break;
case 0xbd: num=9;
break;
case 0xbb: num=10;
break;
case 0xb7: num=11;
break;
}
while(temp!=0x0f) //松手检测
{
temp=P1;
temp=temp&0x0f;
}
}
}
P1=0X7f; //第4行置0,扫描第4列
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
delay(); //按键防抖动
temp=P1;
temp=temp&0x0f;
while(temp!=0x0f)
{
temp=P1;
switch(temp)
{
case 0x7e: num=12;
break;
case 0x7d: num=13;
break;
case 0x7b: num=14;
break;
case 0x77: num=15;
break;
}
while(temp!=0x0f) //松手检测
{
temp=P1;
temp=temp&0x0f;
}
}
}
return num; //传回num的数值
}
void main()
{
count=16; //使得P0=duan[16],即显示0
while(1)
{
count=key_scan(); //读回num的数值,赋值给count
P0=duan[count]; //数码管显示
}
}
//注:键盘扫描函数key_scan,还可以利用for循环代码少很多
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -