Arduino Project: Simple Traffic Light

Traffic lights, also known as traffic signals, traffic lamps, signal lights, stop lights, or technically as traffic control signals are signalling device positioned at road intersection, pedestrian crossings, and other locations to control competing flows of traffic.

In this project we will create a simple “traffic light”, imitating what traffic light does and program it using Arduino.

Circuit

We use three LED at once. The first LED is red, the second LED should be yellow, and the last one is green LED. Remember which one is the positive leg and which one is negative leg (anode and cathode) for each LED. Connect attach the long leg of an LED (positive leg or anode) with resistor and then connect it to corresponding pin. Red one will use pin 12, yellow will be in 11, and green would use pin 10. Connect the short leg (negative leg or cathode) to the ground (GND).

Code

Let’s see what code we use for this project and discuss it later.

Arduino

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

#define RED_PIN 12

#define YELLOW_PIN 11

#define GREEN_PIN 10

// timeout for each LED in second

inttimeout[3]={10,1,20};

intcurrentLED=0;

intalternate=-1;

intenumLED[3]={RED_PIN,YELLOW_PIN,GREEN_PIN};

voidsetup(){

pinMode(RED_PIN,OUTPUT);

pinMode(YELLOW_PIN,OUTPUT);

pinMode(GREEN_PIN,OUTPUT);

}

voidloop(){

digitalWrite(enumLED[currentLED],LOW);

if(currentLED==0){

alternate=1;

}elseif(currentLED==2){

alternate=-1;

}

currentLED=currentLED+alternate;

digitalWrite(enumLED[currentLED],HIGH);

delay(timeout[currentLED]*1000);

}

We define three constant here: RED_PIN, YELLOW_PIN, and GREEN_PIN for red, yellow, and green LED respectively. However this time we only define it using macro not as constant. Then we create an array of LED as enumLED. This array will be our shortcut to switch between LED. For indexing we use currentLED variable.

The timeout array is an array which stored delay interval for each LED in seconds. This means our lights won’t turned on in same duration.

The alternate variable is used to increment the currentLED index. Remember that in one cycle, we define the LED switching as red – yellow – green – yellow.

Result

LED is turned on in following order:

red for 10 seconds

yellow for 1 second

green for 20 seconds

yellow for 1 second

red for 10 seconds at another cycle.

Why it Works

Our code is as simple as turned off current LED and turned on the next LED. The previous, current, and next LED are defined in an array and we use currentLED variable as an index. The alternate is used to increase or decrease the index and make our LED obey our pattern.