#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit RED_1=P0^0; //东西向灯
sbit YELLOW_1=P0^1;
sbit GREEN_1=P0^2;
sbit RED_2=P0^3; //南北向灯
sbit YELLOW_2=P0^4;
sbit GREEN_2=P0^5;
uchar number=0,type=1; //闪烁次数,操作类型变量
//延时子程序
void Delay(uint x)
{
uchar i;
while(x--) for(i=0;i<120;i++);
}
//交通灯切换程序
//总共分为四种情况,如此循环
//注:1为关灯,0为开灯
traffic()
{
switch(type)
{
case 1: //东西向绿灯与南北向红灯亮5秒
RED_1=1;YELLOW_1=1;GREEN_1=0;
RED_2=0;YELLOW_2=1;GREEN_2=1;
Delay(5000);
type=1;
break;
case 2: //东西向、南北向黄灯闪烁2秒
Delay(500);
YELLOW_1=~YELLOW_1;GREEN_1=1;
YELLOW_2=~YELLOW_2;RED_2=1;
if(++number!=4) return; //闪烁2次
number=0;
type=2;
break;
case 3: //东西向红灯,南北向绿灯亮
RED_1=0;YELLOW_1=1;GREEN_1=1;
RED_2=1;YELLOW_2=1;GREEN_2=0;
Delay(5000);
type=3;
break;
}
}
void main()
{
while(1) traffic();
}
|