Sharjah, UAE GST
Home/ Projects/ Lesson 2: Traffic-Light Distance Indicator
Lesson 2 of 9 Basics Beginner ◎ 30 min

Lesson 2: Traffic-Light Distance Indicator

Add three LEDs that act like a traffic light for distance: green when it is far, yellow when it gets close and red when it is near.

Arduino Ultrasonic Distance & Parking Learning Kit
One of 9 projects in the Arduino Ultrasonic Distance & Parking Learning Kit — the parts below are from that kit.

Before you start

Time
30 min
Do these first
On your own
You can do this lesson on your own.

Exact parts

PartHow many
Wiring from Lesson 1
Red, yellow and green LED1 each
220 Ω resistors (red-red-brown)3
Male-to-male jumper wiresabout 6

Not in the box

Nothing extra - just the kit and your computer.

What you build and learn

  • Which LED leg is + and why every LED needs its own resistor
  • Turning a measurement into a decision with if / else if / else
  • Choosing zones with named numbers (CLEAR_CM, NEAR_CM)
  • Why "no echo" must never look like "all clear"

Each LED has its own pin: red on 5, yellow on 6, green on 7. HIGH turns an LED on and LOW turns it off.

Each LED has its own 220 Ω resistor. Without one, the LED takes too much current and can damage itself or the UNO pin. Sharing one resistor between LEDs makes them glow unevenly.

loop() measures once, then picks one zone: under 20 cm red, under 50 cm yellow, otherwise green. Only one LED is on at a time.

If no echo comes back, the sketch does not know the distance. It blinks yellow instead of showing green: unknown must never look like safe.

New words

LED
Light-emitting diode. It only lights one way round: long leg +.
Resistor
A part that limits current. The lessons use 220 Ω: red-red-brown bands.
Zone
A range of distances that gets the same light, such as 20-49 cm = yellow.
if / else
Code that does one thing if something is true, and something else if not.

What this project uses

Every item is in the kit — nothing extra to buy.

Build this with

Arduino Ultrasonic Distance & Parking Learning Kit

All 9 parts in one box, with this project and 8 more to build from them.

AED 85.00 See the kit
Need only these parts? Order them loose · from AED 87.65
Used in this project tick what you still need
Selected parts AED 87.65

One of each part. Packs (resistor assortment, jumper wires) already hold more than a single build needs. red/yellow/green LEDs: included in the kit, ask us for it loose. Delivery is AED 20, free on orders AED 100+.

Connections

Unplug USB before you change any wire. Pin names are the labels printed on the board.

Lesson 2: Traffic-Light Distance Indicator - connection diagram with labelled pins
Connection diagram, drawn from this lesson's pin plan - not a photo of a tested build. Tap to open it full size. The table below says the same thing in words.
Part / pinConnect toNote
Red LED long leg (+)220 Ω → UNO pin 5One resistor for each LED
Yellow LED long leg (+)220 Ω → UNO pin 6
Green LED long leg (+)220 Ω → UNO pin 7
All three short legs (−)− rail (GND)
HC-SR04As in Lesson 1TRIG pin 9, ECHO pin 10

Step by step

One thing at a time. Tick nothing off until it matches the diagram.

  1. Unplug the USB cable.Watch out: Always unplug the USB cable before you add, move or remove a wire.
  2. Leave the sensor and the rail wires from Lesson 1 where they are.
  3. Push the red LED into the breadboard with its two legs in two different rows. Note which row has the long leg.Watch out: The long leg is +. If the legs are cut, the flat edge on the LED's rim marks the − side.
  4. Put a 220 Ω resistor (red-red-brown) from the long-leg row to an empty row, and wire that row to UNO pin 5.Watch out: Every LED needs its own resistor.
  5. Do the same for the yellow LED (pin 6) and the green LED (pin 7).
  6. Wire each LED's short-leg row to the − rail.
  7. Check the three LEDs against the diagram, plug in USB, then copy the Lesson 2 code into the IDE and upload it.Watch out: If anything gets hot or smells, unplug straight away.
  8. Watch the light test (red, yellow, green), then move a book slowly towards the sensor from about 70 cm away.

Sketch for this project

Written for the board in the kit. Copy it into the Arduino IDE; change the pin numbers if you wire it differently.

lesson2_traffic_light.ino arduino
/*
  DIY KIT - Arduino Ultrasonic Distance & Parking Learning Kit
  Lesson 2 of 9: Traffic-Light Distance Indicator

  WIRING (unplug the USB cable before you wire)
    HC-SR04 as in Lesson 1: VCC 5V, TRIG pin 9, ECHO pin 10, GND.
    Red LED    long leg -> 220 ohm resistor -> UNO pin 5
    Yellow LED long leg -> 220 ohm resistor -> UNO pin 6
    Green LED  long leg -> 220 ohm resistor -> UNO pin 7
    All three short legs -> GND (- rail)

  WHAT SHOULD HAPPEN
    Green  = 50 cm or more   (CLEAR)
    Yellow = 20 to 49 cm     (CAUTION)
    Red    = under 20 cm     (NEAR)
    Yellow blinking = no echo: the sensor does not know. Unknown is never shown as green.
    The Serial Monitor (9600 baud) prints the zone and the distance.
*/

const int RED_LED = 5;
const int YELLOW_LED = 6;
const int GREEN_LED = 7;
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;

const int CLEAR_CM = 50;   // this far or more: green
const int NEAR_CM = 20;    // closer than this: red

const unsigned long ECHO_TIMEOUT_US = 30000;
const int MIN_CM = 2;
const int MAX_CM = 400;

long readOnceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long us = pulseIn(ECHO_PIN, HIGH, ECHO_TIMEOUT_US);
  if (us == 0) return 0;          // no echo
  long cm = us / 58;
  if (cm < MIN_CM || cm > MAX_CM) return 0;
  return cm;
}

