#include <reg51.h>
#include <INTRINS.H>
unsigned char count; //中断次数计数
unsigned char s; //状态变量
unsigned char sn,ew; //倒计时变量
unsigned char code seg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
//0~9十个数字和共阳型段码
sbit r1=P1^0; //两个方向的红黄绿灯
sbit y1=P1^1;
sbit g1=P1^2;
sbit r2=P1^5;
sbit y2=P1^4;
sbit g2=P1^3;
void delay(unsigned int j)
{
while(j--);
}
display()
{
unsigned char i,wk=0x01;//wk变量作位控,初始选通右边第1位
unsigned char buf[4]; //声明数码管显示字形缓冲数组
buf[0]=seg[sn%10]; //南北方向计时变量
buf[1]=seg[sn/10%10];
buf[2]=seg[ew%10];
buf[3]=seg[ew/10%10];
for (i=0;i<4;i++)
{
P3=wk; //输出位控
P0=buf[i]; //依次输出段码
delay(50); //延时
wk=_crol_(wk,1); //位控左移一位
P0=0xff; //熄灭所有数码管(消隐)
}
}
int main()
{
TMOD=0x01;
TH0=0x3c;
TL0=0xb0;
EA=1;
ET0=1;
TR0=1;
sn=40;
ew=45;
while(1)
{
display();
switch(s)
{
case 0: //状态一
r1=1;y1=1;g1=0;
r2=0;y2=1;g2=1;
if(sn==255) //字符型数据0减1等255
{
sn=4;
s=1;
}
break;
case 1: //状态二
r1=1;y1=0;g1=1;
r2=0;y2=1;g2=1;
if(sn==255)
{
sn=35;
ew=30;
s=2;
}
break;
case 2: //状态三
r1=0;y1=1;g1=1;
r2=1;y2=1;g2=0;
if(ew==255)
{
ew=4;
s=3;
}
break;
case 3: //状态四
r1=0;y1=1;g1=1;
r2=1;y2=0;g2=1;
if(ew==255)
{
sn=40;
ew=45;
s=0;
}
break;
}
}
}
void timer0() interrupt 1
{
TH0=0x3c;
TL0=0xb0;
count++;
if(count==20) //1秒定时
{
count=0;
sn--;
ew--;
}
}
|