DEV Community 👩‍💻👨‍💻

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

Posted on

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)

Top comments (0)

Image description

Join the One Year Club

You can earn this badge by being a registered member of the DEV Community for at least one year. Create an account and get started today.