#include<reg51.h>
sbit p30=P3^0;
sbit p31=P3^1;
sbit p34=P3^4;
sbit p35=P3^5;
sbit p36=P3^6;
sbit p37=P3^7;
sbit p00=P0^0;
sbit p01=P0^1;
sbit p02=P0^2;
sbit p03=P0^3;
sbit p04=P0^4;
sbit p05=P0^5;
sbit p06=P0^6;
sbit p07=P0^7;
//LED字模
char LedNum[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
//南北初始化等待时间
short initNbGreen=30;
short initNbRed=30;
//南北灯标志:0 绿灯 1 红灯 2黄灯
short NbFlag=0;
//南北等待时间
short NbTime=30;
//东西初始化等待时间
short initDxGreen=30;
short initDxRed=30;
//东西灯标志:0 绿灯 1 红灯 2黄灯
short DxFlag=1;
//东西等待时间
short DxTime=33;
//夜间模式和绿灯模式
char nightMode=0;
char greenMode=0;
//延时函数
void delay(unsigned short N) //@12.000MHz
{
for(;N>0;N--){
unsigned char i, j;
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
};
}
//定时器0 减少等待时间
int count=0;
int countYellow=0;
void addTime() interrupt 1{
if(nightMode==1){
p00=0;p02=0;
p03=0;p05=0;
if(++countYellow%1000==0){
countYellow=0;p01=!p01;p04=!p04;
}
return;
}else if(greenMode==1){
p00=1;p01=0;p02=0;
p03=0;p04=0;p05=1;
return;
}
if(count%2500==0){ //控制黄灯闪烁
if(NbFlag==2){
p01=!p01;
}
if(DxFlag==2){
p04=!p04;
}
}
if(++count==5000){
count=0;
NbTime--;
DxTime--;
if(NbTime==0){
if(NbFlag==0){
NbFlag=2;
p00=0;p01=1;p02=0;
NbTime=3;
}else if(NbFlag==1){
NbFlag=0;
p00=1;p01=0;p02=0;
NbTime=initNbGreen;
}else if (NbFlag==2){
NbFlag=1;
p00=0;p01=0;p02=1;
NbTime=initNbRed+3;
}
}
if(DxTime==0){
if(DxFlag==0){
DxFlag=2;
p03=0;p04=1;p05=0;
DxTime=3;
}else if(DxFlag==1){
DxFlag=0;
p03=1;p04=0;p05=0;
DxTime=initDxGreen;
}else if (DxFlag==2){
DxFlag=1;
p03=0;p04=0;p05=1;
DxTime=initDxRed+3;
}
}
}
}
//外部中断0 改变红灯时间
void changeNbRed() interrupt 0{
if(p36==0){
if(initNbGreen>3){
initNbRed++;
initNbGreen--;
initDxGreen++;
initDxRed--;
}
}else if(p37==0){
if(initNbRed>3){
initNbRed--;
initNbGreen++;
initDxGreen--;
initDxRed++;
}
}
}
//用于缓存切换模式前红绿灯的状态
char tempLed[6]={0};
//外部中断1 切换模式
void changeMode() interrupt 2{
if(p06==0){
if(greenMode==0){
tempLed[0]=p00;tempLed[1]=p01;tempLed[2]=p02;tempLed[3]=p03;tempLed[4]=p04;tempLed[5]=p05;
}else{
p00=tempLed[0];p01=tempLed[1];p02=tempLed[2];p03=tempLed[3];p04=tempLed[4];p05=tempLed[5];
}
greenMode=!greenMode;
}else if(p07==0){
if(nightMode==0){
tempLed[0]=p00;tempLed[1]=p01;tempLed[2]=p02;tempLed[3]=p03;tempLed[4]=p04;tempLed[5]=p05;
}else{
p00=tempLed[0];p01=tempLed[1];p02=tempLed[2];p03=tempLed[3];p04=tempLed[4];p05=tempLed[5];
}
nightMode=!nightMode;
}
}
void showNB(){
if(nightMode==1 || greenMode==1){
return ;
}
p30=0;
p31=1;
P2=LedNum[NbTime%10];
delay(1);
P2=0xff;
p30=1;
p31=0;
P2=LedNum[NbTime/10];
delay(1);
P2=0xff;
}
void showDX(){
if(nightMode==1 || greenMode==1){
return ;
}
p34=0;
p35=1;
P1=LedNum[DxTime%10];
delay(1);
P1=0xff;
p34=1;
p35=0;
P1=LedNum[DxTime/10];
delay(1);
P1=0xff;
}
int main(void){
//中断初始化
TMOD=0x02;
TR0=1;IT0=1;IT1=1; //TCON寄存器
EA=1;ET0=1;EX0=1;EX1=1; //IE寄存器
TL0=0x38;TL1=0x38; //初始化时间
p00=1;p01=0;p02=0; //南北初始化为绿灯
p03=0;p04=0;p05=1; //东西初始化为红灯
while(1){
showNB();
showDX();
}
}