# Multi-Way Traffic Light Control Project

A comprehensive educational project demonstrating traffic light control systems from basic single lights to complex multi-way intersections.

## 📁 Project Files

### Documentation
- **`traffic_lights_tutorial.md`** - Complete tutorial explaining the logic and concepts

### Two-Way Intersection
- **`two_way_traffic_simple.py`** - Simple sequential state machine (best for learning)
- **`two_way_traffic_generator.py`** - Elegant generator-based approach

### Three-Way Intersection  
- **`three_way_traffic_paired.py`** - Paired operation (A+B vs C)
- **`three_way_traffic_sequential.py`** - Sequential operation (A → B → C)

### Advanced
- **`traffic_oo_controller.py`** - Object-oriented class-based design
- **`traffic_simulator.py`** - No-hardware simulation (test without GPIO)

## 🚦 Circuit Setup

### Two-Way System
```
Direction A (North-South):
  Red:   GPIO 2
  Amber: GPIO 3
  Green: GPIO 4

Direction B (East-West):
  Red:   GPIO 17
  Amber: GPIO 27
  Green: GPIO 22
```

### Three-Way System (adds Direction C)
```
Direction C (Side Road):
  Red:   GPIO 10
  Amber: GPIO 9
  Green: GPIO 11
```

### Component Requirements
- Raspberry Pi (any model with GPIO)
- 6 LEDs for two-way (9 for three-way):
  - 2-3 red LEDs
  - 2-3 amber/yellow LEDs
  - 2-3 green LEDs
- 6-9× 330Ω resistors (one per LED)
- Breadboard
- Jumper wires

## 🔧 Installation

1. Install required libraries:
```bash
sudo apt update
sudo apt install python3-gpiozero python3-rpi.gpio
```

2. Clone or download this project:
```bash
git clone <repository-url>
cd traffic-lights
```

3. Make scripts executable:
```bash
chmod +x *.py
```

## 🚀 Usage

### Start with Simulation (No Hardware)
Perfect for understanding the logic before building the circuit:
```bash
python3 traffic_simulator.py
```

### Two-Way Intersection

**Simple version (recommended for beginners):**
```bash
python3 two_way_traffic_simple.py
```

**Generator version (more elegant):**
```bash
python3 two_way_traffic_generator.py
```

### Three-Way Intersection

**Paired operation (main road vs side road):**
```bash
python3 three_way_traffic_paired.py
```

**Sequential operation (each direction takes turns):**
```bash
python3 three_way_traffic_sequential.py
```

### Object-Oriented Version

**Two-way:**
```bash
python3 traffic_oo_controller.py
```

**Three-way:**
```bash
python3 traffic_oo_controller.py three
```

## 📚 Learning Path

1. **Read the tutorial** - Start with `traffic_lights_tutorial.md`
2. **Run simulation** - Test with `traffic_simulator.py` (no hardware needed)
3. **Build circuit** - Set up LEDs on breadboard
4. **Two-way simple** - Run `two_way_traffic_simple.py`
5. **Two-way generator** - Try the elegant approach
6. **Three-way paired** - Extend to T-junction
7. **Three-way sequential** - More complex logic
8. **Object-oriented** - Professional software design

## 🎓 Key Concepts Covered

### Safety
- **Never conflicting greens** - Core safety rule
- **All-red phases** - Clearing time between changes
- **Predictable timing** - Consistent patterns for drivers

### UK Traffic Light Sequence
1. Green (10s)
2. Amber (3s)
3. Red (variable)
4. **Red + Amber** (2s) ← Unique to UK/Europe
5. Back to Green

### Software Techniques
- Sequential state machines
- Python generators
- Object-oriented design
- Non-blocking operation
- Logging and debugging

## 🔍 Understanding the Code

