Build a Smart Traffic Management System Using IoT

Published  November 19, 2025   0
V Vedhathiri
Author
IoT Based Smart Traffic System

In addition to causing delays, fuel waste, and increased pollution, traffic jams and congestion are serious concerns in cities and can occasionally result in fatalities. Traditional traffic light systems operate on fixed time intervals, often leading to unnecessary delays during periods of low traffic. To overcome this issue, in this project, vehicle flow in each lane is monitored in real time using infrared (IR) sensors controlled by an ESP32 microcontroller. The system enhances traffic flow efficiency by dynamically controlling the red, yellow, and green lights for each lane based on traffic density. Unlike conventional systems, this IoT project also features an online web server hosted by the ESP32. A web dashboard, accessible through the local IP address of the ESP32, allows users to view real-time lane activity and vehicle counts.

This system consists of four lanes. Each lane includes three indicator LEDs, red, yellow, and green and an IR sensor for vehicle detection. Acting as the primary controller for this ESP32 project:

1. Reads sensor inputs from each of the four lanes.
2. Determines which lane should receive the green light based on the number of vehicles.
3. Controls the LEDs to display each lane’s current status (red, yellow, or green).
4. Hosts a local web server dashboard that displays real-time traffic data, including active lanes and vehicle counts.
5. Maintains regular traffic flow if the number of vehicles does not exceed a defined limit.

Components  Required

Hardware:

Components

Quality

ESP32 Microcontroller 

1

Jumper cables 

Required amount

IR sensor 

4

Red, Yellow and  Green LED 

Each 3

USB cable 

1

Breadboard 

Required amount

Resistor (220ohms)

12

Software

  • Arduino IDE
  • Web Browser (for viewing dashboard)

Block Diagram for the Smart Traffic System

Let's look at the block diagram of the Smart Traffic System

Block Diagram for the Smart Traffic System

The above block diagram illustrates the connection of four IR sensors to the ESP32 microcontroller. For the four lanes, a set of red, yellow, and green LEDs is used for each lane to indicate the traffic signal status. The system is powered through a suitable power supply connected to the ESP32. Additionally, the web dashboard is connected via the ESP32’s Wi-Fi network, allowing real-time monitoring and control.

Circuit Diagram of the Smart Traffic System

The image below shows the circuit diagram of the Smart Traffic System

Circuit Diagram of the Smart Traffic System

The circuit diagram illustrates a Smart Traffic Management System using an ESP32. Four IR sensors (IR1–IR4) are connected to the ESP32 to detect vehicles in four lanes. Each lane has a set of Red, Yellow, and Green LEDs controlled by the ESP32 to manage traffic signals. A 5V regulated power supply powers all components, with a common ground connection. The ESP32’s Wi-Fi feature connects the system to a dashboard for real-time monitoring and control. This setup ensures efficient traffic flow by adjusting signal timing based on vehicle density.

Components

Connection to ESP3

IR 1

13

IR 2

12

IR 3

14

IR 4

15

Red LED(LANE 1)

32

Yellow LED

21

Green LED

16

Red LED (LANE 2)

33

Yellow LED

22

Green LED

17

Red LED(LANE 3)

27

Yellow LED

23

Green  LED

18

Red  LED(LANE 4)

26

Yellow LED

25

Green LED

19

Hardware Connection of the IoT Smart Traffic System

The above image shows the hardware connection of the smart traffic system.

Code Explanation

This program uses an ESP32 to control a smart traffic management system with four lanes. Each lane has red, yellow, and green LEDs along with an IR sensor to detect vehicles. The code connects the ESP32 to Wi-Fi and hosts a real-time web dashboard to display signal status and vehicle counts. It runs in two modes: normal and preemption. In normal mode, lanes cycle sequentially through green, yellow, and red based on preset timing. In preemption mode, if any lane has two or more vehicles waiting, all lanes turn red for safety before giving green priority to the congested lane. The system automatically resets vehicle counts, filters false sensor readings, and continuously updates the web interface to ensure smooth, efficient, and adaptive traffic flow.

