Preface
Experiment: Through the 4*4 matrix keyboard, after pressing a certain button, the corresponding key number will be displayed on the digital tube. (0~F)
For basic operations, refer to this blog:
Keil
The experiment used a common anode connection method. So the elements in this binary data all share the same anode.
Through line-by-line scanning, assuming that the first line is currently scanned, if there is 0 in the corresponding P1^0~P1^3, it means that a key has been pressed in that line. Combined with the if judgment, it can be determined which column it is.
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit L1=P1^0;//定义列
sbit L2=P1^1;
sbit L3=P1^2;
sbit L4=P1^3;
//共阳极字符0~F的段码
uchar dis[16]={0xC0,0XF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E};
uint time;
//延时,放键盘抖动
void delay(uint time);
void main(void){
uchar temp;
uchar i;
while(1){
P1=0xEF;//行扫描初值1110 1111(扫描P1^4)
for(i=0;i<4;i++){//逐行为低,按行扫描,一共4行
if(L1==0)P0=dis[i*4+0];//判断第一列有无键被按下
if(L2==0)P0=dis[i*4+1];//判断第二列有无键被按下
if(L3==0)P0=dis[i*4+2];//判断第三列有无键被按下
if(L4==0)P0=dis[i*4+3];//判断第四列有无键被按下
delay(500);//延时
temp=P1;//读入P1口的状态
temp=temp|0x0F;//将P1^3~P1^0为1
temp=temp<<1;//左移,准备扫描下一行
temp=temp|0x0F;
P1=temp;//为扫描下一行做准备
}
}
}
//软件消除抖动,延时
void delay(uint time){
uint i;
for(i=0;i<time;i++);
}
Proteus
I believe that everyone is already familiar with it, so I will just put the schematic diagram.
Required devices
Component name | Proteus keyword |
51 microcontroller | AT89C51 |
reset button | BUTTON |
resistance | RES |
Common anode eight-bit digital tube | 7SEG-MPX1-CA |
power supply | POWER |
Matrix keyboard
Summarize
Keep up the good work! ! !