Start by defining variables so that you can address the lights by name rather than a number. Start a new Arduino project, and begin with these lines:
int red = 10;
Next, let’s add the setup function, where you'll configure the red, yellow and green LEDs to be outputs. Since you have created variables to represent the pin numbers, you can now refer to the pins by name instead:
void setup(){
The pinMode function configures the Arduino to use a given pin as an output. You have to do this for your LEDs to work at all. Now for the actual logic of the traffic light. Here's the code you need. Add this below your variable definitions and setup function:
void loop(){
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):
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.
The changeLights function consists of four distinct steps:
- Green on, yellow off
- Yellow off, red on
- Yellow on, red on
- Green on, red off, yellow off
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 off using digitalWrite. This is an Arduino function used to set output pins to HIGH (for on), or LOW (for off).
After enabling or disabling the required LEDs, the delay makes the Arduino wait for a given amount of time. Three seconds in this case.
Comments