CYTHEIA AIOpen the editor

Traffic Light

Red, yellow, green LEDs cycling like a traffic light.

Open this circuit and run it

Opens in your browser with the parts, wiring and code already in place. Press Run to watch it work, then change anything you like.

How it works

Three LEDs, each with its own resistor, are wired to pins 11 (red), 12 (yellow) and 13 (green), and all three cathodes go to ground. Each LED lights when its pin is high, so the sketch controls the light by deciding which of the three pins is on at any moment.

loop() runs one full cycle of the lights. First it turns green on (pin 13) and the other two off, for three seconds. Then yellow for one second, then red for three. Each stage also prints its message (“GO - Green”, “CAUTION - Yellow”, “STOP - Red”) to the Serial tab. Only one LED is ever on at a time, because every stage sets all three pins explicitly.

Parts

Wiring

Arduino code

// Traffic Light Controller
void setup() {
  pinMode(11, OUTPUT); // Red
  pinMode(12, OUTPUT); // Yellow
  pinMode(13, OUTPUT); // Green
  Serial.begin(9600);
}

void loop() {
  // Green
  digitalWrite(13, HIGH);
  digitalWrite(12, LOW);
  digitalWrite(11, LOW);
  Serial.println("GO - Green");
  delay(3000);

  // Yellow
  digitalWrite(13, LOW);
  digitalWrite(12, HIGH);
  digitalWrite(11, LOW);
  Serial.println("CAUTION - Yellow");
  delay(1000);

  // Red
  digitalWrite(13, LOW);
  digitalWrite(12, LOW);
  digitalWrite(11, HIGH);
  Serial.println("STOP - Red");
  delay(3000);
}

Try changing it

Open this circuit and run it

Next challenge

More projects in LED & Lighting