Pinterest Stumbleupon Whatsapp
Advertisement

The traffic light is a fun little project, that can be completed in under an hour. Learn how to build your own – using an Arduino – and how to modify the circuit for an advanced model.

Don’t worry if you’ve never used an Arduino before, we have a beginners guide Getting Started With Arduino: A Beginner's Guide Getting Started With Arduino: A Beginner's Guide Arduino is an open-source electronics prototyping platform based on flexible, easy-to use hardware and software. It's intended for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments. Read More .

Note: This is the latest in a series of beginner level tutorials for Arduino, the open source electronics prototyping platform. Here’s a list of the previous articles in the series:

What You Need

Apart from the basic Arduino, you’ll need:

  • Red, yellow and green LEDs.
  • A breadboard.
  • 6 x 220 ? resistors.
  • Connecting wires.
  • 1 x pushbutton switch.
  • 1 x 10k ? resistor

Almost any Arduino will be suitable, providing it has enough pins. Make sure you read our buying guide Arduino Buying Guide: Which Board Should You Get? Arduino Buying Guide: Which Board Should You Get? There are so many different kinds of Arduino boards out there, you'd be forgiven for being confused. Which should you buy for your project? Let us help, with this Arduino buying guide! Read More if you are not sure what model you need. You probably have these parts in your starter kit What's in Your Arduino Starter Kit? [Arduino Beginners] What's in Your Arduino Starter Kit? [Arduino Beginners] Faced with a box full of electronic components, it's easy to be overwhelmed. Here's a guide to exactly what you'll find in your kit. Read More  already.

A Simple Example

Let’s start small. A basic, single traffic light is a good place to start. Here’s the circuit:

Advertisement

arduino_traffic_light

Connect the anode (long leg) of each LED to digital pins eight, nine, and ten (via a 220? resistor). Connect the cathodes (short leg) to Arduino ground.

I used Fritzing to draw these diagrams. Not only is it easy to use, it’s free!

The Code

Start by defining variables so that we can address the lights by name rather than a number. Start a new Arduino project, and begin with these lines:

int red = 10;
int yellow = 9;
int green = 8;

Next, let’s add the setup function, where’ll we 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(){
    pinMode(red, OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green, OUTPUT);
}

That was easy. Now for the difficult part -– the actual logic of a traffic light. Create a separate function for changing the lights (you’ll see why later).

When you first begin programming, the code itself is very rudimentary – it’s figuring out the minute logic details that presents the biggest problem. The key to being a good programmer is to be able to look at any process, and break it down into its fundamental steps. Here’s the rest of the code:

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);
}

Done! Now, upload and run (make sure to select the correct board and port from the Tools > Port and Tools > Board menus). You should have a working traffic light that changes every 15 seconds, like this (sped up):

single_traffic_light

A Pedestrian Crossing

Now that you know the basics, let’s improve it. Add in a pushbutton for pedestrians to change the light whenever they like:

arduino_traffic_light_with_button

Notice how the traffic light is exactly the same as the previous example. Connect the button to digital pin 12. You’ll notice that the switch has a high-impedance 10k? resistor attached to it, and you may be wondering why. This is called a pull-down resistor. It’s a difficult concept to grasp at first, but bear with me.

A switch either lets the current flow, or doesn’t. This seems simple enough, but in a logic circuit, the current should be always flowing in either a high or low state (remember – 1 or 0, high or low). You might assume that a pushbutton switch that isn’t actually being pushed would be defined as being in a low state, but in fact it’s said to be ‘floating’, because no current is being drawn at all.

In this floating state, it’s possible that a false reading will occur as it fluctuates with electrical interference. In other words, a floating switch is giving neither a reliable high, nor low state reading. A pull down resistor keeps a small amount of current flowing when the switch is closed, thereby ensuring an accurate low state reading. In other logic circuits, you may find a pull-up resistor instead – this works on the same principle, but in reverse, making sure that particular logic gate defaults to high.

Now, in the loop part of the code, instead of changing the lights every 15 seconds, we’re going to read the state of the pushbutton switch instead, and only change the lights when it’s activated.

