DEV Community

Cover image for Traffic Light Simulator - Arduino
Ochwada Linda
Ochwada Linda

Posted on

5 3

Traffic Light Simulator - Arduino

Simulating a traffic light using LEDs and Arduino, I did the project with my 8-year-old son! He found it so cool.

COMPONENTS

  • Arduino UNO
  • Breadboard (Generic)
  • Jumper Wires (Generic)
  • LED (Red, Green, Yellow)
  • Arduino USB 2.0 Data Cable
  • Resistor 100 ohm

COMPONETS SETUP
Image set-up

IDE used: Arduino IDE

This simple "for beginners " uses an Arduino and LEDs to simulate a traffic light.

Define variables, use lights by colour name:

// variables
int red = 10;
int yellow = 9;
int green = 8;
Enter fullscreen mode Exit fullscreen mode

Create a function to configure the output colours of the LEDs (Red, Yellow, Green):

void setup(){
    pinMode(red, OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green, OUTPUT);
}
Enter fullscreen mode Exit fullscreen mode

This pinMODE function, configures the Arduino to use a defined pin as an output.

Write the code for the actual logic behind the traffic light simulation. The given values are in milliseconds

void loop(){
    changeLights();
    delay(15000);
}
void changeLights(){
    // green off, yellow on for 3 seconds
    digitalWrite(green, LOW);
    digitalWrite(yellow, HIGH);
    delay(3000);

    // turn off yellow, then turn red on for 5 seconds
    digitalWrite(yellow, LOW);
    digitalWrite(red, HIGH);
    delay(5000);

    // red and yellow on for 2 seconds (red is already on though)
    digitalWrite(yellow, HIGH);
    delay(2000);

    // turn off red and yellow, then turn on green
    digitalWrite(yellow, LOW);
    digitalWrite(red, LOW);
    digitalWrite(green, HIGH);
    delay(3000);
}
Enter fullscreen mode Exit fullscreen mode

Upload the above code to your Arduino and run (make sure the right board and port are selected from Tools menu)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs