arduino的红绿灯倒计时代码
时间: 2024-10-13 15:00:47 浏览: 48
倒计时交通灯
3星 · 编辑精心推荐
Arduino是一种开源电子平台,常用于制作基于数字IO控制硬件的项目。如果你想要编写一个简单的红绿灯倒计时程序,通常会涉及到使用Timer库来定时切换LED灯的颜色。下面是一个基本的示例,假设你有三个LED连接到数字端口:
```cpp
#include <TimerOne.h>
// LED pin connections (replace with your own)
const int led_red = 9;
const int led_green = 10;
const int led_yellow = 11;
TimerOne timer; // Timer object for the delay
void setup() {
pinMode(led_red, OUTPUT);
pinMode(led_green, OUTPUT);
pinMode(led_yellow, OUTPUT);
Serial.begin(9600); // Enable serial communication for debugging
}
void loop() {
// Set initial time (seconds) for each color cycle
int red_time = 5;
int green_time = 3;
int yellow_time = 2;
// Start a loop that alternates colors
while (true) {
if (!timer.isExpired(red_time * 1000)) { // Check if red light time has expired
digitalWrite(led_red, HIGH); // Turn on red
digitalWrite(led_green, LOW);
digitalWrite(led_yellow, LOW);
} else {
timer.restart(); // Reset the timer for red
if (!timer.isExpired(green_time * 1000)) { // Check if green time has expired
digitalWrite(led_red, LOW);
digitalWrite(led_green, HIGH); // Turn on green
digitalWrite(led_yellow, LOW);
} else {
timer.restart(); // Reset the timer for green
if (!timer.isExpired(yellow_time * 1000)) { // Check if yellow time has expired
digitalWrite(led_red, LOW);
digitalWrite(led_green, LOW);
digitalWrite(led_yellow, HIGH); // Turn on yellow
} else {
// Repeat the cycle or start over here
}
}
}
}
}
阅读全文