🚑 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.
2. Project Objectives
- Detect an approaching ambulance.
- Monitor traffic density.
- Count vehicles.
- Calculate emergency priority.
- Analyze traffic conditions using AI.
- Generate traffic clearance recommendations.
- Send Telegram text alerts.
- Send Telegram voice notifications.
- Store emergency data in Google Sheets.
- Upload IoT data to ThingSpeak.
- Display data on a PHP dashboard.
- 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
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
6. Complete Flowchart
7. Ambulance Detection
RFID Method
GPS Method
Emergency Button Method
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
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
- Open Telegram.
- Search for BotFather.
- Send: /newbot
- Enter your bot name.
- Copy the generated Bot Token.
- Create a Telegram group.
- Add the bot to the group.
- 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
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 ```
16. Agentic IoT Decision-Making
Example:
- Ambulance is detected.
- Traffic density is analyzed.
- AI determines emergency priority.
- AI generates a clearance recommendation.
- n8n sends Telegram alerts.
- Voice notification is generated.
- Google Sheets stores the event.
- ThingSpeak displays the data.
- 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
- Assemble the ESP32 hardware.
- Connect traffic sensors.
- Connect ambulance detection system.
- Connect emergency button.
- Connect LEDs and buzzer.
- Create the MySQL database.
- Deploy the PHP backend.
- Configure the ESP32 WiFi.
- Configure the API URL.
- Test ESP32 data transmission.
- Configure the n8n webhook.
- Configure the AI Agent.
- Configure Telegram Bot.
- Configure voice notification automation.
- Configure Google Sheets.
- Configure ThingSpeak.
- Test emergency ambulance detection.
19. Complete Operating Workflow
20. Future Enhancements
21. Safety Consideration
22. Final Project Summary
This project integrates ESP32, IoT sensors, Artificial Intelligence, n8n automation, Telegram notifications, voice alerts, Google Sheets, ThingSpeak, PHP and MySQL.
The system is suitable for Electrical Engineering, Electronics Engineering, IoT, Embedded Systems, Artificial Intelligence, Automation, Smart City, Final-Year Engineering and Research Projects.
```
No comments:
Post a Comment