lois li
Published © CERN-OHL2

3D Traffic Light Simulation with a Seven-Segment Display

A simple traffic light project to learn how to light up different LEDs in sequence according to a pattern.

BeginnerProtip2 hours66

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
LED (generic)
LED (generic)
×1
LED, Green
LED, Green
×1
5 mm LED: Yellow
5 mm LED: Yellow
×1
5 mm LED: Red
5 mm LED: Red
×1
Resistor 10k ohm
Resistor 10k ohm
×1

Software apps and online services

Online Simulation
PCBX Online Simulation

Hand tools and fabrication machines

Materia 101
Arduino Materia 101

Story

Read more

Schematics

3D Traffic Light

A simple traffic light project to learn how to light up different LEDs in sequence according to a pattern.

3D Traffic Light

A simple traffic light project to learn how to light up different LEDs in sequence according to a pattern.

Code

3D Traffic Light

Arduino
1. The green LED lights up, and the seven-segment display counts down from 8 to 0.

2. The green LED turns off, and the yellow LED starts blinking three times with 1-second intervals.

3. The red LED lights up, and the seven-segment display counts down from 8 to 0.

4. The red LED turns off, and the cycle repeats.
int segmentPins[] = {2, 3, 4, 5, 6, 7, 8};
int cathodePin = 9;
int greenLED = A5, yellowLED = A4, redLED = A3;

byte numbers[10] = {
    0x3F, // 0
    0x06, // 1
    0x5B, // 2
    0x4F, // 3
    0x66, // 4
    0x6D, // 5
    0x7D, // 6
    0x07, // 7
    0x7F, // 8
    0x6F  // 9
};

void setup() {
    for (int i = 0; i < 7; i++) {
        pinMode(segmentPins[i], OUTPUT);
    }
    pinMode(cathodePin, OUTPUT);
    
    pinMode(greenLED, OUTPUT);
    pinMode(yellowLED, OUTPUT);
    pinMode(redLED, OUTPUT);
}

void loop() {
    // Green light
    digitalWrite(greenLED, HIGH);
    displayTime(8); // 8 seconds
    digitalWrite(greenLED, LOW);
    delay(1000); // 1-second pause

    // Yellow light
    for (int i = 0; i < 3; i++) {
        digitalWrite(yellowLED, HIGH);
        delay(500); // Yellow LED on for 0.5 seconds
        digitalWrite(yellowLED, LOW);
        delay(500); // Yellow LED off for 0.5 seconds
    }
    digitalWrite(yellowLED, LOW);
    delay(1000); // 1-second pause

    // Red light
    digitalWrite(redLED, HIGH);
    displayTime(8); // 8 seconds
    digitalWrite(redLED, LOW);
    delay(1000); // 1-second pause
}

void displayTime(int time) {
    for (int i = time; i > 0; i--) {
        byte num = numbers[i];
        for (int j = 0; j < 7; j++) {
            digitalWrite(segmentPins[j], num & (1 << j));
        }
        digitalWrite(cathodePin, LOW);
        delay(1000); // Display each second
        digitalWrite(cathodePin, HIGH);
    }
}

Credits

lois li
8 projects • 0 followers

Comments