51单片机交通红绿灯控制 能设定红绿灯工作时间。能显示工作时,红绿灯倒计时时间。紧急情况下,按下按钮实现两个方向的交通灯全红。编程代码
时间: 2024-04-01 15:37:25 浏览: 81
以下是一个简单的51单片机交通红绿灯控制的程序,其中可以设定红绿灯工作时间,可以显示工作时,红绿灯倒计时时间,可以在紧急情况下按下按钮实现两个方向的交通灯全红:
```
#include <reg51.h>
sbit red1 = P1^0; //第一组红灯
sbit yellow1 = P1^1; //第一组黄灯
sbit green1 = P1^2; //第一组绿灯
sbit red2 = P1^3; //第二组红灯
sbit yellow2 = P1^4; //第二组黄灯
sbit green2 = P1^5; //第二组绿灯
sbit button = P3^2; //紧急情况按钮
unsigned char time1 = 10; //第一组红绿灯工作时间
unsigned char time2 = 10; //第二组红绿灯工作时间
unsigned char count1 = 0; //第一组红绿灯倒计时时间
unsigned char count2 = 0; //第二组红绿灯倒计时时间
void delay(unsigned int time); //延时函数
void emergency(); //紧急情况函数
void main()
{
while(1)
{
//第一组红绿灯控制
red1 = 1;
yellow1 = 0;
green1 = 0;
count1 = time1;
while(count1 > 0)
{
count1--;
//显示倒计时时间
P2 = 0x80 | count1;
delay(1000);
if(button == 0) //紧急情况
{
emergency();
break;
}
}
yellow1 = 1;
delay(2000);
red1 = 0;
yellow1 = 0;
green1 = 1;
count1 = time1;
while(count1 > 0)
{
count1--;
//显示倒计时时间
P2 = 0x80 | count1;
delay(1000);
if(button == 0) //紧急情况
{
emergency();
break;
}
}
yellow1 = 1;
delay(2000);
//第二组红绿灯控制
red2 = 1;
yellow2 = 0;
green2 = 0;
count2 = time2;
while(count2 > 0)
{
count2--;
//显示倒计时时间
P2 = 0x90 | count2;
delay(1000);
if(button == 0) //紧急情况
{
emergency();
break;
}
}
yellow2 = 1;
delay(2000);
red2 = 0;
yellow2 = 0;
green2 = 1;
count2 = time2;
while(count2 > 0)
{
count2--;
//显示倒计时时间
P2 = 0x90 | count2;
delay(1000);
if(button == 0) //紧急情况
{
emergency();
break;
}
}
yellow2 = 1;
delay(2000);
}
}
void delay(unsigned int time)
{
unsigned int i, j;
for(i = 0; i < time; i++)
{
for(j = 0; j < 125; j++);
}
}
void emergency()
{
red1 = 1;
yellow1 = 0;
green1 = 0;
red2 = 1;
yellow2 = 0;
green2 = 0;
delay(5000);
red1 = 0;
yellow1 = 0;
green1 = 1;
red2 = 0;
yellow2 = 0;
green2 = 1;
}
```
在上述代码中,使用了51单片机的定时器来实现延时控制,使用了P2口来显示倒计时时间。在紧急情况下,通过按下P3.2口的按钮来触发emergency()函数,该函数会将两个方向的交通灯都设置为红灯,持续5秒钟后再恢复正常的红绿灯控制。
阅读全文