Try Traffic Light
Try Traffic Light
com/tag/arduino-traffic-light-controller/
Connect the anode (long leg) of each LED to digital pins eight, nine, and ten
(via a 220-ohm resistor). Connect the cathodes (short leg) to the Arduino’s
ground.
void setup(){
pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
}
void loop(){
changeLights();
delay(15000);
}
void changeLights(){
// green off, yellow on for 3 seconds
digitalWrite(green, LOW);
digitalWrite(yellow, HIGH);
delay(3000);
// turn off yellow, then turn red on for 5 seconds
digitalWrite(yellow, LOW);
digitalWrite(red, HIGH);
delay(5000);
// red and yellow on for 2 seconds (red is already on though)
digitalWrite(yellow, HIGH);
delay(2000);
// turn off red and yellow, then turn on green
digitalWrite(yellow, LOW);
digitalWrite(red, LOW);
digitalWrite(green, HIGH);
delay(3000);
}
Upload this code to your Arduino, and run (make sure to select the correct
board and port from the Tools > Board and Tools > Port menus). You
should have a working traffic light that changes every 15 seconds, like this
(sped up):
Check output:
Let’s break down this code. The changeLights function performs all the
hard work. This rotates the traffic light through yellow and red, then back to
green. As this gets called inside the loop function, the Arduino will run this
code forever, with a 15-second pause every time.
These four steps replicate the process used in real traffic lights. For each
step, the code is very similar. The appropriate LED gets turned on or of
using digitalWrite. This is an Arduino function used to set output pins to
HIGH (for on), or LOW (for of).
After enabling or disabling the required LEDs, the delay makes the Arduino
wait for a given amount of time. Three seconds in this case.