Pinterest Stumbleupon Whatsapp
Ads by Google

traffic light controllerLast week, we learnt about the basic structure of an Arduino program and took a closer look at the ‘blink’ example. Hopefully you took the opportunity to experiment with code, adjusting the timings. This time, we’ll be writing something from scratch. In fact, let’s make a traffic light.

Apart from the basic Arduino, you’ll need:

  • A red, yellow and green LED.
  • A breadboard.
  • 3 x suitable resistors for the LEDs you have ( probably 220 Ohms is fine).
  • Connecting wires.
  • A pushbutton switch.
  • A high value resistor (10k).

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:

You may also want to download and install Fritzing Fritzing - The Ultimate Tool For Sketching Out Electronics Projects [Cross Platform] Fritzing - The Ultimate Tool For Sketching Out Electronics Projects [Cross Platform] Despite sounding like an alcopop, Fritzing is actually an incredible bit of free software you can use to create circuit and component diagrams for use with rapid-prototyping electronics boards such as the fantastic open-source Arduino.... Read More , the tool I used to draw the wiring diagrams for these projects.

Wiring

Here’s a quick schematic I made up in Fritzing. It’s very simple – just the three LEDs wired with resistors to three separate input pins, and all connected to the ground.

traffic light controller

Ads by Google

Programming

We’ll 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 = 13;
int yellow = 12;
int green = 11;

Next, let’s add the setup function, where’ll we define the red, yellow and green LEDs to be output mode. Since we’ve created variables to represent the pin numbers, we can now refer to the pins by names 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. I’m going to create a separate function for changing the lights, and 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.

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

void changeLights(){
// green off, yellow for 3 seconds
digitalWrite(green,HIGH);
digitalWrite(yellow,LOW);
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);
}

Done! Now, upload and run. You should have a working traffic light that changes every 15 seconds. However, I think it’s a little basic right now, so let’s add in a pushbutton for pedestrians to change the light whenever they like. Refer to the updated circuit diagram below:

traffic light controller

You’ll notice that the switch has a high-impedance 10k resistor attached to it, and 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 – 0 or 1, 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.

Start by adding some new variables to the start of the app:

int button = 2; // switch is on pin 2
int buttonValue = 0; // switch defaults to 0 or LOW

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(switch,INPUT);
digitalWrite(green,HIGH);

