51单片机交通灯数码管倒计时
时间: 2023-06-17 07:08:51 浏览: 178
以下是一个基于51单片机的交通灯倒计时程序:
```c
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit beep = P1^5;
sbit red_light = P2^2;
sbit yellow_light = P2^1;
sbit green_light = P2^0;
sbit digit1 = P0^4;
sbit digit2 = P0^5;
sbit digit3 = P0^6;
sbit digit4 = P0^7;
sbit seg_a = P1^0;
sbit seg_b = P1^1;
sbit seg_c = P1^2;
sbit seg_d = P1^3;
sbit seg_e = P1^4;
sbit seg_f = P1^6;
sbit seg_g = P1^7;
uchar code table[] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
};
void delay(uint t) {
uint i, j;
for (i = 0; i < t; i++) {
for (j = 0; j < 110; j++);
}
}
void display(uint num) {
digit1 = digit2 = digit3 = digit4 = 1;
P0 = table[num % 10];
digit1 = 0; delay(5);
P0 = table[num / 10 % 10];
digit2 = 0; delay(5);
P0 = table[num / 100 % 10];
digit3 = 0; delay(5);
P0 = table[num / 1000 % 10];
digit4 = 0; delay(5);
}
void main() {
uchar i;
uint time;
while (1) {
for (i = 30; i > 0; i--) {
red_light = 1; yellow_light = 0; green_light = 0;
display(i);
if (i == 3) beep = 0;
delay(1000);
}
for (i = 5; i > 0; i--) {
red_light = 1; yellow_light = 1; green_light = 0;
display(i);
if (i == 4) beep = 0;
delay(1000);
}
for (i = 30; i > 0; i--) {
red_light = 0; yellow_light = 0; green_light = 1;
display(i);
delay(1000);
}
for (i = 5; i > 0; i--) {
red_light = 0; yellow_light = 1; green_light = 0;
display(i);
delay(1000);
}
}
}
```
其中,`delay()` 函数用于延时一定的时间,`display()` 函数用于在数码管上显示倒计时数字。程序通过循环控制交通灯的倒计时,每个循环中包括红灯倒计时、红黄灯倒计时、绿灯倒计时和黄灯倒计时四个阶段。同时,在倒计时到达一定时间时,程序会发出蜂鸣声提醒。
阅读全文