求一个基于51单片机的交通灯程序,带倒计时功能
发布网友
发布时间:2022-04-30 20:12
我来回答
共1个回答
热心网友
时间:2023-10-10 06:45
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit RED_A=P3^0; //东西向指示灯
sbit YELLOW_A=P3^1;
sbit GREEN_A=P3^2;
sbit RED_B=P3^3; //南北向指示灯
sbit YELLOW_B=P3^4;
sbit GREEN_B=P3^5;
sbit KEY1=P1^0;
sbit KEY2=P1^1;
sbit KEY3=P1^2;
//延时倍数,闪烁次数,操作类型变量
uchar Flash_Count=0,Operation_Type=1,LEDsng,LEDsns,LEDewg,LEDews,discnt;
uint Time_Count=0,time;
uchar ledtab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0xff};
void displaysn()
{
LEDsng=((time-Time_Count)/20)%10;
LEDsns=((time-Time_Count)/20)/10;
LEDewg=0x10;
LEDews=0x10;
}
void displayew()
{
LEDewg=((time-Time_Count)/20)%10;
LEDews=((time-Time_Count)/20)/10;
LEDsng=0x10;
LEDsns=0x10;
}
//定时器0 中断函数
void T0_INT() interrupt 1
{
TH0=(65536-50000)/256;
TL0=(65536-50000)%256;
switch(Operation_Type)
{
case 1: //东西向绿灯与南北向红灯亮
if((Time_Count%20)==0)displayew();
RED_A=0;YELLOW_A=0;GREEN_A=1;
RED_B=1;YELLOW_B=0;GREEN_B=0;
if(++Time_Count!=time) return;
Time_Count=0;
Operation_Type=2;
break;
case 2: //东西向黄灯开始闪烁,绿灯关闭
LEDewg=0x0;
LEDews=0x0;
if(++Time_Count!=8) return;
Time_Count=0;
YELLOW_A=~YELLOW_A;GREEN_A=0;
if(++Flash_Count!=6) return; //闪烁
Flash_Count=0;
Operation_Type=3;
break;
case 3: //东西向红灯与南北向绿灯亮
if((Time_Count%20)==0)displaysn();
RED_A=1;YELLOW_A=0;GREEN_A=0;
RED_B=0;YELLOW_B=0;GREEN_B=1;
if(++Time_Count!=time) return;
Time_Count=0;
Operation_Type=4;
break;
case 4: //南北向黄灯开始闪烁,绿灯关闭
LEDsng=0x0;
LEDsns=0x0;
if(++Time_Count!=8) return;
Time_Count=0;
YELLOW_B=~YELLOW_B;GREEN_A=0;
if(++Flash_Count!=6) return; //闪烁
Flash_Count=0;
Operation_Type=1;
break;
}
}
void t1_isr() interrupt 3
{
TR1=0;
TH1=(65536-3000)/256;
TL1=(65536-3000)%256;
TR1=1;
switch(discnt)
{
case 0:
P2=0x02;
P0=ledtab[LEDewg];
break;
case 1:
P2=0x01;
P0=ledtab[LEDews];
break;
case 2:
P2=0x08;
P0=ledtab[LEDsng];
break;
case 3:
P2=0x04;
P0=ledtab[LEDsns];
break;
default:discnt=0;break;
}
discnt++;
discnt&=0x03;
}
void delay()
{
uint i;
for(i=0;i<1000;i++);
}
//主程序
void main()
{
TMOD=0x11; //T0 方式1
EA=1;
ET0=1;
TR0=1;
TH1=(65536-3000)/256;
TL1=(65536-3000)%256;
TR1=1;
ET1=1;
time=120;
Time_Count=100;
Time_Count=0;
Operation_Type=1;
while(1)
{
if(KEY1==0) //按一下加1S
{
delay();
if(KEY1==0)
{
while(KEY1==0);
TR0=0;
time+=20;
LEDsng=(time/20)%10;
LEDsns=(time/20)/10;
LEDewg=0x10;
LEDews=0x10;
}
}
if(KEY2==0) //按一下减1S
{
delay();
if(KEY2==0)
{
while(KEY2==0);
TR0=0;
time-=20;
if(time==0)time=20;
LEDewg=(time/20)%10;
LEDews=(time/20)/10;
LEDsng=0x10;
LEDsns=0x10;
}
}
if(KEY3==0) //启动
{
delay();
if(KEY3==0)
{
while(KEY2==0);
TR0=1;
Time_Count=0;
}
}
}
}