#define uchar unsigned char
#define uint unsigned int
#include <reg52.h>
sbit led2_EW = P2^3;
sbit led1_EW = P2^2;
sbit led2_SN = P2^1;
sbit led1_SN = P2^0;
sbit yellow_SN = P1^6; //南北黄灯
sbit red_SN = P1^7; //南北红灯
sbit yellow_EW = P1^2; //东西黄灯
sbit red_EW = P1^3; //东西红灯
bit yellow_SN_Flag; //南北黄灯标志位
bit yellow_EW_Flag; //东西黄灯标志位
char time_EW; //东西方向倒计时单元
char time_SN; //南北方向倒计时单元
uchar EW = 30,SN = 30,EWL = 3,SNL = 3;
uchar EW1 = 30,SN1 = 30,EWL1 = 3,SNL1 = 3;
uchar code table[10] = {0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar code S[9]={0X28,0X48,0X18,0X48,0X82,0X84,0X81,0X84,0x88};
//延时函数
void delay_ms(unsigned int x) //延时ms
{
unsigned int i,j;
for(i = x;i > 0;i--)
for(j = 110;j > 0;j--);
}
//数码管显示
void Display(void)
{
char h,l;
h = time_EW/10;
l = time_EW%10;
P0 = table[l];
led2_EW = 1;
delay_ms(1);
led2_EW = 0;
P0 = table[h];
led1_EW = 1;
delay_ms(1);
led1_EW = 0;
h = time_SN/10;
l = time_SN%10;
P0 = table[l];
led2_SN = 1;
delay_ms(1);
led2_SN = 0;
P0 = table[h];
led1_SN = 1;
delay_ms(1);
led1_SN = 0;
}
//中断
void timer0(void)interrupt 1 using 1
{
static uchar count;
TH0 = (65536-50000) / 256;
TL0 = (65536-50000) % 256;
count++;
if(count == 10)
{
if(yellow_SN_Flag == 1) //测试南北黄灯标志位
{yellow_SN =~yellow_SN;}
if(yellow_EW_Flag == 1) //测试东西黄灯标志位
{yellow_EW =~yellow_EW;}
}
if(count == 20) {
time_EW--;
time_SN--;
if(yellow_SN_Flag == 1) //测试南北黄灯标志位
{yellow_SN =~yellow_SN;}
if(yellow_EW_Flag == 1) //测试东西黄灯标志位
{yellow_EW =~yellow_EW;}
count = 0;
}
}
void main(void)
{
TMOD = 0x01; //定时器工作于方式1
TH0 = (65536 - 50000) / 256; //定时器赋初值
TL0 = (65536 - 50000) % 256;
EA = 1; //CPU开中断总允许
ET0 = 1; //开定时中断
TR0 = 1; //启动定时
time_EW = 3;
time_SN = 3;
while(time_SN >= 0 || time_EW >= 0)
{
yellow_EW_Flag = 0; //东西关黄灯显示信号
P1 = S[8]; //所有路口红灯
Display();
}
while(1)
{
time_EW = EW;
time_SN = SN;
while(time_SN >= 4)
{
yellow_EW_Flag = 0;
P1 = S[0]; //南北通行,东西红灯
Display();
}
P1 = 0x00;
while(time_SN >= 0)
{
yellow_SN_Flag = 1; //南北开黄灯信号位
red_EW = 1; //南北黄灯亮,等待左转信号,东西红灯
Display();
}
EW = EW1;
SN = SN1;
EWL = EWL1;
SNL = SNL1;
time_EW = SN;
time_SN = EW;
while(time_EW >= 4)
{
yellow_SN_Flag = 0; //南北关黄灯显示信号
P1 = S[4]; //东西通行,南北红灯
Display();
}
P1 = 0X00;
while(time_EW >= 0)
{
yellow_EW_Flag = 1; //东西开黄灯信号位
red_SN = 1; //东西黄灯亮,等待左拐信号,南北红灯
Display();
}
EW = EW1;
SN = SN1;
EWL = EWL1;
SNL = SNL1;
}
}