deckle studioOpen in the editor

Arduino Uno: traffic light with pedestrian button

Red, yellow, green; the button shortens green.

  • Arduino Uno
Open in the simulatorNo account needed: press Simulate and it runs.

How it works

Three LEDs on D10 (red), D9 (yellow) and D8 (green) run the traffic light phases. Press SW1 (on D2, with the internal pull-up): green ends early and the light turns red for the pedestrians. The sketch uses millis() instead of delay(), so it always reads the button. The Uno is powered over USB; the serial console shows each phase with its time.

Wiring

Each line is one connection (net) and the pins it joins.

NetPins
GNDA1 GNDD1 KD2 KD3 KSW1 2
BTNA1 D2SW1 1
GRNA1 D8R3 1
GRN_AD3 AR3 2
REDA1 ~D10/SSR1 1
RED_AD1 AR1 2
YELA1 ~D9R2 1
YEL_AD2 AR2 2
D1
LED
D2
LED
D3
LED

Parts

Firmware

sketch.ino · 35 lines

// Traffic light: red D10, yellow D9, green D8. The button on D2 (to GND) asks for red:
// green ends early. No delay() in the loop, so the button is always read (millis state machine).
const int RED = 10, YELLOW = 9, GREEN = 8, BUTTON = 2;
enum Phase { RED_ON, RED_YELLOW, GREEN_ON, YELLOW_ON };
const unsigned long DURATION[] = { 4000, 1000, 5000, 1500 };   // ms per phase
Phase phase = RED_ON;
unsigned long since = 0;
bool request = false;

void show() {
  digitalWrite(RED, phase == RED_ON || phase == RED_YELLOW);
  digitalWrite(YELLOW, phase == RED_YELLOW || phase == YELLOW_ON);
  digitalWrite(GREEN, phase == GREEN_ON);
  const char *names[] = { "red", "red+yellow", "green", "yellow" };
  Serial.print(millis()); Serial.print(F(" ms: ")); Serial.println(names[phase]);
}

void setup() {
  Serial.begin(115200);
  pinMode(RED, OUTPUT); pinMode(YELLOW, OUTPUT); pinMode(GREEN, OUTPUT);
  pinMode(BUTTON, INPUT_PULLUP);
  show();
}

void loop() {
  if (digitalRead(BUTTON) == LOW && !request) { request = true; Serial.println(F("button: pedestrian waiting")); }
  unsigned long d = DURATION[phase];
  if (phase == GREEN_ON && request) d = 1000;               // shorten green
  if (millis() - since >= d) {
    phase = (Phase)((phase + 1) % 4);
    since = millis();
    if (phase == RED_ON) request = false;
    show();
  }
}
Open in the simulator

More examples: Arduino