智能交通灯————单片机

#include
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
unsigned char code LedChar[] = {
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E
};
unsigned char LedBuff[7] = {
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
bit flagls = 1;
unsigned char T0RH = 0;
unsigned char T0RL = 0;
void ConfigTimer0(unsigned int ms);
void TrafficLight();
void ConfigUART(unsigned int baud);
unsigned char timer1,timer2,timer3;
unsigned char L;
unsigned char ch1=‘r’,ch2=‘y’,ch3=‘g’;
void main()
{
EA = 1;
ConfigUART(9600);
ENLED = 0;
ADDR3 = 1;
ConfigTimer0(1);
while(1)
{
if(flagls)
{
flagls = 0;
TrafficLight();
if(LedBuff[6]==0xFC) //红
SBUF=ch1;
if(LedBuff[6]==0xE7) //黄
SBUF=ch2;
if(LedBuff[6]==0x3F) //绿
SBUF=ch3;
}
}
}
void ConfigTimer0(unsigned int ms)
{
unsigned long tmp;
tmp = 11059200/12;
tmp = (tmp * ms)/1000;
tmp = 65535 - tmp;
tmp = tmp+13;
T0RH = (unsigned char)(tmp>>8);
T0RL = (unsigned char )tmp;
TMOD &= 0xF0;
TMOD |= 0x01;
TH0 = T0RH;
TL0 = T0RL;
ET0 = 1;
TR0 = 1;
}
void TrafficLight()
{
static unsigned char color = 2;
static unsigned char timer = 0;

if(timer == 0)
{
switch(color)
{
case 0:
color = 1;
timer = timer1;
LedBuff[6] = 0xE7; //黄
break;
case 1:
color = 2;
timer =timer2;
LedBuff[6] = 0xFC; //红
break;
case 2:
color = 0;
timer = timer3;
LedBuff[6] = 0x3F; //绿
break;
default:
break;
}

}
else
{
timer–;
}
LedBuff[0] = LedChar[timer%10];
LedBuff[1] = LedChar[timer/10];
}

void LedScan()
{
static unsigned char i=0;
P0=0xFF;
P1=(P1&0xF8)|i;
P0=LedBuff[i];
if(i<6)
i++;
else
i=0;
}
void InterruptTimer0() interrupt 1
{
static unsigned int tmrls=0;
TH0=T0RH;
TL0=T0RL;
LedScan();
tmrls++;
if(tmrls>=1000)
{
tmrls =0;
flagls=1;
}
}
/串口配置函数/
void ConfigUART(unsigned int baud)
{
SCON=0x50;
TMOD&=0x0F;
TMOD|=0x20;
TH1=256-(11059200/12/32)/baud;
TL1=TH1;
ET1=0;
ES=1;
TR1=1;
}
/UART中断服务函数/
void InterruptUART()interrupt 4
{
unsigned char ch;
static unsigned int Rec=0;

if(RI)
{
	RI=0;
	 ch=SBUF;

	 
	if(ch==0)
{	timer1=4;	//黄
	timer2=34;	   //红
	timer3=29;	   //绿
}
	 
	 switch(Rec)
	 {
	 case 0: if(ch==0xeb)
	          Rec=1;
	         else Rec=0;   break;
	 case 1:  L=ch;
	           Rec=2;	break;
	 case 2:
			 if(L==0x01)  //绿
			 timer3=ch;
			 if(L==0x02)	// 红
			 timer2=ch;
			 if(L==0x03)	 //黄
			 timer1=ch;	
			 Rec=0; break;
	  default: Rec=0;
	 }
	
}
if(TI)
{
	TI=0;

}

}

你可能感兴趣的:(智能交通灯————单片机)