Tuesday, 21 July 2026

AI-Based Smart Traffic Ambulance Clearance System

``` AI-Based Smart Traffic Ambulance Clearance System ```
```

🚑 AI-Based Smart Traffic Ambulance Clearance System

ESP32 + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak + PHP + MySQL

```
```

1. Full Project Description

The AI-Based Smart Traffic Ambulance Clearance System is an intelligent Agentic IoT project designed to detect an approaching ambulance, monitor traffic conditions, analyze traffic density, and assist authorized traffic personnel in creating a clear path for the ambulance.

The system uses ESP32 sensors to collect real-time traffic and emergency data. The collected data is sent through the Internet to a PHP backend and n8n automation workflow.

An AI Agent analyzes ambulance status, traffic density, vehicle count, emergency level, and other parameters. Based on the analysis, the AI generates a recommended emergency traffic clearance action.

Main Concept: SENSE → ANALYZE → DECIDE → AUTOMATE → ALERT → LOG → PREDICT
```
```

2. Project Objectives

  1. Detect an approaching ambulance.
  2. Monitor traffic density.
  3. Count vehicles.
  4. Calculate emergency priority.
  5. Analyze traffic conditions using AI.
  6. Generate traffic clearance recommendations.
  7. Send Telegram text alerts.
  8. Send Telegram voice notifications.
  9. Store emergency data in Google Sheets.
  10. Upload IoT data to ThingSpeak.
  11. Display data on a PHP dashboard.
  12. Predict future power consumption.
```
```

3. Components List

Component Purpose
ESP32 DevKit Main IoT controller
HC-SR04 Ultrasonic Sensor Vehicle detection
IR Vehicle Sensor Traffic counting
NEO-6M GPS Module Ambulance location tracking
RC522 RFID Reader Ambulance authentication
RFID Card or Tag Emergency vehicle identification
OLED Display Local data display
Buzzer Local emergency alert
Red LED Emergency status
Green LED Normal status
Current Sensor Power monitoring
Voltage Sensor Voltage measurement
5V Power Supply System power
```
```

4. Complete System Architecture

``` AMBULANCE ↓ GPS / RFID / SOS ↓ ESP32 CONTROLLER ↓ TRAFFIC SENSORS ↓ WiFi INTERNET ↓ PHP API + MySQL ↓ n8n AUTOMATION ↓ AI AGENT ↓ ┌────────────────────────────┐ │ Telegram Text Alert │ │ Telegram Voice Alert │ │ Google Sheets Logging │ │ ThingSpeak Cloud │ │ PHP Web Dashboard │ └────────────────────────────┘ ```
```
```

5. Circuit Schematic Diagram


                     +--------------------+
                     |       ESP32        |
                     |                    |
                     | GPIO 5  ----------|---- TRIG SENSOR 1
                     | GPIO 18 ----------|---- ECHO SENSOR 1
                     |                    |
                     | GPIO 19 ----------|---- TRIG SENSOR 2
                     | GPIO 21 ----------|---- ECHO SENSOR 2
                     |                    |
                     | GPIO 4  ----------|---- RFID SDA
                     | GPIO 22 ----------|---- RFID RST
                     | GPIO 27 ----------|---- EMERGENCY BUTTON
                     | GPIO 26 ----------|---- RED LED
                     | GPIO 25 ----------|---- GREEN LED
                     | GPIO 33 ----------|---- BUZZER
                     |                    |
                     |       WiFi         |
                     +---------┬----------+
                               |
                               ▼
                          INTERNET
                               |
          ┌────────────────────┼───────────────────┐
          ▼                    ▼                   ▼
    PHP + MySQL              n8n              ThingSpeak
     Dashboard            Automation             Cloud
                               |
                               ▼
                           AI AGENT
                               |
          ┌────────────────────┼───────────────────┐
          ▼                    ▼                   ▼
      Telegram            Google Sheets        Voice Alert

Important: The HC-SR04 ECHO pin may output 5V. ESP32 GPIO pins use 3.3V logic. Use a voltage divider for the ECHO signal.
```
```

6. Complete Flowchart

``` SYSTEM START ↓ INITIALIZE ESP32 ↓ CONNECT TO WiFi ↓ READ TRAFFIC SENSORS ↓ DETECT AMBULANCE ↓ ┌───────────────┐ │ Ambulance? │ └───────┬───────┘ │ ┌────┴────┐ │ │ NO YES │ │ ▼ ▼ NORMAL READ TRAFFIC DATA ↓ CALCULATE DENSITY ↓ AI ANALYSIS ↓ CALCULATE PRIORITY ↓ GENERATE ACTION ↓ SEND n8n ↓ ┌───────────┼───────────┐ ▼ ▼ ▼ Telegram Voice Google Sheets │ │ │ └───────────┼───────────┘ ▼ ThingSpeak ↓ PHP Dashboard ↓ LOOP ```
```
```

7. Ambulance Detection

RFID Method

``` RFID READER ↓ READ RFID UID ↓ COMPARE WITH REGISTERED ID ↓ AMBULANCE AUTHENTICATED ```

GPS Method

``` AMBULANCE GPS ↓ LATITUDE + LONGITUDE ↓ DISTANCE FROM JUNCTION ↓ ESTIMATE ARRIVAL TIME ```

Emergency Button Method

``` EMERGENCY BUTTON ↓ ESP32 ↓ WiFi ↓ EMERGENCY ALERT ```
```
```

8. AI Decision Logic

The AI Agent receives ambulance status, traffic density, vehicle count, emergency level, distance and power data.

```

