Siddhant Kumar
Project 079 · Smart City

Adaptive Traffic Signal.

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.

Advanced 16–24 hours 31 min read TrafficVisionCity
Jump to source Bill of materials
Adaptive Traffic Signal — reference build illustration MCU VCC · GND · SIG · NC
Difficulty
Advanced
Build time
16–24 hours
Indicative cost
₹5,000 – ₹9,000 (demo)
Platform
ESP32 DevKit V1 (ESP-WROOM-32)
Category
Smart City
Last updated
28 July 2026
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.

A road traffic signal head
Adaptive signals match green time to the traffic actually present, easing congestion. Photograph sourced from Wikimedia Commons — Traffic light.jpg. Reused under the licence stated on that page; please check it before republishing.

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

SettingHow it is used
Adaptive intersection control (educational)Demonstrating demand-responsive signal timing to ease congestion.
Traffic-engineering study/simulationTesting adaptive timing logic and its congestion benefit.
Smart-corridor conceptsIllustrating coordinated/adaptive signals along a route.
Education / demonstrationTeaching 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

AttributeValue
Difficulty levelAdvanced
Estimated completion time16–24 hours
Indicative build cost₹5,000 – ₹9,000 (demo)
Primary disciplineSmart City
Reference platformESP32 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.

ComponentKey specificationQtyApprox. 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 DAC1₹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 out1₹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° beam1₹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 channel1₹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 channel1₹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²C1₹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 protection1₹350
Vehicle detection per approach
Reliable per-approach demand sensing
Inductive loop / radar / camera counting for demand4₹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 occur1₹1,000
Fail-safe supply/logicDrops to flashing/safe mode on fault1₹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

PartSpecificationSupplyInterfaceReference
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 DAC3.3 V logic / 5 V USBUART, SPI, I²C, I²S, CAN, PWMDatasheet
TCRT5000 IR reflectance sensor module1–8 mm optimum sensing gap, 950 nm emitter, analogue + digital out3.3–5 VAnalogue + digitalDatasheet
JSN-SR04T waterproof ultrasonic sensor25–450 cm, ±1 cm, IP67 sealed transducer, 45° beam5 VTrigger/Echo or UARTDatasheet
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 channel5 V1-wire timed protocolDatasheet
4-channel opto-isolated relay board4 × SPDT, 10 A @ 250 VAC, active-low inputs, LED per channel5 V coil4× digitalDatasheet
0.96″ SSD1306 OLED display128 × 64 monochrome, 1.3–3.3 V logic, 100 kHz–400 kHz I²C3.3–5 VI²C (0x3C)Datasheet
5 V 3 A regulated SMPS adapter100–240 VAC in, 5 V ±5 % out, 3 A, short-circuit and over-voltage protection5 VDC barrel / USBDatasheet

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.

LoadSupply railTypical current (mA)Notes
ESP32 DevKit V1 (ESP-WROOM-32)3.3 V logic / 5 V USB160Wi-Fi transmit bursts peak near 500 mA — size the regulator accordingly.
TCRT5000 IR reflectance sensor module3.3–5 V20Ambient sunlight saturates it — shroud the sensor on outdoor robots.
JSN-SR04T waterproof ultrasonic sensor5 V30The 25 cm blind zone matters — mount it above the maximum expected water level.
WS2812B addressable RGB LED strip (60 LED/m)5 V60Budget 60 mA × LED count; add a 1000 µF cap and a 330 Ω series resistor on data.
4-channel opto-isolated relay board5 V coil280All four coils energised draw ~280 mA — do not power from the MCU 5 V pin.
0.96″ SSD1306 OLED display3.3–5 V20Static images burn in — invert or scroll the screen periodically.
5 V 3 A regulated SMPS adapter5 V3000Measure 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.json under 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 dialout group: sudo usermod -aG dialout $USER and 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

LibraryWhy it is neededInstall
WiFi (ESP32 core) bundledStation/AP connection management for the ESP32.Bundled with the ESP32 Arduino core
PubSubClient 2.8Lightweight MQTT 3.1.1 client for constrained devices.Library Manager → "PubSubClient" by Nick O'Leary
FastLED 3.6.xTiming-exact WS2812B driver with colour-correction and palettes.Library Manager → "FastLED"
Adafruit SSD1306 + GFX 2.5.xFramebuffer and text/graphics primitives for the OLED.Library Manager → "Adafruit SSD1306"
ArduinoJson 7.xZero-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.

Adaptive Traffic Signal — system block diagramFunctional block diagram of the Adaptive Traffic Signal system. SenseApproach demandper approachAdapt (within limits)ESP32extend/terminateAllocatebusy approachSafety (independent)Min green/clearanceinviolableConflict monitorno conflictsOutputSignal headsR/A/GFail-safeflashing on faultrightrightnone
Adaptive Traffic Signal — system block diagram

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.

