給你寫了參考程序,按鍵端口按你的實際電路重新定義。
#include <AT89X52.H>
#define uint unsigned int
#define uchar unsigned char
sbit code0=P3^1; //定義發(fā)光管端口
sbit code1=P0^0;
sbit code2=P0^1;
sbit code3=P0^2;
sbit code4=P0^3;
sbit code5=P0^6;
sbit code6=P0^7;
sbit code7=P3^4;
sbit key=P3^7; //定義按鍵端口
uchar code table1[]={0xe7,0xdb,0xbd,0x7e};//花樣跑馬燈數(shù)組
uchar code table2[]={0x7e,0xbd,0xdb,0xe7};
uchar code table3[]={0x00,0xff,0x00,0xff};
uchar Cnt50ms=0; //中斷計時變量
uchar KeySec=0; //鍵值變量(花樣選擇)
uchar j=0; //流水順序變量
void Timer0Init() //50毫秒@12.000MHz
{
TMOD= 0x01; //設(shè)置定時器模式
TL0 = 0xB0; //設(shè)置定時初值
TH0 = 0x3C; //設(shè)置定時初值
TF0 = 0; //清除TF0標志
TR0 = 1; //定時器0開始計時
EA=1; //開總中斷
ET0=1; //開定時器0中斷
}
void PX(uchar i) //寫8位數(shù)據(jù)函數(shù)
{
code0=i&0x01;i>>=1;
code1=i&0x01;i>>=1;
code2=i&0x01;i>>=1;
code3=i&0x01;i>>=1;
code4=i&0x01;i>>=1;
code5=i&0x01;i>>=1;
code6=i&0x01;i>>=1;
code7=i&0x01;
}
void keyscan()
{
static uchar count=0; //計數(shù)變量
static bit key_sign; //按鍵狀態(tài)標志
if(!key) //檢測輸入如果為0
{
count++; //計數(shù)延時消抖
if((count>=200)&&(key_sign==0))
{
key_sign=1; //按鍵狀態(tài)標志置1,防止重復(fù)響應(yīng)
j=0; //流水順序變量清0
KeySec++; //鍵值變量自+1
if(KeySec>=4)
KeySec=0;
}
}
else
{
count=0; //計數(shù)變量清0
key_sign=0;
}
}
void main()
{
Timer0Init();
while(1)
{
keyscan();
if(Cnt50ms>=10)//0.5秒
{
Cnt50ms=0;
switch(KeySec)
{
case 0: PX(0xff); break;
case 1: PX(table1[j]); break;
case 2: PX(table2[j]); break;
case 3: PX(table3[j]); break;
}
j++; //流水順序變量自+1
if(j>=4)
j=0;
}
}
}
void timer0() interrupt 1
{
TL0 = 0xB0; //設(shè)置定時初值
TH0 = 0x3C; //設(shè)置定時初值
Cnt50ms++; //中斷變量Cnt50ms自+1
} |