// Turn each LED on (true) or off (false).
void showLights(bool red, bool yellow, bool green) {
  digitalWrite(RED_LED, red ? HIGH : LOW);
  digitalWrite(YELLOW_LED, yellow ? HIGH : LOW);
  digitalWrite(GREEN_LED, green ? HIGH : LOW);
}

void setup() {
  pinMode(RED_LED, OUTPUT);
  pinMode(YELLOW_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  Serial.begin(9600);
  Serial.println("Lesson 2: Traffic-Light Distance Indicator");

  // Light test: red, yellow, green, one after another.
  showLights(true, false, false);  delay(300);
  showLights(false, true, false);  delay(300);
  showLights(false, false, true);  delay(300);
  showLights(false, false, false);
}

void loop() {
  long cm = readOnceCm();

  if (cm == 0) {
    // No echo: blink yellow - on for half a second, off for half a second.
    unsigned long halfSeconds = millis() / 500;   // half-seconds since the UNO started
    bool blinkOn = (halfSeconds % 2 == 0);        // even: on, odd: off
    showLights(false, blinkOn, false);
    Serial.println("NO_ECHO");
  } else if (cm < NEAR_CM) {
    showLights(true, false, false);
    Serial.print("NEAR ");
    Serial.println(cm);
  } else if (cm < CLEAR_CM) {
    showLights(false, true, false);
    Serial.print("CAUTION ");
    Serial.println(cm);
  } else {
    showLights(false, false, true);
    Serial.print("CLEAR ");
    Serial.println(cm);
  }

  delay(100);
}
ℹCompiler-checked for Arduino UNO (0 warnings) and run in the kit simulator. Pins match the lesson diagram. Not yet bench-tested on the shipped parts.

Upload it

  1. Click Copy (or Download .ino and open the file).
  2. In the Arduino IDE choose File → New Sketch, select everything in it and paste.
  3. Check the bottom of the window says Arduino Uno and your port (Start here, step 5).
  4. Click Upload (the → arrow) and wait for Done uploading.

How the code works

In the codeWhat it does
const int CLEAR_CM = 50; const int NEAR_CM = 20;The zone edges. Change them here and the whole sketch follows.
showLights(red, yellow, green)Our own function: true switches an LED on, false switches it off.
if (cm == 0) { ... } else if (cm < NEAR_CM) ...The decision: no echo first, then red, then yellow, otherwise green.
halfSeconds % 2 == 0Counts half-seconds since start. Even numbers: yellow on, odd: off. That makes the blink.

Change it and see

Change: Change NEAR_CM from 20 to 30.What happens: Red now comes on further away: the red zone is bigger.
Change: Change the 500 in millis() / 500 to 150.What happens: With no echo, yellow blinks much faster.

What you should see or hear

  • At start: red, yellow, green each light for a moment.
  • Green at 50 cm and more, yellow from 20 to 49 cm, red under 20 cm.
  • Point the sensor at an empty space: yellow blinks and the Serial Monitor shows NO_ECHO.

If it doesn't work

ProblemWhat to check
One LED never lights, not even in the light testUnplug USB and turn that LED round (long leg towards the resistor). Check its wire goes to the right pin.
The colours light in the wrong zonesTwo pin wires are swapped. Red must be on 5, yellow on 6, green on 7.
The LEDs light in the test but never changeThe sensor wiring moved. Check it against Lesson 1.
An LED is very dimCheck the resistor bands: red-red-brown is 220 Ω. Brown-black-orange is 10 kΩ, far too big.
It always says no echoUnplug USB. Check VCC to the + rail, GND to the − rail, TRIG to pin 9 and ECHO to pin 10 - by the labels on the sensor, not their position. Point it at a big flat object 20-50 cm away.
The upload failsSee Start here, step 6: "If the upload fails".

Small experiment

Find the exact distance where yellow changes to red. Move the book 1 cm at a time. Is it always at the same place, or does it flicker at the edge?

Check what you learned

Why does every LED need its own resistor?

To limit the current so the LED and the UNO pin are not damaged; sharing one makes them glow unevenly.

A book is 35 cm away. Which LED is on?

Yellow (20-49 cm).

Why does the sketch blink yellow instead of showing green when there is no echo?

No echo means the distance is unknown, and unknown must never look like "all clear".

▶In the simulator: The simulator shows the same three lights. It does not check which way round the LEDs are or whether you used resistors - on the real breadboard both matter.

Next

  • Lesson 3 adds the buzzer, so it beeps when something gets close. Keep the LEDs where they are.

Stuck?

Most problems are one wire in the wrong hole. Check these first:

  1. Unplug, then compare every wire with the lesson's diagram and table. One pin off is the most common problem.
  2. Sensor: are VCC, TRIG, ECHO and GND wired by their labels, with TRIG on 9 and ECHO on 10?
  3. LEDs: is the long leg on the resistor side?
  4. Is the − rail connected to a UNO GND pin, and the + rail to 5V?
  5. Serial Monitor: is it set to 9600 baud (and "New Line" when you type commands)?
  6. Upload problems: is Tools → Board set to Arduino Uno and Tools → Port to your UNO? (Start here, step 5.)
Still stuck? Ask us on WhatsApp. Send this message with a photo of your wiring - it tells us exactly where you are.
Hi DIY KIT, I'm stuck on the Arduino Ultrasonic Distance & Parking Learning Kit.
Lesson: __
Step number: __
What should happen: __
What happens instead: __
Error message (copied exactly): __
I'll attach a photo of my wiring.
Message us on WhatsApp

More from this kit

All projects →

Bot
ECHO
Online — usually replies instantly
Catalog assistant: verify final stock/price on the product page before checkout.