# Multi-Way Traffic Light Control Tutorial

## Introduction

This tutorial extends the basic single traffic light example to handle two-way and three-way intersections. We'll explore the logic, safety considerations, and implementation strategies for realistic traffic control systems.

## Safety First: The Golden Rule

**Never have conflicting green lights!** This is the fundamental safety constraint in traffic light systems. Before we write any code, we must ensure that vehicles on collision courses never both have green lights.

## Understanding Traffic Light Phases

### UK Traffic Light Sequence (Single Direction)
1. **Green** (10s) - Go
2. **Amber** (3s) - Prepare to stop
3. **Red** (varies) - Stop
4. **Red + Amber** (2s) - Prepare to go
5. Back to Green

The red+amber phase is unique to UK/European systems and warns drivers to prepare for movement.

---

## Two-Way Traffic Lights

### Scenario: Simple Crossroads

Imagine a simple crossroads where:
- **Direction A**: North-South traffic
- **Direction B**: East-West traffic

### The Logic

At any given time:
- If A is green, B must be red
- If B is green, A must be red
- There's a transition period where both are red (for safety)

### State Diagram

```
State 1: A=Green,  B=Red      (10s)
         ↓
State 2: A=Amber,  B=Red      (3s)
         ↓
State 3: A=Red,    B=Red      (2s) ← Safety buffer
         ↓
State 4: A=Red,    B=Red+Amber (2s)
         ↓
State 5: A=Red,    B=Green     (10s)
         ↓
State 6: A=Red,    B=Amber     (3s)
         ↓
State 7: A=Red,    B=Red       (2s) ← Safety buffer
         ↓
State 8: A=Red+Amber, B=Red    (2s)
         ↓
Back to State 1
```

### Key Concepts

1. **All-Red Phase**: The 2-second period where both directions are red provides a safety buffer for clearing the intersection
2. **Alternating Priority**: Each direction gets its turn in strict sequence
3. **Predictable Timing**: Consistent timing helps drivers anticipate changes

---

## Three-Way Traffic Lights

### Scenario: T-Junction

Consider a T-junction with:
- **Direction A**: Main road (straight through)
- **Direction B**: Main road (opposite direction)
- **Direction C**: Side road (joining the main road)

### The Logic

This is more complex! We have two strategies:

