⭐ Beginner ⏱️ 15 minutes

Traffic light

You build a real traffic light with a red, a yellow, and a green LED. They turn on one by one, just like on the street.

First you log in for a moment. Then your project is ready right away.

🧰 What do you need?

🗺️ Wiring diagram

Follow the wires from the Arduino to each part. You can choose the wire colors yourself.

From To
Arduino UNO · D4 220Ω · 1
220Ω · 2 LED red · ANODE
LED red · CATHODE Arduino UNO · GND
Arduino UNO · D3 220Ω · 1
220Ω · 2 LED yellow · ANODE
LED yellow · CATHODE Arduino UNO · GND
Arduino UNO · D2 220Ω · 1
220Ω · 2 LED green · ANODE
LED green · CATHODE Arduino UNO · GND

🛠️ This is how you build it

  1. Put the three LEDs next to each other in the breadboard.
  2. Give each LED its own 220 Ω resistor to its pin: red to 4, yellow to 3, green to 2.
  3. Connect all short legs to the minus strip (−) of the breadboard.
  4. Connect the minus strip to GND of your Arduino.

💻 The code

// Traffic light
// Three LEDs do exactly what a real traffic light does: green, orange, red.

const int RED = 4;    // Red LED on pin 4
const int ORANGE = 3;  // Yellow/orange LED on pin 3
const int GREEN = 2;   // Green LED on pin 2

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(ORANGE, OUTPUT);
  pinMode(GREEN, OUTPUT);
}

// Turn one light on and the other two off
void setLight(int on) {
  digitalWrite(RED, on == RED ? HIGH : LOW);
  digitalWrite(ORANGE, on == ORANGE ? HIGH : LOW);
  digitalWrite(GREEN, on == GREEN ? HIGH : LOW);
}

void loop() {
  setLight(GREEN);   // Green: you may go
  delay(5000);
  setLight(ORANGE);  // Orange: watch out, it will turn red
  delay(2000);
  setLight(RED);    // Red: stop!
  delay(5000);
}

🧠 What does the code do?

  • Each LED has its own pin: red on 4, yellow on 3, and green on 2.
  • The function setLight() turns one light on and the other two off.
  • In loop() we go from green to orange to red, with a wait in between.

🎯 Try this…

  • Make the orange light blink three times before it turns red
  • Add a button: when you press it, the light goes to red faster (a pedestrian button)
  • Make a night mode where only the orange light blinks

🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/traffic-light and click MAKE THIS. Then the code and the wiring diagram are ready right away.

First you log in for a moment. Then your project is ready right away.
⬇️ Download this page as a PDF 📚 Download the complete tutorial (PDF)

Codey Online is a product of OTRONIC

Build your Arduino or ESP32 project with AI

Describe what you want to build. Codey Online writes the code, draws the wiring diagram, compiles it and flashes your board straight from the browser.

Start for free