|
//上电南北通行30秒,5秒倒计时亮黄灯,30秒结束,东西通行,后面依次交替,
//增加了2个应急按键,按下S3南北通行30秒,30秒结束时回到应急前的状态,同理按下S2.....
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
#define led P0
sbit s3=P3^5;//南北应急通行
sbit s2=P3^4;//东西应急通行
sbit wei1=P2^1;sbit wei0=P2^0;//数码管位选
sbit red0=P2^5;sbit green0=P2^6;sbit yellow0=P2^7;//南北红绿黄灯
sbit red1=P2^4;sbit green1=P2^2;sbit yellow1=P2^3;//东西红绿黄灯
//uchar code display[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//0 ---- 9,共阳
uchar code display[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00};//共阴数码管0---9,a---f,灭
uchar buf[2]={3,0};//初始显示30
uchar num0,num1;//1s计时
uchar counter0=30;//30s倒计时
uchar counter1=30;//30s倒计时
bit flag1=0;//正常南北东西切换
bit flag2=0;//应急南北东西切换
bit flag3=0;//正常与应急切换,初始为正常
uchar temp;//缓存标记
//==============================================================================================
void time0_init()
{
TMOD=0x11;//定时器0,1均工作于方式1
TH0=(65535-50000)/256;//定时50ms
TL0=(65535-50000)%256;
TH1=(65535-50000)/256;//定时50ms
TL1=(65535-50000)%256;
ET0=ET1=EA=TR0=1;TR1=0;
}
void delay1m(uint x)//毫秒级延时函数
{
uint i,j;
for(i=0;i<x;i++) //连数x次,约 x ms
for(j=0;j<120;j++); //数120 次,约1 ms
}
void scan()//数码管扫描函数
{
wei1=1;wei0=0;led=display[buf[1]];
delay1m(5);led=0x00;
wei1=0;wei0=1;led=display[buf[0]];
delay1m(5);led=0x00;
}
void convert(uchar dat)//将数据转成适合数码管显示的数
{
buf[0]=dat/10;
buf[1]=dat%10;
}
void main()//主函数
{
time0_init();//初始化
while(1)
{
if(flag3==0){convert(counter0);}//正常数据转换
else if(flag3==1){{convert(counter1);}}//应急数据转换
scan();//倒计时显示
//===================================================================================
if((flag1==0)&&(flag3==0))//南北通行
{
red0=green1=yellow0=yellow1=1;green0=red1=0;
if(counter0<=5){yellow0=red1=0;red0=green0=yellow1=green1=1;}
}
else if((flag1==1)&&(flag3==0))//东西通行
{
red1=yellow1=green0=yellow0=1;green1=red0=0;
if(counter0<=5){yellow1=red0=0;red1=green1=yellow0=green0=1;}
}
//===================================================================================
if(s3==0)//南北应急按键
{
delay1m(3);
if(s3==0)
{
TR0=0;flag3=1;flag2=0;
TR1=1;counter1=30;
}while(!s3);
}
if(s2==0)//东西应急按键
{
delay1m(3);
if(s2==0)
{
TR0=0;flag3=flag2=1;
TR1=1;counter1=30;
}while(!s2);
}
//====================================================================================
if((flag2==0)&&(flag3==1))//南北应急通行
{
red0=yellow0=green1=yellow1=1;green0=red1=0;
if(counter1<=5){yellow0=red1=0;red0=green0=yellow1=green1=1;}
}
else if((flag2==1)&&(flag3==1))//东西应急通行
{
red1=yellow1=green0=yellow0=1;green1=red0=0;
if(counter1<=5){yellow1=red0=0;red1=green1=yellow0=green0=1;}
}
}
}
void time0_interrupt()interrupt 1
{
TH0=(65535-50000)/256;//定时50ms
TL0=(65535-50000)%256;
num0++;
if(num0==20)//1s时间
{
num0=0;counter0--;
if(counter0==0){counter0=30;flag1=~flag1;}
}
}
void time1_interrupt()interrupt 3
{
TH1=(65535-50000)/256;//定时50ms
TL1=(65535-50000)%256;
num1++;
if(num1==20)//1s时间
{
num1=0;counter1--;
if(counter1==0){TR0=1;flag3=0;}
}
}
|
|