用三个发光二极管实现红绿灯信号灯的代码
时间: 2024-03-22 22:41:07 浏览: 31
以下是一个基于Arduino的红绿灯信号灯的代码实现:
```c++
int redLed = 13; // 红灯引脚
int yellowLed = 12; // 黄灯引脚
int greenLed = 11; // 绿灯引脚
void setup() {
pinMode(redLed, OUTPUT);
pinMode(yellowLed, OUTPUT);
pinMode(greenLed, OUTPUT);
}
void loop() {
digitalWrite(redLed, HIGH);
digitalWrite(yellowLed, LOW);
digitalWrite(greenLed, LOW);
delay(5000); // 等待5秒钟
digitalWrite(redLed, LOW);
digitalWrite(yellowLed, HIGH);
digitalWrite(greenLed, LOW);
delay(2000); // 等待2秒钟
digitalWrite(redLed, LOW);
digitalWrite(yellowLed, LOW);
digitalWrite(greenLed, HIGH);
delay(5000); // 等待5秒钟
}
```
在这个代码中,我们首先定义了红灯、黄灯、绿灯的引脚,然后在setup()函数中将它们设置为输出模式。在loop()函数中,我们通过 digitalWrite() 函数来控制这三个灯的亮灭。每次循环开始时,红灯亮,其他灯灭;过了5秒钟后,红灯熄灭,黄灯亮;再过2秒钟后,黄灯熄灭,绿灯亮。然后等待5秒钟,开始下一轮循环。
需要注意的是,这个代码只是一个简单的演示,实际应用中可能需要加入更多的逻辑判断和安全保护。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![ms14](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](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_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)
![](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)