Example:

Ambulance Detected = TRUE

Traffic Density = 85

Vehicle Count = 42

Emergency Level = 5

Priority Score =
Emergency Level × 30
+
Traffic Density × 0.3
+
Distance Factor

Priority > 150
= CRITICAL

Priority 100 to 150
= HIGH

Priority 50 to 100
= MEDIUM

Priority < 50
= NORMAL

```
```
```

9. ESP32 Source Code


```

#include 
#include 
#include 
#include 
#include 

#define TRIG1 5
#define ECHO1 18

#define TRIG2 19
#define ECHO2 21

#define RFID_SS 4
#define RFID_RST 22

#define EMERGENCY_BUTTON 27
#define RED_LED 26
#define GREEN_LED 25
#define BUZZER 33

const char* WIFI_SSID =
"YOUR_WIFI_NAME";

const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";

const char* SERVER_URL =
"https://your-domain.com/api/ambulance_data.php";

MFRC522 rfid(
RFID_SS,
RFID_RST
);

long readDistance(
int trigPin,
int echoPin
)
{
digitalWrite(
trigPin,
LOW
);

```
delayMicroseconds(
    2
);

digitalWrite(
    trigPin,
    HIGH
);

delayMicroseconds(
    10
);

digitalWrite(
    trigPin,
    LOW
);

long duration =
pulseIn(
    echoPin,
    HIGH,
    30000
);

long distance =
duration *
0.034 /
2;

return distance;
```

}

void connectWiFi()
{
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD
);

```
while(
    WiFi.status()
    != WL_CONNECTED
)
{
    delay(
        500
    );
}
```

}