#### Strategy 1: Paired Operation
- A and B operate together (they're on the same road)
- C operates independently
- This creates a two-way system: (A+B) vs C

#### Strategy 2: Sequential Operation
- Each direction gets its own green phase
- Order: A → B → C → repeat
- More complex but potentially more efficient

### State Diagram (Paired Operation)

```
Phase 1: A=Green, B=Green, C=Red        (12s)
         ↓
Phase 2: A=Amber, B=Amber, C=Red        (3s)
         ↓
Phase 3: A=Red,   B=Red,   C=Red        (2s) ← Safety buffer
         ↓
Phase 4: A=Red,   B=Red,   C=Red+Amber  (2s)
         ↓
Phase 5: A=Red,   B=Red,   C=Green      (8s)
         ↓
Phase 6: A=Red,   B=Red,   C=Amber      (3s)
         ↓
Phase 7: A=Red,   B=Red,   C=Red        (2s) ← Safety buffer
         ↓
Phase 8: A=Red+Amber, B=Red+Amber, C=Red (2s)
         ↓
Back to Phase 1
```

### State Diagram (Sequential Operation)

```
Phase 1:  A=Green, B=Red,   C=Red        (8s)
Phase 2:  A=Amber, B=Red,   C=Red        (3s)
Phase 3:  A=Red,   B=Red,   C=Red        (2s)
Phase 4:  A=Red,   B=Red+Amber, C=Red    (2s)
Phase 5:  A=Red,   B=Green, C=Red        (8s)
Phase 6:  A=Red,   B=Amber, C=Red        (3s)
Phase 7:  A=Red,   B=Red,   C=Red        (2s)
Phase 8:  A=Red,   B=Red,   C=Red+Amber  (2s)
Phase 9:  A=Red,   B=Red,   C=Green      (8s)
Phase 10: A=Red,   B=Red,   C=Amber      (3s)
Phase 11: A=Red,   B=Red,   C=Red        (2s)
Phase 12: A=Red+Amber, B=Red, C=Red      (2s)
Back to Phase 1
```

---

## Circuit Considerations

### GPIO Pin Allocation

**Two-Way System:**
```
Direction A: Red=2,  Amber=3,  Green=4
Direction B: Red=17, Amber=27, Green=22
```

**Three-Way System:**
```
Direction A: Red=2,  Amber=3,  Green=4
Direction B: Red=17, Amber=27, Green=22
Direction C: Red=10, Amber=9,  Green=11
```

### Current Draw

Each LED draws approximately 20mA through a 330Ω resistor:
- Two-way system: 6 LEDs max simultaneous = 120mA (safe)
- Three-way system: 9 LEDs max simultaneous = 180mA (safe)

The Raspberry Pi can safely source up to 50mA per GPIO pin and approximately 500mA total across all pins, so these configurations are well within limits.

---

## Programming Strategies

### 1. Sequential State Machine
Define each state explicitly and transition between them. Clear and easy to debug.

**Pros:**
- Very explicit and readable
- Easy to modify timing for specific states
- Simple to add sensor-based control

**Cons:**
- More code for complex systems
- Timing locked into state definitions

### 2. Generator Functions
Use Python generators to yield light states, leveraging gpiozero's `source` parameter.

**Pros:**
- Elegant and Pythonic
- Non-blocking operation
- Clean separation of logic

**Cons:**
- Harder to integrate dynamic control
- Less intuitive for beginners

### 3. Class-Based Design
Create a traffic light controller class with methods for each phase.

**Pros:**
- Object-oriented and scalable
- Easy to extend to more complex systems
- Can include logging, error handling, etc.

**Cons:**
- More complex setup
- Overkill for simple demonstrations

---

## Testing and Debugging

### Safety Checklist

Before running your code:
1. ✓ Verify no two conflicting directions can be green simultaneously
2. ✓ Check all-red safety buffers exist between direction changes
3. ✓ Confirm proper red+amber sequences
4. ✓ Test timing values are reasonable

### Simulation Mode

Add a print statement mode for testing without hardware:
```python
def set_lights(direction, red, amber, green):
    if SIMULATION:
        state = []
        if red: state.append('R')
        if amber: state.append('A')
        if green: state.append('G')
        print(f"{direction}: {'-'.join(state) if state else 'OFF'}")
    else:
        # Actual GPIO control
        pass
```

---

## Real-World Extensions

Once you've mastered the basics, consider:

1. **Pedestrian Crossings**: Add button-activated pedestrian phases
2. **Sensor-Based Timing**: Adjust green time based on traffic flow
3. **Emergency Vehicle Priority**: Override normal sequence for emergency vehicles
4. **Time-of-Day Adjustment**: Different timings for rush hour vs. off-peak
5. **Roundabout Control**: Even more complex multi-direction logic

---

## Learning Progression

1. Start with single traffic light (you've done this!)
2. Build two-way system with fixed timing
3. Add print statements to visualize state transitions
4. Extend to three-way (paired operation)
5. Try three-way sequential operation
6. Add button control for testing
7. Implement sensor-based extensions

---

## Common Mistakes to Avoid

1. **Forgetting all-red phases**: Cars need time to clear intersections
2. **Skipping red+amber**: UK drivers expect this warning
3. **Inconsistent timing**: Predictable patterns are safer
4. **No error handling**: What if a light fails?
5. **Blocking code**: Use non-blocking approaches for real systems

---

## Conclusion

Multi-way traffic light control is an excellent exercise in:
- State machine design
- Safety-critical system logic
- Timing and synchronization
- Real-world constraint management

The principles learned here apply to many embedded systems, robotics projects, and industrial control applications. Start simple, test thoroughly, and always prioritize safety!
