Aim:
Simulate a real traffic light system with programmed timing.
Requirements:
- Arduino Uno or Raspberry Pi Pico
- Red, yellow, and green LEDs (1 each)
- 3 × 220 Ω resistors
- Breadboard and jumper wires
- USB cable and computer with Arduino IDE (or Thonny for Pico)
Working Principle:
Traffic lights use fixed cycles to manage traffic flow:
- Red → STOP
- Green → GO
- Yellow → Get ready to STOP
We will program LEDs to turn ON/OFF for specific durations, simulating real-world traffic control.
Circuit Diagram:
Arduino Pin 2 → [220Ω] → Red LED → GND
Arduino Pin 3 → [220Ω] → Yellow LED → GND
Arduino Pin 4 → [220Ω] → Green LED → GND
(Visual diagram can be included in the printed book)
Step-by-Step Instructions
Step 1: Wiring
- Place all three LEDs on the breadboard.
- Connect a 220 Ω resistor to each LED’s positive leg (anode).
- Connect the resistor ends to Arduino pins:
- Red → Pin 2
- Yellow → Pin 3
- Green → Pin 4
- Connect all LED cathodes (negative legs) to Arduino GND.
Step 2: Arduino Code (Delay Version)
void setup() {
pinMode(2, OUTPUT); // Red LED
pinMode(3, OUTPUT); // Yellow LED
pinMode(4, OUTPUT); // Green LED
}
void loop() {
// Red light – 5 seconds
digitalWrite(2, HIGH);
delay(5000);
digitalWrite(2, LOW);
// Green light – 5 seconds
digitalWrite(4, HIGH);
delay(5000);
digitalWrite(4, LOW);
// Yellow light – 2 seconds
digitalWrite(3, HIGH);
delay(2000);
digitalWrite(3, LOW);
}
Step 3: Upload and Test
- Open Arduino IDE → Select board → Upload code.
- Observe LEDs switching in the red → green → yellow order repeatedly.
Upgrading to a Timer (Non-Blocking) Version
Using millis() allows other actions (like reading a button) while lights run.
unsigned long previousMillis = 0;
int state = 0;
void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (state == 0 && currentMillis – previousMillis >= 5000) {
digitalWrite(2, LOW);
digitalWrite(4, HIGH);
previousMillis = currentMillis;
state = 1;
}
else if (state == 1 && currentMillis – previousMillis >= 5000) {
digitalWrite(4, LOW);
digitalWrite(3, HIGH);
previousMillis = currentMillis;
state = 2;
}
else if (state == 2 && currentMillis – previousMillis >= 2000) {
digitalWrite(3, LOW);
digitalWrite(2, HIGH);
previousMillis = currentMillis;
state = 0;
}
}
Real-World Variations of This Project:
- Pedestrian Crossing Button – Add a push button that triggers a special sequence for pedestrians.
- Smart Traffic Light – Use sensors to detect cars and change timing dynamically.
- Night Mode – Only blink yellow light during late hours.
Troubleshooting:
|
Problem |
Possible Cause |
Fix |
|
LEDs don’t light |
Wrong pin numbers in code |
Check wiring matches code |
|
All LEDs ON at once |
Forgot to turn previous LED OFF |
Add digitalWrite(…, LOW) |
|
LEDs too dim |
Wrong resistor value |
Use 220 Ω or 330 Ω |