These include network libraries that enable the ESP32 to connect via Wi-Fi and host a local webpage displaying live information

#include <WiFi.h>
#include <WebServer.h>
const char* WIFI_SSID = "your wifi name";
const char* WIFI_PASSWORD = "wifi password";

GREEN_DURATION_MS – Green light ON time (5 seconds).
YELLOW_DURATION_MS – Yellow light ON time (5 seconds).
ALL_RED_DELAY_MS – Delay for all red lights before preemption (2 seconds).
DEBOUNCE_MS – Time filter to avoid false IR triggers.

const unsigned long GREEN_DURATION_MS  = 5000;
const unsigned long YELLOW_DURATION_MS = 5000;
const unsigned long ALL_RED_DELAY_MS   = 2000;
const unsigned long DEBOUNCE_MS        = 80;

Each lane has 3 LEDs (Red, Yellow, Green) and one IR sensor.
The arrays define the corresponding GPIO pins of the ESP32 for each component.

const uint8_t NUM_LANES = 4;
const uint8_t greenLedPins[NUM_LANES]  = {16, 17, 18, 19};
const uint8_t yellowLedPins[NUM_LANES] = {21, 22, 23, 25};
const uint8_t redLedPins[NUM_LANES]    = {32, 33, 27, 26};
const uint8_t irPins[NUM_LANES]        = {13, 12, 14, 15};

An enumeration is used to represent the three possible states of each lane — RED, YELLOW, or GREEN.

enum SignalState { RED, YELLOW, GREEN };
SignalState laneState[NUM_LANES];
     uint8_t currentGreenIndex = 0;
unsigned long stateStartMillis = 0;
unsigned long stateDurationMs = GREEN_DURATION_MS;
These variables track which lane is currently green and for how long the current state has been active.

These variables handle vehicle counting.

vehicleCount[] – stores vehicle count for each lane.
irTriggered[] – ensures one count per vehicle.
lastIrChangeMillis[] – used to filter noise and prevent double-counting.

unsigned int vehicleCount[NUM_LANES] = {0, 0, 0, 0};
int lastIrState[NUM_LANES] = {HIGH, HIGH, HIGH, HIGH};
bool irTriggered[NUM_LANES] = {false, false, false, false};
unsigned long lastIrChangeMillis[NUM_LANES] = {0, 0, 0, 0};

These variables manage the preemption mode, preventing other signals from changing during priority switching.

bool inPreemption = false;
bool preemptionReady = false;
uint8_t preemptedLane = 0;

This function configures all LED pins as outputs and all IR sensor pins as inputs with internal pull-up resistors. Initially, all lanes are set to red for safety.

void setupPins() {
for (uint8_t i = 0; i < NUM_LANES; i++) {
pinMode(greenLedPins[i], OUTPUT);
pinMode(yellowLedPins[i], OUTPUT);
pinMode(redLedPins[i], OUTPUT);
pinMode(irPins[i], INPUT_PULLUP);
}
allRed();
}

It modifies the LED outputs for each lane depending on whether the lane’s state is red, yellow, or green

void setLaneState(uint8_t lane, SignalState s) {
laneState[lane] = s;
digitalWrite(greenLedPins[lane],  (s == GREEN));
digitalWrite(yellowLedPins[lane], (s == YELLOW));
digitalWrite(redLedPins[lane],    (s == RED));
}

This routine manages the typical traffic sequence where each lane cycles from green to yellow to red before advancing to the next lane.

When a lane turns green, its vehicle count is reset.

