单片机实验(十二)单片机矩阵按键控制数码管

1、实验环境:win732位系统,keil2,proteus7.5sp3。
2、实验目的:学习通过编程单片机矩阵按键控制数码管。
3、实验连接图。
在这里插入图片描述

4、实验代码。

#include <reg52.h>
unsigned char seg7code[]={
    
    0x3f,0x06,0x5b,0x4f,
							0x66,0x6d,0x7d,0x07,
							0x7f,0x6f,0x77,0x7c,
							0x39,0x5e,0x79,0x71};
void delay(int x)
{
    
    
	char i;
	while(x--)
	{
    
    
	for(i=120;i>0;i--);
}
}
void display(unsigned char num)
{
    
    
	P3=seg7code[num];
} 
void keyscan()
{
    
    
	unsigned char temp,key;//diyihang扫描
	P2=0xfe;
	temp=P2;
	temp=temp&0xf0;
	if(temp!=0xf0)
	{
    
    
		delay(10);
		temp=P2;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
    
    
			temp=P2;
			switch(temp)
			{
    
    
				case 0xee:
					key=0;
					break;
				case 0xde:
					key=1;
					break;
				case 0xbe:
					key=2;
					break;
				case 0x7e:
					key=3;
					break;
			}
			while(temp!=0xf0)
			{
    
    
				temp=P2;
				temp=temp&0xf0;
			}
			display(key);
		}
	}
		//di2hang扫描
	P2=0xfd;
	temp=P2;
	temp=temp&0xf0;
	if(temp!=0xf0)
	{
    
    
		delay(10);
		temp=P2;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
    
    
			temp=P2;
			switch(temp)
			{
    
    
				case 0xed:
					key=4;
					break;
				case 0xdd:
					key=5;
					break;
				case 0xbd:
					key=6;
					break;
				case 0x7d:
					key=7;
					break;
			}
			while(temp!=0xf0)
			{
    
    
				temp=P2;
				temp=temp&0xf0;
			}
			display(key);
		}
	}
//di3hang扫描
	P2=0xfb;
	temp=P2;
	temp=temp&0xf0;
	if(temp!=0xf0)
	{
    
    
		delay(10);
		temp=P2;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
    
    
			temp=P2;
			switch(temp)
			{
    
    
				case 0xeb:
					key=8;
					break;
				case 0xdb:
					key=9;
					break;
				case 0xbb:
					key=10;
					break;
				case 0x7b:
					key=11;
					break;
			}
			while(temp!=0xf0)
			{
    
    
				temp=P2;
				temp=temp&0xf0;
			}
			display(key);
		}
	}
//di4hang扫描
	P2=0xf7;
	temp=P2;
	temp=temp&0xf0;
	if(temp!=0xf0)
	{
    
    
		delay(10);
		temp=P2;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
    
    
			temp=P2;
			switch(temp)
			{
    
    
				case 0xe7:
					key=12;
					break;
				case 0xd7:
					key=13;
					break;
				case 0xb7:
					key=14;
					break;
				case 0x77:
					key=15;
					break;
			}
			while(temp!=0xf0)
			{
    
    
				temp=P2;
				temp=temp&0xf0;
			}
			display(key);
		}
	}
}
void main()
{
    
    
	P3=0;
	while(1)
	{
    
    
		keyscan();
	}
}

5、实验结果:
在这里插入图片描述

6、实验体会:
今天,进行了单片机矩阵按键控制数码管的实验,了解了51单片机的矩阵按键如何操作,还学会了连接单片机的最小系统,对单片机的理解进一步加深,有所收获,感觉棒棒哒,继续加油。

猜你喜欢

转载自blog.csdn.net/weixin_43149382/article/details/109962307