交通灯控制实验程序
时间: 2023-10-10 22:04:31 浏览: 79
以下是一个简单的交通灯控制实验程序,基于51单片机和Keil C编译器:
```c
#include <reg52.h>
#define red_light P1_0
#define yellow_light P1_1
#define green_light P1_2
#define button P3_2
unsigned char state = 0; // 交通灯状态,0表示红灯,1表示绿灯
void timer0_init() {
TMOD |= 0x01; // 设置为模式1,16位定时器
TH0 = 0x3C; // 设置计数初值,65536-50000=15536,即0x3C00+0x3C=0x3C3C
TL0 = 0x3C;
ET0 = 1; // 开启定时器0中断
TR0 = 1; // 启动定时器0
EA = 1; // 开启总中断
}
void timer0_isr() interrupt 1 {
static unsigned char cnt = 0; // 计数器,用于控制交通灯的状态
TH0 = 0x3C; // 重新设置计数初值
TL0 = 0x3C;
cnt++; // 每次中断计数器加1
switch (state) {
case 0: // 红灯
if (cnt == 30) { // 500ms
red_light = 0; // 红灯熄灭
yellow_light = 1; // 黄灯亮起
} else if (cnt == 33) { // 550ms
yellow_light = 0; // 黄灯熄灭
green_light = 1; // 绿灯亮起
cnt = 0; // 计数器清零
state = 1; // 状态改为绿灯
}
break;
case 1: // 绿灯
if (cnt == 50) { // 1s
green_light = 0; // 绿灯熄灭
yellow_light = 1; // 黄灯亮起
} else if (cnt == 53) { // 1.1s
yellow_light = 0; // 黄灯熄灭
red_light = 1; // 红灯亮起
cnt = 0; // 计数器清零
state = 0; // 状态改为红灯
}
break;
}
}
void main() {
button = 1; // 按键输入口上拉
red_light = 1; // 初始状态为红灯
yellow_light = 0;
green_light = 0;
timer0_init(); // 初始化定时器0
while (1) {
if (button == 0) { // 按键按下,强制将交通灯状态改为绿灯
state = 1;
}
}
}
```
该程序实现了一个简单的交通灯控制系统,红灯亮30次(500ms),黄灯亮3次(50ms),绿灯亮50次(1s),黄灯亮3次(50ms),循环执行。按下按键时,会强制将交通灯状态改为绿灯,方便调试。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)