Contents — 26 sections
Project Overview
Adjusts signal timing to the traffic that is actually there — giving green to the busy approach and not stranding cars at an empty one — to ease congestion, within strict safety rules.
A fixed-time traffic signal is dumb: it gives each approach the same green regardless of whether ten cars or none are waiting, so you sit at a red light while the cross street is empty, and a queue builds on the busy approach while the quiet one gets green it does not need. Adaptive signals fix this by sensing the traffic that is actually present and adjusting the timing to it — extending green for a busy approach, cutting short a green that no one is using, and responding to demand in real time — which measurably reduces delay, queuing and the stop-start that wastes fuel and frays tempers. This project builds an educational adaptive-signal controller that demonstrates exactly that, within the strict safety framework real traffic control demands.
The core is demand sensing per approach — detecting how many vehicles are waiting or arriving on each — via inductive loops, radar, or camera-based counting, and feeding that into an adaptive timing algorithm. Instead of fixed phase lengths, the controller extends a green while vehicles keep arriving (up to a maximum), terminates it early when the approach clears, and allocates green preferentially to the busier movements — so the intersection's capacity follows the real, changing demand rather than a static assumption. The result is less time wasted on empty phases and less queuing on busy ones.
But traffic signals are safety-critical infrastructure, and this dominates the design. Real signals are governed by rigorous standards and must obey inviolable rules — minimum green times, mandatory amber/all-red clearance intervals so an intersection is never given conflicting greens, and fail-safe behaviour (a fault must drop to flashing red/amber or a safe fixed mode, never a dangerous state). The adaptive logic operates strictly within these constraints: it can only shorten or extend phases inside the safe minimum/maximum, and it can never compromise clearance or conflict-monitoring. The project is emphatic that a homebrew controller is an educational demonstration of adaptive timing, not a certified traffic controller, and that deploying real signals requires certified equipment, conflict monitors and regulatory approval. Within that honest, safety-first frame, it shows the genuine idea behind smart traffic control: sense the demand, adapt the timing to ease congestion, and never, ever break the safety rules that keep an intersection from becoming a crash.
What this project does
- Senses traffic demand per approach (loops/radar/camera counting)
- Extends green while vehicles arrive; terminates early when clear
- Allocates green preferentially to busier movements
- Reduces delay, queuing and stop-start congestion
- Enforces minimum green, amber/all-red clearance and no conflicting greens
- Fails safe (flashing red/amber or safe fixed mode) on fault
- Demonstrates adaptive timing within strict safety rules
Real-World Applications
| Setting | How it is used |
|---|---|
| Adaptive intersection control (educational) | Demonstrating demand-responsive signal timing to ease congestion. |
| Traffic-engineering study/simulation | Testing adaptive timing logic and its congestion benefit. |
| Smart-corridor concepts | Illustrating coordinated/adaptive signals along a route. |
| Education / demonstration | Teaching signal phases, clearance and adaptive control safely. |
Deployment contexts where a build of this kind earns its keep.
Features & Capabilities
- Per-approach demand sensing
- Adaptive green extension/termination and allocation
- Congestion reduction vs fixed-time
- Inviolable minimum-green and clearance intervals
- Conflict avoidance (never conflicting greens)
- Fail-safe on fault
- Explicit: educational, not a certified controller
Difficulty, Time & Required Skills
| Attribute | Value |
|---|---|
| Difficulty level | Advanced |
| Estimated completion time | 16–24 hours |
| Indicative build cost | ₹5,000 – ₹9,000 (demo) |
| Primary discipline | Smart City |
| Reference platform | ESP32 DevKit V1 (ESP-WROOM-32) |
Skills you should have (or will pick up)
- Vehicle demand sensing (loops/radar/camera)
- Adaptive signal timing (extend/terminate/allocate)
- Safety rules: minimum green, clearance, conflict avoidance
- Fail-safe design
- Understanding traffic-control standards (scope/limits)
Bill of Materials
Every part below is commonly available from Indian and international hobby-electronics suppliers. Prices are indicative 2026 retail figures in Indian rupees and will drift — treat them as a budgeting guide, not a quotation.
| Component | Key specification | Qty | Approx. cost |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 1 | ₹450 |
| TCRT5000 IR reflectance sensor module Ambient sunlight saturates it — shroud the sensor on outdoor robots. | 1–8 mm optimum sensing gap, 950 nm emitter, analogue + digital out | 1 | ₹45 |
| JSN-SR04T waterproof ultrasonic sensor The 25 cm blind zone matters — mount it above the maximum expected water level. | 25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam | 1 | ₹450 |
| WS2812B addressable RGB LED strip (60 LED/m) Budget 60 mA × LED count; add a 1000 µF cap and a 330 Ω series resistor on data. | 5 V, 60 mA per LED at full white, 800 kHz single-wire protocol, 8-bit per channel | 1 | ₹900 |
| 4-channel opto-isolated relay board All four coils energised draw ~280 mA — do not power from the MCU 5 V pin. | 4 × SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel | 1 | ₹280 |
| 0.96″ SSD1306 OLED display Static images burn in — invert or scroll the screen periodically. | 128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C | 1 | ₹250 |
| 5 V 3 A regulated SMPS adapter Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A. | 100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection | 1 | ₹350 |
| Vehicle detection per approach Reliable per-approach demand sensing | Inductive loop / radar / camera counting for demand | 4 | ₹6,400 |
| Signal heads (demo) + drivers Real heads/controllers must be certified | Red/amber/green heads and safe drivers (demo scale) | 4 | ₹8,000 |
| Conflict monitor (concept) Real signals require a certified conflict monitor | Independent check that conflicting greens never occur | 1 | ₹1,000 |
| Fail-safe supply/logic | Drops to flashing/safe mode on fault | 1 | ₹500 |
Estimated total: ₹18,625, excluding tools, shipping and consumables.
Tools and consumables
- Soldering iron (temperature controlled, 350 °C) with 0.8 mm 60/40 or lead-free solder
- Digital multimeter — continuity, DC volts and current ranges
- Wire strippers, flush cutters and a small set of precision screwdrivers
- Heat-shrink tubing and a heat gun (or a lighter, carefully)
- A laptop with a USB port and the toolchain listed above
Hardware Specifications
| Part | Specification | Supply | Interface | Reference |
|---|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | Dual-core Xtensa LX6 @ 240 MHz, 520 KB SRAM, 4 MB flash, Wi-Fi 802.11 b/g/n + BLE 4.2, 34 GPIO, 18× 12-bit ADC, 2× 8-bit DAC | 3.3 V logic / 5 V USB | UART, SPI, I²C, I²S, CAN, PWM | Datasheet |
| TCRT5000 IR reflectance sensor module | 1–8 mm optimum sensing gap, 950 nm emitter, analogue + digital out | 3.3–5 V | Analogue + digital | Datasheet |
| JSN-SR04T waterproof ultrasonic sensor | 25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam | 5 V | Trigger/Echo or UART | Datasheet |
| WS2812B addressable RGB LED strip (60 LED/m) | 5 V, 60 mA per LED at full white, 800 kHz single-wire protocol, 8-bit per channel | 5 V | 1-wire timed protocol | Datasheet |
| 4-channel opto-isolated relay board | 4 × SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel | 5 V coil | 4× digital | Datasheet |
| 0.96″ SSD1306 OLED display | 128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C | 3.3–5 V | I²C (0x3C) | Datasheet |
| 5 V 3 A regulated SMPS adapter | 100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection | 5 V | DC barrel / USB | Datasheet |
Consolidated electrical and interface specifications for every active part in the build.
Power Budget & Supply Sizing
Add up the typical active current of every part, then size the supply with at least 50 % headroom so transmit bursts and motor inrush never brown out the controller.
| Load | Supply rail | Typical current (mA) | Notes |
|---|---|---|---|
| ESP32 DevKit V1 (ESP-WROOM-32) | 3.3 V logic / 5 V USB | 160 | Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly. |
| TCRT5000 IR reflectance sensor module | 3.3–5 V | 20 | Ambient sunlight saturates it — shroud the sensor on outdoor robots. |
| JSN-SR04T waterproof ultrasonic sensor | 5 V | 30 | The 25 cm blind zone matters — mount it above the maximum expected water level. |
| WS2812B addressable RGB LED strip (60 LED/m) | 5 V | 60 | Budget 60 mA × LED count; add a 1000 µF cap and a 330 Ω series resistor on data. |
| 4-channel opto-isolated relay board | 5 V coil | 280 | All four coils energised draw ~280 mA — do not power from the MCU 5 V pin. |
| 0.96″ SSD1306 OLED display | 3.3–5 V | 20 | Static images burn in — invert or scroll the screen periodically. |
| 5 V 3 A regulated SMPS adapter | 5 V | 3000 | Measure the real output — many "3 A" adapters sag below 4.7 V at 2 A. |
Summed typical draw is 3570 mA. With a 1.5× design margin the supply should deliver at least 5400 mA continuously at the stated rail voltage.
Software Requirements & Development Environment
Reference toolchain: Arduino IDE 2.3.x with the ESP32 board package 3.x (or PlatformIO on VS Code). Anything newer normally works; anything older may lack the board definitions used here.
- Install the Arduino IDE 2.3.x (or PlatformIO if you prefer a real editor and dependency locking).
- Add
https://espressif.github.io/arduino-esp32/package_esp32_index.jsonunder File → Preferences → Additional Board Manager URLs, then install esp32 from the Boards Manager. - Set the correct port under Tools → Port. On Linux add yourself to the
dialoutgroup:sudo usermod -aG dialout $USERand log out and back in. - Open the Serial Monitor at 115200 baud — every sketch here logs its state there.
- Keep File → Preferences → Show verbose output during: compilation switched on while you are debugging build errors.
Required libraries
| Library | Why it is needed | Install |
|---|---|---|
| WiFi (ESP32 core) bundled | Station/AP connection management for the ESP32. | Bundled with the ESP32 Arduino core |
| PubSubClient 2.8 | Lightweight MQTT 3.1.1 client for constrained devices. | Library Manager → "PubSubClient" by Nick O'Leary |
| FastLED 3.6.x | Timing-exact WS2812B driver with colour-correction and palettes. | Library Manager → "FastLED" |
| Adafruit SSD1306 + GFX 2.5.x | Framebuffer and text/graphics primitives for the OLED. | Library Manager → "Adafruit SSD1306" |
| ArduinoJson 7.x | Zero-allocation JSON serialisation and parsing. | Library Manager → "ArduinoJson" by Benoit Blanchon |
Block Diagram
The block diagram shows the functional decomposition of the system — what senses, what decides, what acts, and where the data ends up.
Circuit Diagram & Wiring
Every signal line in the build is shown below, followed by a pin-by-pin connection table you can work through with a multimeter in hand.
| Peripheral | Peripheral pin | Controller pin | Signal |
|---|---|---|---|
| Approach detectors ×4 | in | GPIO 34/35/32/33 | Per-approach demand |
| Signal heads (R/A/G) | ctrl | relays/NeoPixel | Phase outputs |
| Conflict monitor | in | GPIO | No conflicting greens (independent) |
| Fail-safe | ctrl | GPIO 26 | Drop to safe mode on fault |
| OLED | SDA/SCL | GPIO 21/22 | Phase/timing status |
Wire one row at a time and tick it off — most "it does not work" reports trace back to a single swapped pair.
Wiring explanation
- This is an educational demonstration. Real traffic signals require certified controllers, certified conflict monitors and regulatory approval — do not deploy a homebrew controller on a live road.
- Sense demand per approach reliably (loops/radar/camera); the adaptive logic depends on it.
- Enforce inviolable rules in code and, ideally, with an independent conflict monitor: minimum green, mandatory amber/all-red clearance, and never conflicting greens.
- Design fail-safe: any fault, watchdog timeout or conflict detection must drop to flashing red/amber or a safe fixed mode.
- Keep the safety logic independent of the adaptive logic so adaptation can never violate safety.
System Architecture
Read the stack from the bottom up: physical hardware, the firmware that drives it, the transport that moves data off the device, and the software a human actually looks at.
Working Principle
Adaptive traffic control rests on one idea — match green time to real demand — and one non-negotiable constraint: safety comes absolutely first. A fixed-time signal allocates the same time to each movement regardless of who is there, so it systematically wastes capacity (green to empty approaches) and creates delay (red to full ones). Sensing the actual demand and adapting the timing to it recovers that wasted capacity and cuts delay — but a traffic signal is a machine that, if it ever gives green to conflicting movements, causes crashes, so every gain in efficiency must be won inside an inviolable safety envelope. The entire design is the interplay of these two: adapt as much as helps, never break the rules.
The efficiency mechanism is demand-responsive phase timing. The controller senses how many vehicles are waiting or arriving on each approach (via loops, radar, or camera counting) and uses that to make three decisions within each cycle: extend a green while vehicles keep arriving on that approach (so a platoon is not chopped in half), terminate a green early once its approach clears (so no time is wasted on an empty movement), and allocate the next green to the approach with the most waiting demand. The effect is an intersection whose timing continuously tracks the changing traffic rather than a static plan — less wasted green, shorter queues, fewer needless stops.
That adaptation, however, is permitted to move phase lengths only within a safe band, and the band is defined by rules that can never be violated. Every green has a minimum duration (so a phase, once started, runs long enough to be safe and to clear the pedestrians/vehicles that committed to it) and a maximum (so no approach is starved). Between conflicting phases there must be the mandatory amber and all-red clearance intervals — the time to stop and for the intersection to empty — which are fixed by safety, not by demand, and can never be shortened. And the controller must never display green to conflicting movements, a property so critical that real signals enforce it with an independent conflict monitor that will force the intersection to a safe state if the main controller ever tries. The adaptive logic proposes timings; the safety logic has absolute veto.
The final principle is fail-safe and honest scope. Any fault — a sensor failure, a watchdog timeout, a detected conflict, a power problem — must drop the intersection to a safe state: flashing red/amber (treating it as a stop or give-way) or a known-safe fixed-time mode, never a dark or dangerous state. This must-not-fail-dangerous property, the independent conflict monitoring, and the fixed clearance intervals are exactly why real traffic controllers are certified, standards-governed equipment subject to regulatory approval — and why this project is emphatic that it is an educational demonstration of the adaptive-timing idea, not a controller to put on a live road. Built and understood that way, it teaches the real substance of smart traffic control: sense the demand and adapt the timing to ease congestion, but subordinate every efficiency decision to minimum greens, mandatory clearance, conflict avoidance and fail-safe behaviour — because at an intersection, safety is not one goal among several; it is the constraint everything else lives inside.
The maths behind it
Adaptive green (extend/terminate)
Serve green g on approach A:
hold until t_green ≥ G_MIN (minimum green)
extend while vehicles arriving AND t_green < G_MAX
terminate when approach clears (gap-out) OR t_green = G_MAX
Adaptation lives strictly within [G_MIN, G_MAX].
Mandatory clearance (fixed by safety)
Between conflicting phases, ALWAYS:
amber (yellow) for T_amber + all-red for T_allred
These are fixed by safety (stopping + intersection clear
time) and are NEVER shortened by demand. Then and only then
may a conflicting green start.
Conflict avoidance + fail-safe
Invariant: no two conflicting movements green together.
independent conflict monitor forces SAFE state if violated.
On any fault/watchdog/conflict:
outputs → flashing red/amber (or safe fixed mode)
Never a dark/dangerous state.
Program Flowchart
The firmware is a single cooperative loop. Nothing blocks for long, so networking, sensing and the user interface all stay responsive.
Assembly Instructions
Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.
Build the safety framework FIRST
Implement the inviolable rules — minimum green, maximum green, mandatory amber/all-red clearance, and never conflicting greens — and a fail-safe that drops to flashing/safe mode on any fault. Ideally add an independent conflict monitor.
Add demand sensing
Sense demand per approach (loops/radar/camera counting) reliably, feeding the adaptive logic.
Add adaptive timing within the safety band
Extend/terminate greens and allocate to the busiest approach strictly within [G_MIN, G_MAX] and after full clearance.
Step-by-Step Implementation Guide
Work through these in order. Each step ends in something you can observe, so a failure is always localised to the step you just finished.
Run adaptive timing subordinate to safety
Serve a green no shorter than minimum, extend it on continued demand up to maximum, terminate on gap-out, then always run amber + all-red before the next (non-conflicting) phase.
cppadaptive-signal.ino#define G_MIN 7000UL // ms minimum green (safety) #define G_MAX 45000UL // ms maximum green (fairness) #define T_AMBER 3000UL // fixed by safety #define T_ALLRED 2000UL // fixed by safety // Decide when to end the current green (within the safe band). bool endGreen(uint32_t tGreen, bool arriving){ if (tGreen < G_MIN) return false; // never below minimum green if (tGreen >= G_MAX) return true; // fairness cap return !arriving; // gap-out when approach clears } // Transition to the next phase ALWAYS via mandatory clearance. void toNextPhase(int nextApproach){ setGreen(currentApproach, false); setAmber(currentApproach, true); safeDelay(T_AMBER); // amber setAmber(currentApproach, false); allRed(); safeDelay(T_ALLRED); // all-red clear // conflict monitor must confirm no conflict before any green: if (!conflictClear()) { failSafe(); return; } currentApproach = nextApproach; setGreen(nextApproach, true); // safe to go }if (tGreen < G_MIN) return false; // never below minimum greenA green can never be terminated before its minimum — a safety rule the adaptive logic cannot override.return !arriving; // gap-out when approach clearsWithin the safe band, the green ends when the approach clears (no more vehicles arriving), so no time is wasted on an empty movement.setAmber(...); safeDelay(T_AMBER); ... allRed(); safeDelay(T_ALLRED)Every phase change runs the mandatory amber and all-red clearance, fixed by safety and never shortened by demand.if (!conflictClear()) { failSafe(); return; }Before any new green, an independent conflict check must confirm no conflict; if it cannot, the intersection fails safe rather than risk conflicting greens.Allocate to demand, and fail safe
Choose the next green for the approach with the most waiting demand, and on any fault/watchdog/conflict drop to flashing red/amber or a safe fixed mode.
Complete Source Code
The listing below is complete and compiles as written — there are no elided sections. Read the annotations under each block before you upload it.
/* ═══════════════════════════════════════════════════════════════
Adaptive Traffic Signal — ESP32 (EDUCATIONAL DEMONSTRATION)
Adapts green timing to sensed demand per approach, strictly within
safety rules: minimum green, mandatory amber/all-red clearance, never
conflicting greens, and fail-safe on fault. NOT a certified traffic
controller — real signals need certified equipment and approval.
══════════════════════════════════════════════════════════════════ */
#include <WiFi.h>
#include <PubSubClient.h>
#define NAPP 4
#define G_MIN 7000UL
#define G_MAX 45000UL
#define T_AMBER 3000UL
#define T_ALLRED 2000UL
const int detPin[NAPP] = {34,35,32,33};
int currentApproach = 0; uint32_t greenStart = 0;
WiFiClient net; PubSubClient mqtt(net);
int demand(int a){ /* count/queue on approach a (loops/radar/camera) */
return readDemand(detPin[a]); }
bool arriving(int a){ return demand(a) > 0; }
// Independent safety checks (kept separate from adaptive logic).
bool conflictClear(){ return conflictMonitorOK(); } // certified in reality
void failSafe(){ flashingRedAmber(); } // safe state on fault
void setPhase(int a){ /* set greens/reds so ONLY approach a is green */ }
void amber(int a){ /* amber for approach a */ }
void allRed(){ /* all red */ }
void toNextPhase(int next){
amber(currentApproach); delay(T_AMBER); // mandatory amber
allRed(); delay(T_ALLRED); // mandatory all-red clearance
if (!conflictClear()){ failSafe(); return; } // never conflicting greens
currentApproach = next; greenStart = millis();
setPhase(next);
}
int busiestApproach(){
int best=currentApproach, bestD=-1;
for(int a=0;a<NAPP;a++){ if(a==currentApproach) continue;
int d=demand(a); if(d>bestD){bestD=d;best=a;} }
return best;
}
void setup(){
Serial.begin(115200);
WiFi.begin(WIFI_SSID,WIFI_PASS); mqtt.setServer(MQTT_HOST,1883);
if(!conflictClear()){ failSafe(); return; }
currentApproach=0; greenStart=millis(); setPhase(0);
}
void loop(){
if(!mqtt.connected()&&WiFi.status()==WL_CONNECTED) mqtt.connect("sig-1");
mqtt.loop();
if(!conflictClear()){ failSafe(); return; } // fault -> safe, always
uint32_t tGreen = millis() - greenStart;
bool end = false;
if (tGreen >= G_MIN){ // never below min green
if (tGreen >= G_MAX) end = true; // fairness cap
else if (!arriving(currentApproach)) end = true; // gap-out (adaptive)
}
if (end) toNextPhase(busiestApproach()); // give green to demand
static uint32_t last=0;
if (millis()-last>1000){ last=millis();
char m[160]; int n=snprintf(m,sizeof m,
"{\"green\":%d,\"t\":%lu,\"demand\":[",currentApproach,tGreen);
for(int a=0;a<NAPP;a++) n+=snprintf(m+n,sizeof m-n,"%d%s",demand(a),a<NAPP-1?",":"");
snprintf(m+n,sizeof m-n,"]}");
mqtt.publish("signal/1/status", m);
}
}
Configuration & Calibration
Configuration steps
- Set minimum/maximum green, and the mandatory amber/all-red clearance times per safety requirements.
- Configure per-approach demand sensing and the conflict-monitor/fail-safe behaviour.
- Set the allocation policy (busiest approach) within the safety band.
- Understand and respect the scope: educational, not a certified controller.
Calibration procedure
An uncalibrated sensor produces confident, precise, wrong numbers. Do this once per physical unit and record the constants.
Safety timings
Set minimum green and the fixed clearance intervals per safety standards; verify they are never violated by adaptation.
Demand sensing
Confirm per-approach detection reliably reflects demand (extend/gap-out behave).
Fail-safe
Verify any fault/conflict drops to flashing/safe mode; test the independent conflict check.
Network Architecture & Connectivity
Communication protocol
Phase, timing and per-approach demand publish for monitoring/study; safety (min green, clearance, conflict monitor, fail-safe) is local and independent of any network.
| Topic / endpoint | Direction | Payload |
|---|---|---|
signal/1/status | controller → dashboard | phase, timing, demand |
signal/1/event | controller → ops | fail-safe / fault |
signal/corridor | management → controllers | coordination (concept) |
Message contract between the device and the broker.
Cloud platform configuration
A dashboard shows phase/demand for study and coordination concepts; safety-critical control always runs locally and independently, never dependent on the network.
Dashboard setup
Phase and timing, per-approach demand, and fail-safe/fault events; congestion comparison in study.
Mobile app integration
Fault/fail-safe notifications (for the demo/study).
Security considerations
- Safety logic (min green, clearance, conflict monitor, fail-safe) is local and independent of the network.
- Never let a network command override safety.
- This is educational; real signals require certified equipment and approval.
Testing Procedure & Expected Output
Test from the bottom up. Confirm power, then each sensor in isolation, then the integrated loop — the first failing step tells you exactly where to look.
| Test | What you should see |
|---|---|
| Heavy demand on one approach | Its green extends (up to max); busy approach favoured |
| Approach clears mid-green | Green gaps-out after minimum — no wasted green |
| Demand below minimum-green time | Green still held for minimum (safety) |
| Force a conflict (test) | Fails safe to flashing; no conflicting greens |
| Simulate a fault/watchdog | Drops to safe state |
| Compare to fixed-time | Less delay/queuing under variable demand (simulation) |
Bench-test checklist. If a row fails, stop and fix it before moving on.
Expected output
The demo/dashboard shows the current phase, timing, per-approach demand, and any fail-safe events; adaptation is visibly subordinate to the safety rules.
{
"green": 0,
"t": 21000,
"demand": [3, 0, 5, 1]
}
Approach 0 has green (21 s in) but approach 2 has the most waiting demand — so after minimum green and gap-out (and full clearance), green passes to approach 2; any fault would instead force a safe flashing state.
Troubleshooting: Common Errors & Fixes
Performance Optimisation
- Run the control loop deterministically; safety timings must be exact.
- Keep safety logic independent of adaptive logic and of the network.
- Adapt only within [G_MIN, G_MAX] and after full clearance.
- Fail safe fast on any fault/conflict.
- Replace every
delay()with amillis()comparison — blocking delays are the single most common cause of dropped readings. - Sample sensors on a fixed cadence and publish on a slower one; you almost never need to transmit at the sampling rate.
- Move networking into its own FreeRTOS task so a slow DNS lookup cannot stall the control loop.
- Use
uint8_t/uint16_twhere the range allows; on an 8-bit AVR a 32-bit add costs four times as much. - Batch several samples into one MQTT publish. Radio time, not CPU time, dominates the energy budget.
- Set the MQTT keep-alive to a value that matches your reporting interval so the broker does not churn reconnections.
- For battery builds use deep sleep between samples: an ESP32 drops from ~160 mA awake to about 10 µA asleep, which is the difference between days and months of runtime.
Safety Precautions
- Traffic signals are SAFETY-CRITICAL and standards-governed. This is an educational demonstration, NOT a certified controller — real deployment requires certified equipment, certified conflict monitors and regulatory approval.
- Inviolable: minimum green, mandatory amber/all-red clearance, and never conflicting greens.
- Fail safe on any fault/watchdog/conflict — flashing red/amber or safe fixed mode, never a dangerous state.
- Keep safety logic independent so adaptation can never produce an unsafe state.
- Mains voltage kills. Anything on the load side of the relay is at 230 V. Do not work on a powered circuit, and never leave exposed mains wiring on a bench where someone could touch it.
- Keep at least 6 mm of creepage between the mains and low-voltage sides of any board you make, and never route mains tracks under the microcontroller.
- Have a qualified electrician do the final installation into a consumer unit or wall fitting. In most jurisdictions this is a legal requirement, not a suggestion.
- Fit an RCD/RCBO upstream and fuse the load appropriately for its rating.
- Wear eye protection when soldering or cutting, and solder in a ventilated space — rosin flux fumes are a respiratory irritant.
- Power the circuit through a bench supply with a current limit while you are testing. A 300 mA limit turns a wiring mistake into a beep instead of a dead board.
- Disconnect power before changing any wiring. Hot-plugging a sensor onto a live bus is the fastest way to lose a controller.
Maintenance
- Verify safety timings and fail-safe/conflict behaviour regularly.
- Check demand sensing reliability.
- Never remove or weaken the safety envelope.
- Keep the educational scope clear.
- Re-check every screw terminal and header after the first week — thermal cycling loosens connections that felt tight on day one.
- Keep the broker and dashboard containers patched, and rotate device credentials at least once a year.
- Recalibrate at the interval given in the calibration section, and keep the constants in a text file next to the firmware — not only in flash.
- Keep a short logbook of firmware versions and what changed. Six months later you will not remember why that constant is 1.083.
Future Improvements & Upgrades
A working v1 is a platform, not a finish line. These are the upgrades that add the most capability for the least rework.
- Add corridor coordination (green waves) within safety.
- Add pedestrian/priority (transit/emergency) phases safely.
- Add camera/AI demand sensing.
- Study/simulate congestion benefit rigorously.
- Design a proper PCB. Once the breadboard version has run for a month, moving to a two-layer board removes the intermittent-contact failures that dominate prototype faults.
- Add over-the-air firmware updates so you never have to physically reach a deployed node again.
- Add persistent local storage (microSD or the on-chip flash) so a network outage does not create a hole in your data.
- Move configuration out of the source: a captive-portal setup page or a JSON config file makes the build reusable without a recompile.
- Add a battery and solar option so the unit survives a power cut and can be sited away from a socket.
- Write a small test harness that feeds synthetic sensor values through the decision logic, so you can validate thresholds without physically triggering the event.
Frequently Asked Questions
References & Learning Resources
These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.
- Traffic signal controlReference
- Adaptive/actuated signal controlReference
- Signal clearance intervals (amber/all-red)Reference
- Conflict monitor / malfunction management unitReference
- Traffic-control standards (e.g. MUTCD)Reference