#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit dula=P2^6;
sbit wela=P2^7;
uchar code table[]={
0x3f,0x06,0x5b,0x4f,
0x66,0x6d,0x7d,0x07,
0x7f,0x6f};
uint key;
uchar a,b,c,Flag=0; 
uint l=100,m=100;
gongneng1();
InitUART();
gongneng2();
matrixkeyscan();
display();
fasong();

gongneng1()
{
   InitUART();
   while(1)
{
   if(Flag==1) 
{
   ES=0; 
   Flag=0;
   SBUF=a; 
   while(!TI); 
   TI=0;
   ES=1; 
}
}
}
 InitUART  (void)
{

    SCON=0x50;		       
    TMOD=0x20;               
    TH1=0xFD; 
	TL1=0xFD;
	PCON=0x00;              
    TR1=1;
	EA=1;                 
    ES=1;                  
} 
 
 void serial() interrupt 4 
{
    P1=SBUF;
    a=SBUF;
    Flag=1;
    RI=0;
}

void delayms(uint xms)
{
	uint i,j;
	for(i=xms;i>0;i--)
		for(j=110;j>0;j--);
}
matrixkeyscan()
{
	uchar temp;
	while(1)
	{
		P3=0xfe;
		temp=P3;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
			delayms(10);
			temp=P3;
			temp=temp&0xf0;
			if(temp!=0xf0)
			{
				temp=P3;
				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=P3;
					temp=temp&0xf0;
				}
				return(key);
			}
		}
		P3=0xfd;
		temp=P3;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
			delayms(10);
			temp=P3;
			temp=temp&0xf0;
			if(temp!=0xf0)
			{
				temp=P3;
				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=P3;
					temp=temp&0xf0;				
				}
				return(key);
			}
		}
		P3=0xfb;
		temp=P3;
		temp=temp&0xf0;
		if(temp!=0xf0)
		{
			delayms(10);
			temp=P3;
			temp=temp&0xf0;
			if(temp!=0xf0)
			{
				temp=P3;
				switch(temp)
				{
					case 0xeb:
					key=8;
					break;
					case 0xdb:
					key=9;
					break;
				}
				while(temp!=0xf0)
				{
					temp=P3;
					temp=temp&0xf0;
				}
				return(key);
			}
		}
	}
}
display()
{
	while(1)
	{
		

		P0=0xfb;
		wela=1;
		wela=0;
		P0=table[a];
		dula=1;
		dula=0;
		delayms(5);

		P0=0xf7;
		wela=1;
		wela=0;
		P0=table[b];
		dula=1;
		dula=0;
		delayms(5);

	}
}
gongneng2()		
{
  	matrixkeyscan();
	a=key;
    c=a;
	fasong();
	matrixkeyscan();
	b=key;
    c=b; 
	fasong();
	display();
	
}
 fasong()
{
   SBUF=c; 
   while(!TI); 
   TI=0;

}


void main(void)
{
   while(1)
   {
   switch(P1)
   {
   	  case 0xfe:
				gongneng1();
				break;
	  case 0xfd:
				gongneng2();
				break;
   }
   }
}