void handleNormalCycle() {
unsigned long now = millis();
if (inPreemption || preemptionReady) return;
if (now - stateStartMillis < stateDurationMs) return;
if (laneState[currentGreenIndex] == GREEN) {
setLaneState(currentGreenIndex, YELLOW);
stateStartMillis = now;
stateDurationMs = YELLOW_DURATION_MS;
} 
else if (laneState[currentGreenIndex] == YELLOW) {
setLaneState(currentGreenIndex, RED);
currentGreenIndex = (currentGreenIndex + 1) % NUM_LANES;
setLaneState(currentGreenIndex, GREEN);
vehicleCount[currentGreenIndex] = 0;
stateStartMillis = now;
stateDurationMs = GREEN_DURATION_MS;
}
}
  • This function continuously reads all IR sensors.
  • Vehicles are counted only when the lane is RED.
  • Each LOW pulse (vehicle passing) increases the count by one.
void checkIR() {
unsigned long now = millis();
for (uint8_t i = 0; i < NUM_LANES; i++) {
if (laneState[i] != RED) continue;
int reading = digitalRead(irPins[i]);
if (reading == LOW && !irTriggered[i]) {
irTriggered[i] = true;
vehicleCount[i]++;
} else if (reading == HIGH && irTriggered[i]) {
irTriggered[i] = false;
}
}
}

The logic monitors whether any red-signal lane accumulates two or more vehicles. If so, a short all-red phase is initiated before prioritising that lane

void checkPreemption() {
for (uint8_t i = 0; i < NUM_LANES; i++) {
if (laneState[i] == RED && vehicleCount[i] >= 2) {
allRed();
inPreemption = true;
preemptedLane = i;
stateStartMillis = millis();
stateDurationMs = ALL_RED_DELAY_MS;
preemptionReady = true;
break;}}}

After the 2-second all-red delay, this function activates green for the congested lane and resets its vehicle count.
Then the normal cycle resumes.

void handlePreemption() {
if (inPreemption && preemptionReady && (millis() - stateStartMillis >= stateDurationMs)) {
for (uint8_t i = 0; i < NUM_LANES; i++)
setLaneState(i, (i == preemptedLane) ? GREEN : RED);
vehicleCount[preemptedLane] = 0;
currentGreenIndex = preemptedLane;
stateStartMillis = millis();
stateDurationMs = GREEN_DURATION_MS;
inPreemption = false;
preemptionReady = false;
}
}

This continuously executes the main tasks:

  1. Updates the web dashboard
  2. Checks vehicle detection
  3. Handles preemption logic
  4. Maintains normal signal operation
void loop() {
server.handleClient();
checkIR();
checkPreemption();
handlePreemption();
handleNormalCycle();
}

Working Principle of the Smart Traffic System

The controller operates in an unending loop, successively cycling across each lane. However, it uses real-time sensor inputs to dynamically adjust to traffic circumstances. The following functional modes comprise the workflow:

Operation Modes

A. Normal Mode (Default Operation)

The first is the normal, in which the system functions similarly to a typical traffic light system, turning green for five seconds, yellow for five, and then red. If the number of vehicles does not exceed the limit, this option guarantees that the traffic signal's automated flow will remain uninterrupted.

Traffic Signal Normal Flow in Smart Traffic Management System

The image above shows the normal flow of the traffic signal when the vehicle count does not exceed the threshold.

Normal flow of Traffic Signal working demonstration

This illustrates the system operating in normal mode, where vehicle counts remain below the set threshold. In this state, the traffic lights switch automatically between lanes in a regular timed cycle, ensuring smooth and uninterrupted traffic flow.

B. Counting Mode (Phase  Of Vehicle Detection)

When a lane is in red in this mode, the associated infrared sensor is enabled and begins to count the number of vehicles that cross it. When one vehicle crosses, the IR sensor detects this as count 1 and transmits the information to the ESP32. This system continuously increments the count of the vehicle crossing the IR sensor until :

  1. The lane turns green(the lane count will automatically change to 0 when it gets a green signal).
  2. The count of the vehicle exceeds the limit.
IR Sensor Vehicle Detection


The above figure demonstrates the operation of the IR sensor as it detects an approaching vehicle.

C. Preemption Mode (Priority Handling For Congested Lanes)

