Menu
CoddyTech

Traffic Light Cycle

Part of the Projects section of Coddy's Arduino journey. Lesson 1 of 24.

This project builds a street crossing in four steps: car lights, better timing, a button for people on foot, and a walk signal with a beeper. The whole crossing is already wired, so the circuit stays the same in every step. Today only the three car lights are used.

A traffic light runs through the same steps forever: green, yellow, red, then green again. Each step is one light on and the other two off, held for a while.

When the same few lines appear again and again, put them in a function. This one turns on the light it is given and turns the others off:

void showLight(int pin) {
  digitalWrite(redPin, LOW);
  digitalWrite(yellowPin, LOW);
  digitalWrite(greenPin, LOW);
  digitalWrite(pin, HIGH);
}

Then each step in loop() is two lines: showLight(greenPin); and a delay() for as long as that light stays on.

challenge icon

Challenge

Easy

The car lights are on pins 12 (red), 11 (yellow) and 10 (green). Make them cycle:

  • make the three pins outputs
  • green for 3000 ms
  • yellow for 1000 ms
  • red for 3000 ms, then start again

Only one car light may be on at a time. Press Run to watch the crossing, then Check.

Try it yourself

// The car lights
const int redPin = 12;
const int yellowPin = 11;
const int greenPin = 10;

void setup() {
  // make the three light pins outputs

}

void loop() {
  // green for 3 s, yellow for 1 s, red for 3 s

}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Projects

Practice on your own: Arduino playground