OBJECTIVE

For this project we will build a single traffic light that follows the correct sequence (in the UK) of RED, RED and AMBER, GREEN, AMBER, RED.

THE HARDWARE

LEDs for traffic light

We will need a red, orange (or yellow) and green LED; 3 220Ω resistors and your Arduino.

THE CIRCUIT

traffic light led arduino

THE CODE

The first thing that we will do is to define 3 variables of the data type int for the RED, AMBER and GREEN LED. Then we will be able to address them by name, rather than by number:

int red = 11;   
int amber = 12; 
int green = 13; 

Next we define a variable of the data type int so that we can create a delay that will be used throughout our loop. This can be any number but it relates to 4 times the change.

int lightDelay = 1500; 

In our setup() we will use pinMode() to set the pins for the RED, AMBER and GREEN LEDs to OUTPUT.

We will also use digitalWrite() to turn ON the RED LED so that there is an LED on from startup and no point where there is no LED on.

void setup() {
  pinMode(red,OUTPUT);   
  pinMode(amber,OUTPUT); 
  pinMode(green,OUTPUT); 
  digitalWrite(red,HIGH); 
}

In our loop() we will use digitalWrite() to select each LED to be turned ON and OFF, along with delay() to wait between each change.

void loop(){

AMBER ON followed by a delay.

digitalWrite(amber,HIGH); 
delay(lightDelay); 

GREEN ON, RED OFF, AMBER OFF, followed by a delay.

digitalWrite(green,HIGH); 
digitalWrite(red,LOW);    
digitalWrite(amber,LOW);  
delay(lightDelay*4);       

AMBER ON, GREEN OFF, followed by a delay.

digitalWrite(amber,HIGH); 
digitalWrite(green,LOW);   
delay(lightDelay);         

AMBER OFF, RED ON, followed by a delay.

digitalWrite(amber,LOW);   
digitalWrite(red,HIGH);    
delay(lightDelay*4);        

IMPROVEMENTS

We could make this interactive by adding a red and green light for pedestrians and a button to press that we will make the pedestrian lights go from red to green and the car lights go from red to amber to green.

traffic light LED Arduino

THE RESULT