给你写个程序,经仿真无误。按键和LED端口可按实际电路修改。
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar code table1[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
uchar code table2[]={0x18,0x24,0x42,0x81,0x18,0x24,0x42,0x81};
uchar code table3[]={0x81,0x42,0x24,0x18,0x81,0x42,0x24,0x18};
uchar code table4[]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};
uint Cnt250us=0;
uchar key=0;
void Timer0Init() //250微秒@11.0592MHz
{
TMOD |= 0x02; //设置定时器模式
TL0 = 0x1A; //设置定时初值
TH0 = 0x1A; //设置定时重载值
TF0 = 0; //清除TF0标志
TR0 = 1; //定时器0开始计时
}
void delay(uint xms) //延时子函数
{
uint i,j;
for(i=xms;i>0;i--)
for(j=110;j>0;j--);
}
void key_scan() //按键检测子函数
{
uchar x;
static bit sign=0;
x=P1&0x0f;
if(x!=0x0f) //检测键是否被按下
{
delay(10);
if((x!=0x0f)&&(sign==0))
{
sign=1;
x=P1&0x0f;
switch(x)
{
case 0x0e: key=1; break;
case 0x0d: key=2; break;
case 0x0b: key=3; break;
case 0x07: key=4; break;
}
}
}
else sign=0;
}
void key_service() //按键服务程序
{
static uchar i=0;
if(key!=0)
{
switch(key)
{
case 1:
P2=~table1;
break;
case 2:
P2=~table2;
break;
case 3:
P2=~table3;
break;
case 4:
P2=~table4;
break;
}
i++;
if(i>=8)
i=0;
}
}
void main()
{
Timer0Init();
while(1)
{
key_scan();
if(TF0==1)
{
TF0=0;
Cnt250us++;
if(Cnt250us>=1000)
{
Cnt250us=0;
key_service();
}
}
}
}
|