程序:
//共阴数码管
//0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71 //0-F的码表
//共阳数码管
//0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e //0-F的码表
#include "reg51.h"
#define SMG_PORT P0
#define KEY_PORT P2
#define uchar unsigned char
sbit LED=P1^0;
uchar code dis[17]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00};
//unsigned char code dis[16]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void delay_ms(int a)
{
int i=0,j=0;
for(i=0;i<a;i++)
for(j=0;j<118;j++);// 1ms
}
uchar Scan_Button(void)
{
uchar i=0,count=0,temp, LINE[4] = {0xef, 0xdf, 0xbf, 0x7f}; //1110 1111
KEY_PORT=0xff;
for(i=0;i<4;i++)
{
KEY_PORT = LINE[i]; //
delay_ms(20);
temp = 0x01;
for(count=0;count<4;count++)
{
if(!(KEY_PORT&temp))//按键按下时!P2&temp为1,进入if // 1110 1110 & 0000 0010 =0000 0000
{
SMG_PORT=dis[count+i*4];
while(!(KEY_PORT&temp)); //松开
return (count+i*4);
}
temp <<= 1;//左移一位 // 0x02 0000 0010
}
}
SMG_PORT=dis[16];
return 0xff;
}
int main(void)
{
LED=1;
while(1)
{
if(0xff!=Scan_Button())
LED=0;
else
LED=1;
}
return 0;
}