Adaptive Traffic Signal — wiring schematicConnection schematic showing which controller pin drives each peripheral. Sensors / InputsControllerActuators / OutputsESP32 DevKit V1(ESP-WROOM-32)3.3 V logic / 5 V USBApproach detectors ×4GPIO 34/35/32/33Per-approach demandSignal heads (R/A/G)relays/NeoPixelPhase outputsConflict monitorGPIONo conflictinggreens (independent)Fail-safeGPIO 26Drop to safe mode onfaultOLEDGPIO 21/22Phase/timing status
Adaptive Traffic Signal — wiring schematic
PeripheralPeripheral pinController pinSignal
Approach detectors ×4inGPIO 34/35/32/33Per-approach demand
Signal heads (R/A/G)ctrlrelays/NeoPixelPhase outputs
Conflict monitorinGPIONo conflicting greens (independent)
Fail-safectrlGPIO 26Drop to safe mode on fault
OLEDSDA/SCLGPIO 21/22Phase/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.
An ESP32 development board with the ESP-WROOM-32 module and USB connector
ESP32 module adapting phase timing within an inviolable safety envelope. Photograph sourced from Wikimedia Commons — ESP32 Espressif ESP-WROOM-32 Dev Board.jpg. Reused under the licence stated on that page; please check it before republishing.

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.

Adaptive Traffic Signal — architecture stackLayered architecture from hardware to user interface. Hardware layerESP32 DevKit V1 (ESP-WROOM-32) · TCRT5000 IR reflectance sensor module ·JSN-SR04T waterproof ultrasonic sensorDriver layerwifi · pubsub · fastled · ssd1306Application logicsampling loop · filtering · thresholds · state machineTransport layerWi-Fi + MQTT → traffic management (demo) · TLS · retry and backoffPresentation layerdashboard · mobile notifications · historical charts
Adaptive Traffic Signal — architecture stack

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)

plainAdaptive 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)

plainMandatory 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

plainConflict 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.

Adaptive Traffic Signal — firmware flowchartControl flow through the main program loop. Sense demand per approachGreen served min green?Vehicles still arriving?Hold green (min not met)Hold green (min not met)Vehicles still arriving?Extend green (≤ max)Amber + all-red clearanceExtend green (≤ max)Amber + all-red clearanceGive green to busiest waitingapproachFault/conflict? → fail safe
Adaptive Traffic Signal — firmware flowchart

Assembly Instructions

Build on a breadboard first and only commit to solder once the whole system has run for an hour without a fault.

  1. 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.

  2. Add demand sensing

    Sense demand per approach (loops/radar/camera counting) reliably, feeding the adaptive logic.

  3. 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.

  1. 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.
  2. 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.