Change the entire loop function to the following instead:

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

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

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?

  1. Nandhini
    September 26, 2016 at 12:04 pm

    when I upload my code correct but I cannot get the output pls any one tell what is the pblm

  2. Faizan Hamayun
    September 22, 2016 at 6:54 am

    Very nice!
    I am new in this field i need a simple single LED flasher/Solid circuit that accepts 3 types of input signal from a circuit one is positive +5v to gnd and other is -5v to gnd when +5 signal input to arduino it should solid ON and when -5v to gnd signal input the LED starts flashing LED at rate of 2sec and when no signal (below 2v) LED off.Please reply

  3. Leo Sun
    September 14, 2016 at 1:08 am

    I need help with the code, when I press upload it says switchvalue was not delcared in this scope.

    • Leo Sun
      September 14, 2016 at 1:25 am

      as well as Im using 1k resisters instead of 220 cos i dont have those.

  4. Joshua Alvin
    August 17, 2016 at 1:54 pm

    Can I use arduino in a real life working traffic light?

    • James Bruce
      August 17, 2016 at 2:59 pm

      I don't see why not - just replace the LEDs with relays on the positive line of each bulb.

  5. Gabriela Pires
    June 1, 2016 at 9:44 pm

    I cant find this pull up resistor in 123d circuits so I can do my project... is there something that we can use to replace it??

    • James Bruce
      June 2, 2016 at 7:07 am

      It's a 10k resistor. Anything close to that value will do, it doesn't have to be exact (though you should be able to set that in 123d circuits).

  6. ZOey
    April 14, 2016 at 9:14 am

    is there a way to have the LED light up one by one but using a shorter code

    • James Bruce
      April 14, 2016 at 9:36 am

      Not entirely sure what you mean. Perhaps by using an array? Then you wourld avoid having so many variables, and just iterate over the array of pin numbers?

    • Daniel
      May 23, 2016 at 1:46 pm

      For loop.

  7. bob saggat
    March 23, 2016 at 1:50 pm

    Here is a copy of the working code to make this function as designed in the schematic. Just make sure that you connect the BUTTON to pin#2 and not 0 as in the original design.

    int red = 13;
    int yellow = 12;
    int green = 11;
    int button = 2; // switch is on pin 2
    int buttonValue = 0; // switch defaults to 0 or LOW

    void setup(){
    pinMode(red,OUTPUT);
    pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
    pinMode(button,INPUT);
    digitalWrite(green,HIGH);
    }

    void loop(){
    // read the value of the switch
    buttonValue = digitalRead(button);
    // if the switch is HIGH, ie. pushed down - change the lights!
    if (buttonValue == HIGH){
    changeLights();
    delay(1); // wait for 15 seconds
    }
    }
    void changeLights(){
    // green off, yellow 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,LOW);
    digitalWrite(red,LOW);
    delay(100);

    // turn off red and yellow, then turn on green
    digitalWrite(yellow,LOW);
    digitalWrite(red,LOW);
    digitalWrite(green,HIGH);
    }

  8. Valentino Martinez
    March 3, 2016 at 5:03 pm

    There is an error for the RX pin and when i take out the wire the code works but when i put it back in it doesn't and only my green led lights up and for a little while the red one lights up but it goes back to green. What's my problem?

  9. Valentino Martinez
    February 23, 2016 at 7:40 pm

    I need help with my code (sorry if I typed this twice). I have it all right but it still gives me errors.

    http://pastebin.com/V1KBAgL8

  10. Valentino Martinez
    February 23, 2016 at 7:38 pm

    I need hep with my code because I figured out the code (even the tricks lol) but it still gives me errors. Here it is on paste-bin.

    http://pastebin.com/V1KBAgL8

  11. Mike
    February 22, 2016 at 12:36 am

    In the diagram the switch is on pin 0 and not pin 2 as in the code.

  12. Peter
    February 18, 2016 at 2:48 pm

    It may be a bit redundant, but you can get away with only 1 resistor if you put it on the common negative side of the circuit. Just a thought.

  13. Ardy
    February 7, 2016 at 1:57 pm

    Hi can anyone help me with the code as I cant seem to get the green led to light. I have done the circuit and code without the switch but only red and yellow led working. Any help would be appreciated. Thanks in advance

    • Prem
      February 10, 2016 at 12:01 am

      It could be the LED that you are using for your green try a different green LED.

  14. Toph
    January 22, 2016 at 1:33 am

    A little bit confusing, and the first part about turning the certain lights on or off is just wrong...

  15. amardubal1760420
    January 21, 2016 at 5:31 pm

    could someone help me with the code if i provide you with the simple home automation project details.I need it ASAP

  16. bob
    January 5, 2016 at 3:51 pm

    How are we supposed to learn if you put “deliberate” typo?

    • saddam hafeez rana
      January 15, 2016 at 5:14 am

      yes

  17. Darsi Venkateswarlu Bujji
    December 9, 2015 at 10:02 am

    Is there any arduino hardware simulator instead buying hardware?. So I can simulate the circuit either working or not.

    • James Bruce
      December 9, 2015 at 10:20 am

      there is indeed: https://123d.circuits.io/

    • NatePG
      August 24, 2016 at 4:01 am

      play some minecraft

  18. Nathan Oliveira
    December 4, 2015 at 8:35 pm

    Hey I was wondering if I were to add a crossing light what would it look like just wondering Thanks!!!

  19. hasnain
    November 25, 2015 at 5:09 pm

    i hav got this error bruce after changing switchValue into buttonValue
    expected primary-expression before 'switch'

    pinMode(switch,INPUT);

    • James Bruce
      November 25, 2015 at 5:25 pm

      Well, you want pinMode(button,INPUT) for a start, but you'd need to post the rest of your code if the error persists. (Post it to a pastebin please, not here).

  20. Gavin Sidhu
    October 20, 2015 at 2:15 pm

    Could someone please post the accurate code? None of these have been working for me. I've triple checked the wires and they all seem to be correct. I've looked at the code and edited as needed, but it still doesn't seem to be working. Thanks in advance

  21. Aiden Patrick
    September 19, 2015 at 3:38 am

    I got the automatic changing traffic light to work but I have this code in (for the pedestrian):

    int red = 13;
    int yellow = 12;
    int green = 11;
    int button = 2;
    int buttonValue = 0;

    void setup(){
    pinMode(red,OUTPUT);
    pinMode(yellow,OUTPUT);
    pinMode(green,OUTPUT);
    pinMode(switch,INPUT);
    digitalWrite(green,HIGH);
    }

    void loop(){
    switchValue = digitalRead(button);
    if (buttonValue == HIGH)
    changeLights();
    delay(15000); // wait for 15 seconds
    }

    and when I go to upload it I get these errors:

    control_tlight.ino: In function ‘void setup()’:
    control_tlight.ino:11:9: error: expected primary-expression before ‘switch’
    control_tlight.ino: In function ‘void loop()’:
    control_tlight.ino:16:1: error: ‘switchValue’ was not declared in this scope
    control_tlight.ino:18:14: error: ‘changeLights’ was not declared in this scope

    • James Bruce
      September 19, 2015 at 7:58 am

      Hi Aiden. there's a "deliberate" typo in my code: it should be buttonValue, not switchValue, in loop().

      Also, you're missing the changeLights() function entirely. Be sure to copy that in too.

    • Aiden Patrick
      September 19, 2015 at 12:21 pm

      I now have this code:

      http://pastebin.com/bTRdASzK

      and get these errors now:

      control_tlight.ino: In function ‘void loop()’:
      control_tlight.ino:38:1: error: ‘switchValue’ was not declared in this scope
      control_tlight.ino:43:1: error: expected ‘}’ at end of input

    • Mihir Patkar
      September 20, 2015 at 12:39 pm

      Hi Aiden, please use Pastebin to paste your code in the future, I've done it for you this time. Thanks!

      -Mihir (Comments Mod)

    • Aiden Patrick
      September 19, 2015 at 12:28 pm

      The switchValue is typed in as button value and nonetheless I get the errors.

    • James Bruce
      September 19, 2015 at 4:05 pm

      You've still got switchValue, here:

      switchValue = digitalRead(button);

      Also, you're missing a closing bracket in the loop function. }.

  22. Aboud
    May 22, 2015 at 2:15 pm

    hi

    i have already made it on 123d circuit but during simulation the LEDs still off ,,, may u tell ,e why? i have fixed the codes already

    https://123d.circuits.io/circuits/826811-the-traffic-light-controller

    i have downloaded Fritzing and try it on and but how can i simulate it ?

    • nmab95
      September 3, 2015 at 6:16 pm

      Hi, what resistors did you use?? 220ohms??? Thank you!!

  23. jjkling
    May 18, 2015 at 5:04 am

    But if i don't want a greenlight as the start ?

    I mean if i want it to automatic like the first set of code but when push the button it go the the yellow and red and then comeback to the loop that change the light every 15 second

    how can i do that?

    should i remove this line ?
    digitalWrite(green,HIGH);

    this is my code
    http://pastebin.com/Qa3TWUM4

    sorry for my english it's not good
    thank you so much

  24. Thomas
    February 23, 2015 at 11:10 am

    Thanks for this example, it's great to see some code in action.

    Some things still seem wrong:
    // green off, yellow for 3 seconds
    digitalWrite(green,HIGH); // I would put that to LOW instead
    digitalWrite(yellow,LOW); // and that one to HIGH like told by Achraf52 in 2011

    pinMode(switch,INPUT); // Where does that "switch" variable comes from? It's "button"

    switchValue = digitalRead(button); // It should be "buttonValue" like told by Brian in 2011

  25. John
    May 15, 2012 at 11:17 pm

    And by the by, your simple light circuit worked just fine, with Achraf52's comments duly noted! :)

  26. John
    May 15, 2012 at 11:14 pm

    I tried to set the traffic light program using "while" statements (idea: while red2 = high, green1 = high for 3 seconds, green1 = low/yellow1=high for 2 seconds, red2 = low; then reverse this for red1=high). All I get is the original digitalWrite for red2=high, then red2 just stays on, like it doesn't enter the loop at all. Know what I'm doing wrong, or shall I upload the file?

    • muotechguy
      May 16, 2012 at 7:38 am

      Yep, please post source code to http://pastebin.com so we can take a look.

  27. John
    February 11, 2012 at 9:27 pm

    Hi

    Thanks for making the effort to publish something useful.

    For the tac switches I have found; your circuit has the switch shorted by the breadboard tracks, so always on.

    • James Bruce
      February 19, 2012 at 10:59 am

      I dont see the error John, this worked for me. 

    • Luc
      January 4, 2015 at 10:52 am

      The button on the breadbord is to turn 90° to work correct, the wire is to connect on pin 2 not on to pin 0.

  28. Brian Bowling
    December 13, 2011 at 5:05 pm

    First I wanted to say thanks very much for the series. It was helpful getting my first arduino board connected and my first project running.
    One thing I noted in this article:
    should the line
    switchValue = digitalRead(button);
    be
    buttonValue = digitalRead(button);
    ??

    • James Bruce
      December 14, 2011 at 1:37 am

      Yes - good catch. Sorry about that. I made some minor alteration prior to publishing to make it more readable. And introduced errors. On purpose. To test you. You pass! Gold star!

  29. Achraf52
    December 7, 2011 at 11:46 am

    You made a mistake in first code where you put LOW then HIGH instead of HIGH then LOW to make it work correctly .

    • muotechguy
      December 9, 2011 at 12:35 am

      Ahh, that was deliberate to see if you noticed! You win!

      j/k, thanks for pointing it out!

    • Achraf52
      December 9, 2011 at 1:49 pm

      Hi, that is nice and I hope they edit the post so beginners don't enter in a trouble while trying on this code .

    • PTA
      December 29, 2015 at 5:52 pm

      did anyone finally get this code working? can you send the final code?

Leave a Reply

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