The Code

Start by adding a new variable to the start of the program:

int button = 12; // switch is on pin 12

Now, in the setup function, add a new line to declare the switch as an input. I’ve also added a single line to start the traffic lights in the green stage. Without this initial setting, they would be turned off, until the first time a changeLights() was initiated using a function.

pinMode(button, INPUT);
digitalWrite(green, HIGH);

Change the entire loop function to the following instead:

void loop() {
    if (digitalRead(button) == HIGH){
        delay(15); // software debounce
        if (digitalRead(button) == HIGH) {
            // if the switch is HIGH, ie. pushed down - change the lights!
            changeLights();
            delay(15000); // wait for 15 seconds
        }
    }
}

That should do it. You may be wondering why the button is checked twice (digitalRead(button)), separated by a small delay. This is called debouncing. Much like the pull down resistor was needed for the button, this simple check stops the code detecting minor interference as a button press. You don’t have to do this (and it would probably work just fine without it), but it’s good practice.

By waiting inside the if statement for 15 seconds, the traffic lights can’t change for at least that duration. Once 15 seconds is up, the loop restarts. Each restart of the loop, read the state of the button again, but if it isn’t pressed, the if statement never activates, the lights never change, and it simply restarts again.

Here’s how this looks (sped up):

pelican_crossing

A Junction

Let’s try a more advanced model. Instead of a pedestrian crossing, modify your circuit to have two traffic lights:

arduino_dual_traffic_light

Connect the second traffic light to digital pins 11, 12, and 13.

The Code

First, assign your new traffic light pins to variables, and configure them as outputs, just like in the first example:

// light one
int red1 = 10;
int yellow1 = 9;
int green1 = 8;

// light two
int red2 = 13;
int yellow2 = 12;
int green2 = 11;

void setup(){
    // light one
    pinMode(red1, OUTPUT);
    pinMode(yellow1, OUTPUT);
    pinMode(green1, OUTPUT);

    // light two
    pinMode(red2, OUTPUT);
    pinMode(yellow2, OUTPUT);
    pinMode(green2, OUTPUT);
}

Now, update your loop to use the code from the first example (instead of the pedestrian crossing):

void loop(){
    changeLights();
    delay(15000);
}

Once again, all the work is being carried out in the changeLights() function. Rather than going red > red & yellow > green, this code will alternate the traffic lights. When one is on green, the other will be on red. Here’s the code:

void changeLights(){
    // turn both yellows on
    digitalWrite(green1, LOW);
    digitalWrite(yellow1, HIGH);
    digitalWrite(yellow2, HIGH);
    delay(5000);

    // turn both yellows off, and opposite green and red
    digitalWrite(yellow1, LOW);
    digitalWrite(red1, HIGH);
    digitalWrite(yellow2, LOW);
    digitalWrite(red2, LOW);
    digitalWrite(green2, HIGH);
    delay(5000);

    // both yellows on again
    digitalWrite(yellow1, HIGH);
    digitalWrite(yellow2, HIGH);
    digitalWrite(green2, LOW);
    delay(3000);

    // turn both yellows off, and opposite green and red
    digitalWrite(green1, HIGH);
    digitalWrite(yellow1, LOW);
    digitalWrite(red1, LOW);
    digitalWrite(yellow2, LOW);
    digitalWrite(red2, HIGH);
    delay(5000);

}

Here’s what that looks like (sped up):

dual_traffic_light

That’s it for this time, so I hope you learnt lots and had fun writing from scratch. You got your hands dirty with a few LEDs and resistors, as well as adding a switch with a pull down resistor – hopefully you understood why we need one. Play around with the code, adjust it, and most importantly have fun. If you make any additions or changes, why not let us know about it in the comments?

Image Credit: androsvector via Shutterstock.com

  1. Aakash Choudhry
    January 11, 2017 at 7:45 pm

    Did this code work for anyone??

  2. saleem
    January 10, 2017 at 1:45 am

    Easy to understand arduino function

Leave a Reply

Your email address will not be published. Required fields are marked *