cppadaptive-traffic-signal.ino
/* ═══════════════════════════════════════════════════════════════
   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);
  }
}
if(!conflictClear()){ failSafe(); return; } // fault -> safe, alwaysOn every loop, an independent conflict/fault check can force the intersection to a safe (flashing) state — safety has absolute veto over the adaptive logic.
if (tGreen >= G_MIN){ // never below min greenA green is only ever ended after its minimum duration, an inviolable safety rule.
else if (!arriving(currentApproach)) end = true; // gap-out (adaptive)Within the safe band, the green ends when the approach clears — the adaptive efficiency gain of not wasting green on empty movements.
void toNextPhase(int next)Every phase change runs mandatory amber and all-red clearance and re-checks for conflicts before any new green — the safety envelope the adaptation lives inside.
if (end) toNextPhase(busiestApproach())The next green is allocated to the approach with the most waiting demand — matching capacity to real traffic while obeying every safety rule.

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.

  1. Safety timings

    Set minimum green and the fixed clearance intervals per safety standards; verify they are never violated by adaptation.

  2. Demand sensing

    Confirm per-approach detection reliably reflects demand (extend/gap-out behave).

  3. Fail-safe

    Verify any fault/conflict drops to flashing/safe mode; test the independent conflict check.

Network Architecture & Connectivity

Adaptive Traffic Signal — network topologyPath taken by telemetry from field node to end user. Edge nodesGatewayCloudClientsSignal controllerESP32 (demo)Detectorsper approachWi-Fi 2.4 GHzRouterto managementMQTTTraffic dashboardphase/demandDashboardtiming/demandStudycongestion
Adaptive Traffic Signal — network topology

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 / endpointDirectionPayload
signal/1/statuscontroller → dashboardphase, timing, demand
signal/1/eventcontroller → opsfail-safe / fault
signal/corridormanagement → controllerscoordination (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.

TestWhat you should see
Heavy demand on one approachIts green extends (up to max); busy approach favoured
Approach clears mid-greenGreen gaps-out after minimum — no wasted green
Demand below minimum-green timeGreen still held for minimum (safety)
Force a conflict (test)Fails safe to flashing; no conflicting greens
Simulate a fault/watchdogDrops to safe state
Compare to fixed-timeLess 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.

jsonsignal.json
{
  "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.

A city skyline at night
Safety first: minimum green, mandatory clearance, no conflicting greens, and fail-safe — this is an educational demonstration, not a certified controller. Photograph sourced from Wikimedia Commons — Smart city.jpg. Reused under the licence stated on that page; please check it before republishing.

Troubleshooting: Common Errors & Fixes

Green ends too soon

Likely cause. Minimum green not enforced

Fix. Never terminate below G_MIN; enforce it independently of adaptation

Wasted green on empty approach

Likely cause. No gap-out

Fix. Terminate green (after min) when the approach clears

Conflicting greens risk

Likely cause. Safety not independent

Fix. Use an independent conflict monitor; never allow conflicting greens; fail safe

Unsafe state on fault

Likely cause. No fail-safe

Fix. Drop to flashing red/amber or safe fixed mode on any fault/watchdog/conflict

Treated as a real controller

Likely cause. Scope misunderstanding

Fix. This is educational; real signals need certified equipment, conflict monitors and approval

The sketch will not upload — "Failed to connect" or "avrdude: stk500_recv()"

Likely cause. The bootloader is not being reached: wrong port, wrong board, a serial monitor holding the port open, or a USB cable that only carries power.

Fix. Close every serial monitor, confirm Tools → Board and Port, and swap to a known data-capable USB cable. On an ESP32 hold BOOT while the IDE prints "Connecting…", then release. If a peripheral is wired to the UART pins (GPIO 1/3 on ESP32, D0/D1 on Uno) unplug it — it fights the programmer.

The board resets in a loop, or the serial monitor prints "Brownout detector was triggered"

Likely cause. The supply cannot deliver peak current. Wi-Fi transmit bursts, relay coils and servos all pull far more than their average draw.

Fix. Power peripherals from a separate regulated supply with a common ground rather than from the board 5 V pin. Add a 470–1000 µF electrolytic capacitor across the supply near the load, and use a real power adapter rather than a laptop USB port.

Serial monitor shows garbage characters

Likely cause. Baud rate mismatch between Serial.begin() and the monitor, or a floating/shared UART line.

Fix. Set the monitor to 115200 to match the sketch. If it still garbles, the crystal or the USB bridge is being confused by noise — shorten the cable and keep motor wiring away from the USB lead.

An I²C device is not detected

Likely cause. Wrong address, missing pull-ups, swapped SDA/SCL, or a bus too long for the pull-up value.

Fix. Run an I²C scanner sketch first — it should print the device address. Most breakout boards include 4.7 kΩ pull-ups, but if you have chained four of them the parallel resistance is too low; remove the pull-ups from all but one board. Keep the bus under 30 cm at 100 kHz.

Wi-Fi connects but MQTT never does (state -2)

Likely cause. Wrong broker address or port, a firewall in the way, or the broker requiring credentials the sketch is not sending.

Fix. Test from a laptop on the same network first: mosquitto_sub -h <broker> -t "#" -v. If that works, the problem is on the device — check the IP literal, port 1883 (or 8883 for TLS), and that client.setServer() runs before connect(). PubSubClient state codes are documented in its header.

Readings arrive for a while and then stop

Likely cause. The Wi-Fi or MQTT session dropped and the sketch never reconnects, or the broker dropped the client on keep-alive timeout.

Fix. Never assume the link stays up. Check WiFi.status() and client.connected() at the top of every loop and reconnect with exponential backoff. Add a watchdog so a wedged network stack reboots the device instead of going silent.

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 a millis() 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_t where 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

How does it reduce congestion?

By matching green time to real demand — extending green for a busy approach, ending green early when an approach clears, and giving the next green to the busiest waiting approach — instead of a fixed plan that wastes green on empty movements.

How is safety guaranteed?

By an inviolable envelope: minimum green times, mandatory amber and all-red clearance intervals (fixed by safety, never shortened), never displaying conflicting greens (enforced by an independent conflict monitor in real systems), and failing safe on any fault. Adaptation may only operate within these.

Can I put this on a real intersection?

No. This is an educational demonstration of the adaptive-timing idea. Real traffic signals are safety-critical and require certified controllers, certified conflict monitors and regulatory approval — a homebrew controller must never control live traffic.

What happens if something faults?

It fails safe — dropping to flashing red/amber (stop/give-way) or a known-safe fixed mode. It must never go dark or produce a dangerous state.

Why keep safety logic separate from the adaptive logic?

So that no bug or extreme in the adaptation can ever violate a safety rule. The adaptive logic proposes timings; the independent safety logic has absolute veto.

References & Learning Resources

These are the primary sources worth reading in full. Manufacturer datasheets always outrank forum posts when the two disagree.

  1. Traffic signal controlReference
  2. Adaptive/actuated signal controlReference
  3. Signal clearance intervals (amber/all-red)Reference
  4. Conflict monitor / malfunction management unitReference
  5. Traffic-control standards (e.g. MUTCD)Reference