In this mode, the ESP32 continuously monitors all lanes and identifies any red-light lane where the number of waiting vehicles exceeds a predefined threshold (two or more). Upon detection, the controller activates priority handling to clear that lane efficiently.

  • Safety Delay:
    All lanes are switched to red for approximately 2 seconds, ensuring a safe transition before changing signals.
  • Priority Green:
    The signal of the congested lane is turned green, allowing vehicles to move and reducing lane buildup.
  • Count Reset:
    After the green phase, the vehicle count for that lane is reset to zero to begin a new measurement cycle.
  • Resume Normal Flow:
    Once the priority lane is cleared, the system automatically returns to its standard cyclic operation.

This adaptive preemption strategy prevents prolonged congestion, optimises lane utilisation, and enhances overall traffic flow efficiency by dynamically responding to real-time traffic density.

 

Vehicle count sense working demonstration

This demonstrates the system’s preemption mode, where if any lane’s vehicle count exceeds the threshold, that lane automatically receives the green signal, while all others turn red to reduce congestion. These real-time lane changes and vehicle counts are simultaneously displayed on the IoT-based dashboard for monitoring and analysis.

D. Condition Reset

The system has an automated reset mechanism to guarantee accurate and trustworthy data. The matching car count is reset to zero each time a lane obtains the green signal. This keeps accurate traffic flow monitoring for each new cycle by preventing out-of-date or residual data from affecting the measurements of the current lane.

E. Web Dashboard And Real-Time Monitoring

This system's real-time web-based monitoring dashboard, which is housed directly on the ESP32 via its integrated Wi-Fi module, is a key component. The ESP32 immediately connects to the local Wi-Fi network when it is switched up, and the serial monitor shows its IP address. The dashboard shows the following when this IP address is viewed using any web browser (on a computer or smartphone connected to the same network):

  • Each lane's current signal state (Red, Yellow, or Green).
  • The number of cars in each lane in real time.

Every second, the website automatically refreshes to provide real-time traffic condition information. This feature improves system efficiency and convenience by enabling continuous traffic flow monitoring without the need for extra hardware.

IoT based dashboard for Smart Traffic System

The above image is the IoT based dashboard that shows the real-time data of the traffic system.

Future Improvements

Although this system reduces fuel wastage and saves time, further improvements can make it even more efficient and user-friendly.
Possible improvements include:

  • Integration with cloud IoT platforms such as Blynk or ThingSpeak could provide extended monitoring capabilities and data analytics.
  • Replacing the IR sensors with ESP32-CAM to increase the efficiency and handle the more congested lane.

The IoT-Based Smart Traffic Management System efficiently overcomes the drawbacks of traditional traffic lights by using real-time vehicle detection and dynamic signal control through the ESP32. With IR sensors and a web-based dashboard, the system reduces congestion, saves fuel, and improves traffic flow. It presents a practical and scalable solution for modern urban traffic management using IoT technology.

Similar Traffic Light Controller 

Previously, we have built many interesting projects on a traffic light controller. If you want to know more about those topics, links are given below.

Arduino Based 3-Way Traffic Light Controller

Arduino-Based 3-Way Traffic Light Controller

This Arduino-based 3-Way Traffic Light Controller project is a simple Arduino DIY project which is useful to understand the working of traffic lights which we see around us.

Edge AI-Powered Smart Traffic Light System

Edge AI-Powered Smart Traffic Light System

Develop an AI-powered adaptive traffic light system to tackle urban congestion, improve traffic flow, reduce emissions, and enhance safety using real-time edge processing on affordable hardware.

 Four Way Traffic Lights Circuit using 555 Timer IC

Four-Way Traffic Lights Circuit using 555 Timer IC

In this traffic signal project, we are going to design a circuit to control traffic lights on a four-way intersection. This circuit is designed using by 555 IC timer and a decade counter. 

Have any question related to this Article?

Add New Comment

Login to Comment Sign in with Google Log in with Facebook Sign in with GitHub