void sendDataToServer(
bool ambulance,
int trafficDensity,
int vehicleCount,
int emergencyLevel
)
{
if(
WiFi.status()
== WL_CONNECTED
)
{
HTTPClient http;

```
    http.begin(
        SERVER_URL
    );

    http.addHeader(
        "Content-Type",
        "application/json"
    );

    StaticJsonDocument<512>
    json;

    json[
        "device_id"
    ] =
    "ESP32_AMBULANCE_001";

    json[
        "ambulance_detected"
    ] =
    ambulance;

    json[
        "traffic_density"
    ] =
    trafficDensity;

    json[
        "vehicle_count"
    ] =
    vehicleCount;

    json[
        "emergency_level"
    ] =
    emergencyLevel;

    json[
        "signal_status"
    ] =
    ambulance
    ?
    "CLEARANCE_REQUIRED"
    :
    "NORMAL";

    String requestBody;

    serializeJson(
        json,
        requestBody
    );

    http.POST(
        requestBody
    );

    http.end();
}
```

}

void setup()
{
Serial.begin(
115200
);

```
pinMode(
    TRIG1,
    OUTPUT
);

pinMode(
    ECHO1,
    INPUT
);

pinMode(
    TRIG2,
    OUTPUT
);

pinMode(
    ECHO2,
    INPUT
);

pinMode(
    EMERGENCY_BUTTON,
    INPUT_PULLUP
);

pinMode(
    RED_LED,
    OUTPUT
);

pinMode(
    GREEN_LED,
    OUTPUT
);

pinMode(
    BUZZER,
    OUTPUT
);

SPI.begin();

rfid.PCD_Init();

connectWiFi();

digitalWrite(
    GREEN_LED,
    HIGH
);
```

}

void loop()
{
long distance1 =
readDistance(
TRIG1,
ECHO1
);

```
long distance2 =
readDistance(
    TRIG2,
    ECHO2
);

int vehicleCount =
0;

if(
    distance1
    < 30
)
{
    vehicleCount++;
}

if(
    distance2
    < 30
)
{
    vehicleCount++;
}

int trafficDensity =
vehicleCount *
50;

bool emergencyButton =
digitalRead(
    EMERGENCY_BUTTON
)
==
LOW;

if(
    emergencyButton
)
{
    digitalWrite(
        RED_LED,
        HIGH
    );

    digitalWrite(
        GREEN_LED,
        LOW
    );

    digitalWrite(
        BUZZER,
        HIGH
    );

    sendDataToServer(
        true,
        trafficDensity,
        vehicleCount,
        5
    );

    delay(
        5000
    );

    digitalWrite(
        BUZZER,
        LOW
    );
}
else
{
    digitalWrite(
        RED_LED,
        LOW
    );

    digitalWrite(
        GREEN_LED,
        HIGH
    );

    sendDataToServer(
        false,
        trafficDensity,
        vehicleCount,
        0
    );
}

delay(
    10000
);
```

}

```
```
```

10. n8n Workflow Automation

``` ESP32 HTTP REQUEST ↓ WEBHOOK ↓ JSON VALIDATION ↓ AI AGENT ↓ EMERGENCY CONDITION ↓ ┌────────────────────────────┐ │ Telegram Text │ │ Telegram Voice │ │ Google Sheets │ │ ThingSpeak │ │ PHP Dashboard │ └────────────────────────────┘ ```

AI Agent Prompt

```

You are an intelligent emergency traffic management AI agent.

Analyze the following ambulance traffic data:

Ambulance Detected:
{{ $json.ambulance_detected }}

Traffic Density:
{{ $json.traffic_density }}

Vehicle Count:
{{ $json.vehicle_count }}

Emergency Level:
{{ $json.emergency_level }}

Your task is to:

1. Determine emergency priority.
2. Classify traffic condition.
3. Recommend a safe traffic clearance action.
4. Generate a Telegram alert.
5. Generate a voice notification.
6. Return JSON only.

Required JSON:

{
"priority": "CRITICAL",
"traffic_condition": "HIGH",
"recommended_action":
"Clear emergency lane and notify traffic controller",
"telegram_message":
"Emergency ambulance detected. Please clear the emergency lane immediately.",
"voice_message":
"Attention. Emergency ambulance approaching. Please clear the emergency lane immediately."
}

```

n8n Workflow JSON


```

{
"name":
"AI Ambulance Traffic Clearance",

```
"nodes":
[
    {
        "name":
        "ESP32 Webhook",

        "type":
        "n8n-nodes-base.webhook",

        "parameters":
        {
            "path":
            "ambulance-alert",

            "httpMethod":
            "POST"
        }
    },

    {
        "name":
        "Emergency Detected?",

        "type":
        "n8n-nodes-base.if",

        "parameters":
        {
            "conditions":
            {
                "boolean":
                [
                    {
                        "value1":
                        "={{$json.ambulance_detected}}",

                        "operation":
                        "isTrue"
                    }
                ]
            }
        }
    },

    {
        "name":
        "Telegram Alert",

        "type":
        "n8n-nodes-base.telegram",

        "parameters":
        {
            "chatId":
            "YOUR_TELEGRAM_CHAT_ID",

            "text":
            "AMBULANCE ALERT: Traffic clearance required immediately."
        }
    },

    {
        "name":
        "Google Sheets Log",

        "type":
        "n8n-nodes-base.googleSheets",

        "parameters":
        {
            "operation":
            "append",

            "documentId":
            "YOUR_GOOGLE_SHEET_ID",

            "sheetName":
            "AmbulanceData"
        }
    }
]
```

}

```
```
```

11. Telegram Bot Setup

  1. Open Telegram.
  2. Search for BotFather.
  3. Send: /newbot
  4. Enter your bot name.
  5. Copy the generated Bot Token.
  6. Create a Telegram group.
  7. Add the bot to the group.
  8. Configure the bot credentials in n8n.

Example Telegram Alert

```

🚨 CRITICAL EMERGENCY 🚨

Ambulance detected.

Traffic Density: HIGH

Vehicle Count: 42

Emergency Level: CRITICAL

Please clear the emergency lane immediately.

```
```
```

12. Voice Notification Automation

``` AI TEXT ↓ TEXT-TO-SPEECH SERVICE ↓ AUDIO FILE ↓ TELEGRAM VOICE MESSAGE ```

Example voice notification:

```

Attention.

Critical emergency.

Ambulance approaching.

Traffic density is high.

Please clear the emergency lane immediately.

```
```
```

13. Google Sheets Integration

Create a Google Sheet with the following columns:

Column Description
Timestamp Event date and time
Device ID ESP32 identification
Ambulance Detected YES or NO
Traffic Density Traffic percentage
Vehicle Count Number of detected vehicles
Emergency Level Emergency priority
Recommended Action AI recommendation
Power Consumption Measured system power
```
```

14. ThingSpeak Cloud Dashboard

Recommended ThingSpeak fields:

  • Field 1: Traffic Density
  • Field 2: Vehicle Count
  • Field 3: Ambulance Status
  • Field 4: Emergency Level
  • Field 5: Power Consumption
  • Field 6: Priority Score

ThingSpeak can display real-time graphs, gauges, emergency events, and power consumption trends.

```
```

15. AI Power Consumption Prediction

```

Power = Voltage × Current

Example:

Voltage = 5V

Current = 0.5A

Power = 5 × 0.5

Power = 2.5 Watts

Energy = Power × Time

```
``` COLLECT POWER DATA ↓ STORE HISTORICAL DATA ↓ AI TREND ANALYSIS ↓ PREDICT FUTURE POWER ↓ GENERATE WARNING ↓ TELEGRAM NOTIFICATION ```
```
```

16. Agentic IoT Decision-Making

``` OBSERVE ↓ ANALYZE ↓ DECIDE ↓ ACT ↓ LEARN ```

Example:

  1. Ambulance is detected.
  2. Traffic density is analyzed.
  3. AI determines emergency priority.
  4. AI generates a clearance recommendation.
  5. n8n sends Telegram alerts.
  6. Voice notification is generated.
  7. Google Sheets stores the event.
  8. ThingSpeak displays the data.
  9. PHP dashboard shows the live status.
```
```

17. Recommended Project Folder Structure

```

ambulance-smart-system/

│
├── index.html
│
├── config.php
│
├── database.sql
│
├── api/
│   ├── ambulance_data.php
│   ├── get_latest_data.php
│   └── power_data.php
│
├── admin/
│   ├── login.php
│   └── dashboard.php
│
├── assets/
│   ├── css/
│   │   └── style.css
│   │
│   └── js/
│       └── dashboard.js
│
├── esp32/
│   └── ambulance_traffic.ino
│
├── n8n/
│   └── ambulance_workflow.json
│
└── README.md

```
```
```

18. Step-by-Step Deployment Guide

  1. Assemble the ESP32 hardware.
  2. Connect traffic sensors.
  3. Connect ambulance detection system.
  4. Connect emergency button.
  5. Connect LEDs and buzzer.
  6. Create the MySQL database.
  7. Deploy the PHP backend.
  8. Configure the ESP32 WiFi.
  9. Configure the API URL.
  10. Test ESP32 data transmission.
  11. Configure the n8n webhook.
  12. Configure the AI Agent.
  13. Configure Telegram Bot.
  14. Configure voice notification automation.
  15. Configure Google Sheets.
  16. Configure ThingSpeak.
  17. Test emergency ambulance detection.
```
```

19. Complete Operating Workflow

``` 🚑 AMBULANCE ↓ 📡 ESP32 DETECTION ↓ 🚦 TRAFFIC SENSOR DATA ↓ 🌐 INTERNET ↓ 🧠 AI AGENT ↓ ⚙️ n8n AUTOMATION ↓ 📱 TELEGRAM TEXT ALERT ↓ 🔊 TELEGRAM VOICE ALERT ↓ 📊 GOOGLE SHEETS ↓ ☁️ THINGSPEAK ↓ 🖥️ PHP WEB DASHBOARD ```
```
```

20. Future Enhancements

Computer Vision Vehicle Detection
AI Traffic Prediction
GPS Ambulance Tracking
ETA Prediction
Multi-Junction Green Corridor
Android Mobile Application
Solar-Powered IoT Node
Accident Detection
Edge AI Processing
5G Communication
Multiple Ambulance Coordination
Hospital Arrival Prediction
```
```

21. Safety Consideration

For real public-road deployment, this prototype should not directly control traffic signals without approval from authorized traffic authorities.
``` DETECTION ↓ AI RECOMMENDATION ↓ AUTHORIZED CONTROLLER APPROVAL ↓ TRAFFIC CLEARANCE ```
```
```

22. Final Project Summary

This project integrates ESP32, IoT sensors, Artificial Intelligence, n8n automation, Telegram notifications, voice alerts, Google Sheets, ThingSpeak, PHP and MySQL.

Final System Concept: SENSE → UNDERSTAND → DECIDE → AUTOMATE → ALERT → LOG → PREDICT

The system is suitable for Electrical Engineering, Electronics Engineering, IoT, Embedded Systems, Artificial Intelligence, Automation, Smart City, Final-Year Engineering and Research Projects.

```
```

© 2026 AI Smart Traffic Ambulance Clearance System

ESP32 + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak + PHP + MySQL

```

No comments:

Post a Comment