### State Machine Approach (Simple)
Each phase is explicitly coded in sequence:
```python
# Phase 1: A gets red+amber
set_lights(lights_a, red=True, amber=True)
set_lights(lights_b, red=True)
sleep(RED_AMBER_TIME)

# Phase 2: A gets green
set_lights(lights_a, green=True)
set_lights(lights_b, red=True)
sleep(GREEN_TIME)
```

**Pros:** Very clear, easy to modify
**Cons:** More code, harder to maintain at scale

### Generator Approach (Elegant)
Uses Python generators and gpiozero's `source`:
```python
def direction_a_sequence():
    while True:
        yield (1, 1, 0)  # red+amber
        sleep(RED_AMBER_TIME)
        yield (0, 0, 1)  # green
        sleep(GREEN_TIME)
        # ...

lights_a.source = direction_a_sequence()
```

**Pros:** Elegant, non-blocking, Pythonic
**Cons:** Harder to integrate dynamic control

### Object-Oriented Approach (Professional)
Classes encapsulate logic:
```python
class TrafficLightController:
    def set_state(self, state: LightState):
        # ...

class TwoWayIntersection(IntersectionController):
    def run_cycle(self):
        # ...
```

**Pros:** Scalable, testable, maintainable
**Cons:** More complex setup

## 🐛 Debugging Tips

### Check LED Polarity
LEDs have polarity - flat side or short leg is negative (cathode)

### Verify GPIO Pins
Use `gpio readall` to check pin numbering (BCM vs Board)

### Test Individual LEDs
```python
from gpiozero import LED
led = LED(2)
led.on()   # Should light up
led.off()  # Should turn off
```

### Use Print Statements
Add debug output to see state changes:
```python
print(f"Phase: A={lights_a.current_state}, B={lights_b.current_state}")
```

## 🎯 Challenges & Extensions

Once you've mastered the basics:

1. **Pedestrian Crossing** - Add button-activated crossing phase
2. **Sensor Integration** - Use motion sensors for adaptive timing
3. **Emergency Override** - Button to force all-red state
4. **Time-of-Day** - Different timings for rush hour vs off-peak
5. **Four-Way Junction** - Extend to full crossroads
6. **Roundabout Control** - Multiple entry/exit points
7. **Web Interface** - Control lights via web browser
8. **Data Logging** - Record traffic patterns to file

## 📊 Traffic Flow Optimization

### Two-Way Timing Analysis
```
Total cycle time: 34 seconds
- Direction A: 15s (44%)
- Direction B: 15s (44%)
- Safety buffers: 4s (12%)
```

### Three-Way Timing (Paired)
```
Total cycle time: 34 seconds
- Main road (A+B): 19s (56%)
- Side road (C): 13s (38%)
- Safety buffers: 4s (12%)
```

## ⚠️ Safety Warnings

1. **Never bypass safety checks** - Always include all-red phases
2. **Test thoroughly** - Verify logic before real-world deployment
3. **GPIO limits** - Don't exceed 50mA per pin or 500mA total
4. **Power safely** - Use proper power supply for Raspberry Pi
5. **Educational use** - These examples are for learning, not production traffic control!

## 🤝 Contributing

Feel free to:
- Report issues
- Suggest improvements
- Add new intersection types
- Create educational materials

## 📖 Further Reading

- [gpiozero Documentation](https://gpiozero.readthedocs.io/)
- [Raspberry Pi GPIO Pinout](https://pinout.xyz/)
- [UK Traffic Light Standards (TSRGD)](https://www.gov.uk/guidance/traffic-signs)
- [Traffic Signal Timing Manual (US)](https://ops.fhwa.dot.gov/)

## 📝 License

This is educational material intended for learning about:
- Embedded systems programming
- State machine design
- GPIO control
- Traffic engineering concepts

Not intended for real traffic control applications!

## 👨‍💻 Credits

Based on examples from the gpiozero documentation.
Extended for educational purposes to demonstrate multi-way traffic control logic.

---

**Remember:** Always prioritize safety in both software and hardware design! 🚦
