Traffic Signal

This example uses three LEDs to make a model traffic light signal. You can use all red LEDs if you like, but its more realistic if you use red, yellow and green.

The LEDs cycle around in the sequence red, yellow, green, yellow and then back to red again.

To add the extra LEDs and resistors, wire them up as shown in the breadboard layout below.

Take care to ensure that the LEDs are the right way around, with the longer positive leads (anodes) to the left.

JavaScript Blocks Code

The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can Click here to open the editor in a separate browser tab.

MicroPython Code

The MicroPython code is listed below.

Download: file
from microbit import *

red_pin = pin0    # giving the LED pins names by using variables
amber_pin = pin1  # makes it easier to see how the program works
green_pin = pin2

while True: 
    # red - turn amber LED off and red LED on
    amber_pin.write_digital(0)
    red_pin.write_digital(1)
    sleep(4000) # delay 4 seconds
    # amber - turn red LED off and amber LED on
    red_pin.write_digital(0)
    amber_pin.write_digital(1)
    sleep(1000)
    # green - turn amber LED off and green LED on
    amber_pin.write_digital(0)
    green_pin.write_digital(1)
    sleep(4000)
    # amber - turn green LED off and amber LED on
    green_pin.write_digital(0)
    amber_pin.write_digital(1)
    sleep(1000)

Arduino code

The Arduino version of this program is very similar to the other two versions.

Download: file
// define constants for each LED pin
const int redPin = 0;
const int amberPin = 1;
const int greenPin = 2;

void setup() {
  // set all three pins to act as digital outputs
  pinMode(redPin, OUTPUT);
  pinMode(amberPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
}

void loop() {
    // red - turn amber LED off and red LED on
    digitalWrite(amberPin, LOW);
    digitalWrite(redPin, HIGH);
    delay(4000);   // delay 4 seconds
    // amber - turn red LED off and amber LED on
    digitalWrite(redPin, LOW);
    digitalWrite(amberPin, HIGH);
    delay(1000);
    // green - turn amber LED off and green LED on
    digitalWrite(amberPin, LOW);
    digitalWrite(greenPin, HIGH);
    delay(4000);
    // amber - turn green LED off and amber LED on
    digitalWrite(greenPin, LOW);
    digitalWrite(amberPin, HIGH);
    delay(1000);
}
This guide was first published on Mar 09, 2018. It was last updated on Mar 09, 2018. This page (Traffic Signal) was last updated on Sep 19, 2019.