1.代碼:
#include
typedef unsigned char u8;
typedef unsigned int u16;
sbit seg_sel = P1^4;
sbit bit_sel = P1^5;
#define DATA P0
u8 code seg_tab[]={
0xc0,0xf9,0xa4,0xb0,
0x99,0x92,0x82,0xf8,
0x80,0x90,0x88,0x83,
0xc6,0xa1,0x86,0x8e
};
u8 code bit_tab[]={
0x10,0x20,0x40,0x80,
0x01,0x02,0x04,0x08
};
void delay(u16 num)
{
u16 x,y;
for(x=num; x>0; x--)
for(y=110; y>0; y--)
{
;//延時1ms
}
}
void display_led(u8 which_bit, u8 which_number)
{
bit_sel = 1;//Q[7..0]=D[7..0]
DATA = bit_tab[which_bit];
bit_sel = 0;//BIT[7..0]=0x80
seg_sel = 1;//Q[7..0]=D[7..0]
DATA = seg_tab[which_number];
seg_sel = 0;
delay(2);
}
u8 key_scan (void)
{
u8 temp,temp2;
P2 = 0xf0;//讓P2輸出0xf0
temp = P2;//讀入P2的值
if (temp != 0xf0) //當(dāng)P2讀入的值不等于0xf0
{
delay(5);//延遲5ms
temp = P2;//再讀入P2口的值
if (temp != 0xf0)//如果P2讀入的值不等于
{ //0xf0,就說明有按鍵按下
temp2 = temp & 0xf0;//保留P2讀入值得高四位
P2 = 0x0f;//再讓P2口輸出0x0f
delay(1);
temp = P2;//再讀入P2口的值
temp2 |= temp;//保留此讀入值的低四位
return temp2;
}
//while(P2!=0x0f);
}
}
u8 encode(u8 cod)
{
u8 num;
switch(cod)
{
case 0xee: num = 0;break;
case 0xde: num = 1;break;
case 0xbe: num = 2;break;
case 0x7e: num = 3;break;
case 0xed: num = 4;break;
case 0xdd: num = 5;break;
case 0xbd: num = 6;break;
case 0x7d: num = 7;break;
case 0xeb: num = 8;break;
case 0xdb: num = 9;break;
case 0xbb: num = 10;break;
case 0x7b: num = 11;break;
case 0xe7: num = 12;break;
case 0xd7: num = 13;break;
case 0xb7: num = 14;break;
case 0x77: num = 15;break;
default : break;
}
return num;
}
void main (void)
{
u8 cod,num;
P0 = 0xff;
P1 = 0xff;//端口初始化
seg_sel = 0;//LE禁止鎖存
bit_sel = 0;
while (1)
{
cod = key_scan();//判斷以及編碼
num = encode(cod);//解碼程序。得出數(shù)字
display_led(1, num);//顯示程序
}
}
2.電路圖:
3.效果