|
Ardunio 入门教程-实验九 模拟交通信号灯
实验用到的元件
实验用到的元件,红‘绿’黄 LED各一个 ,3个470欧姆的电阻,1个10K欧姆电阻,1个轻触,6根杜邦线,一块实验板。
原理图
连接图
3个LED自由闪烁 当 按住轻触开关 停止闪烁。
实验演示视频:
代码:- // Project 5
- int redPin = 2;
- int yellowPin = 3;
- int greenPin = 4;
- int buttonPin = 5;
- int state = 0;
- void setup()
- {
- pinMode(redPin, OUTPUT);
- pinMode(yellowPin, OUTPUT);
- pinMode(greenPin, OUTPUT);
- pinMode(buttonPin, INPUT);
- }
- void loop()
- {
- if (digitalRead(buttonPin))
- {
- if (state == 0)
- {
- setLights(HIGH, LOW, LOW);
- state = 1;
- }
- else if (state == 1)
- {
- setLights(HIGH, HIGH, LOW);
- state = 2;
- }
- else if (state == 2)
- {
- setLights(LOW, LOW, HIGH);
- state = 3;
- }
- else if (state == 3)
- {
- setLights(LOW, HIGH, LOW);
- state = 0;
- }
- delay(1000);
- }
- }
- void setLights(int red, int yellow, int green)
- {
- digitalWrite(redPin, red);
- digitalWrite(yellowPin, yellow);
- digitalWrite(greenPin, green);
- }
-
复制代码 |
|