Agentic IoT with ESP32 + AI + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak
Table of Contents
1. Abstract 2. Objectives 3. System Architecture 4. Components List 5. Circuit Schematic 6. Working Principle 7. AI Accident Severity Prediction 8. n8n Automation Workflow 9. Telegram Bot and Voice Alerts 10. Google Sheets Integration 11. ThingSpeak Cloud Dashboard 12. ESP32 Source Code 13. PHP IoT Dashboard 14. AI Power Consumption Prediction 15. Testing Plan 16. Future Enhancements 17. Conclusion1. Abstract
Road accidents are a major cause of injuries and fatalities. In many accident situations, emergency services are not informed immediately. This project proposes an AI-powered smart vehicle accident detection and severity prediction system using ESP32, IoT sensors, AI, n8n automation, Telegram voice alerts, Google Sheets, ThingSpeak, and a PHP-based IoT webpage.
The ESP32 continuously monitors vehicle parameters such as acceleration, vibration, gyroscope movement, vehicle tilt, speed, GPS location, battery voltage, and power consumption. When abnormal sensor values are detected, the ESP32 sends structured data to an n8n webhook.
The AI system analyzes the sensor data and classifies the event as Normal, Minor, Moderate, or Critical. Based on the result, n8n automatically sends Telegram text alerts, generates voice notifications, stores data in Google Sheets, updates ThingSpeak, and provides data to the IoT dashboard.
2. Project Objectives
- Detect vehicle accidents using ESP32 and multiple sensors.
- Predict accident severity using AI-based logic.
- Send automatic emergency notifications.
- Generate Telegram voice alerts.
- Store accident records in Google Sheets.
- Display real-time data on ThingSpeak.
- Provide a PHP-based IoT monitoring webpage.
- Use n8n as the automation and integration platform.
- Predict vehicle power consumption.
- Provide an AI Agent for intelligent decision-making.
3. Overall System Architecture
4. Components List
| Component | Purpose |
|---|---|
| ESP32 | Main IoT controller with Wi-Fi connectivity |
| MPU6050 | Acceleration and gyroscope measurement |
| GPS Module | Vehicle location and speed |
| Vibration Sensor | Impact and vibration detection |
| Voltage Sensor | Vehicle battery monitoring |
| Buzzer | Local emergency alert |
| Wi-Fi Network | Internet communication |
| n8n | Workflow automation and AI orchestration |
| Telegram Bot | Text and voice notifications |
| Google Sheets | Historical accident data storage |
| ThingSpeak | Cloud IoT dashboard |
| PHP Web Server | Custom IoT monitoring webpage |
5. Circuit Schematic Diagram
MPU6050 Connection
| MPU6050 Pin | ESP32 Pin |
|---|---|
| VCC | 3.3V |
| GND | GND |
| SDA | GPIO 21 |
| SCL | GPIO 22 |
GPS Connection
| GPS Pin | ESP32 Pin |
|---|---|
| VCC | 5V / 3.3V according to module |
| GND | GND |
| TX | GPIO 16 |
| RX | GPIO 17 |
6. System Working Principle
- The vehicle is powered ON.
- ESP32 connects to Wi-Fi.
- All sensors are initialized.
- Sensor data is continuously monitored.
- Abnormal acceleration, vibration, tilt, or rotation is detected.
- ESP32 collects complete accident data.
- Data is transmitted to the n8n webhook.
- The AI Agent analyzes the data.
- Accident severity is calculated.
- n8n decides the required action.
- Telegram notifications are sent when required.
- Voice alert is generated for critical accidents.
- Data is stored in Google Sheets.
- ThingSpeak is updated.
- The PHP dashboard displays monitoring information.
7. AI Accident Severity Prediction
The system combines several sensor values instead of depending on only one sensor.
Severity Categories
| Score | Severity | Action |
|---|---|---|
| 0-20 | Normal | Continue monitoring |
| 21-40 | Minor | Store event |
| 41-70 | Moderate | Telegram warning |
| 71-100 | Critical | Emergency text and voice alert |
Severity Formula
Severity Score =
Acceleration Score
+ Gyroscope Score
+ Vibration Score
+ Speed Score
+ Tilt Score
Acceleration Formula
A = sqrt(Ax² + Ay² + Az²)
AI Agent Output Example
{
"accident_detected": true,
"severity": "CRITICAL",
"confidence": 0.96,
"severity_score": 89,
"send_telegram_alert": true,
"send_voice_alert": true,
"store_in_google_sheets": true,
"update_thingspeak": true
}
8. n8n Automation Workflow
n8n Severity Prediction Code
const data = $json;
const acceleration = Number(data.acceleration || 0);
const gyro = Number(data.gyro || 0);
const vibration = Number(data.vibration || 0);
const speed = Number(data.speed || 0);
const tilt = Number(data.tilt || 0);
let score = 0;
if (acceleration >= 8) {
score += 40;
} else if (acceleration >= 5) {
score += 30;
} else if (acceleration >= 3) {
score += 20;
}
if (gyro >= 250) {
score += 20;
} else if (gyro >= 150) {
score += 15;
} else if (gyro >= 80) {
score += 10;
}
if (vibration === 1) {
score += 15;
}
if (speed >= 80) {
score += 15;
} else if (speed >= 50) {
score += 10;
}
if (tilt >= 45) {
score += 10;
} else if (tilt >= 25) {
score += 5;
}
let severity = "NORMAL";
if (score >= 70) {
severity = "CRITICAL";
} else if (score >= 41) {
severity = "MODERATE";
} else if (score >= 21) {
severity = "MINOR";
}
return [{
json: {
...data,
severity_score: score,
severity: severity,
accident_detected: score >= 21
}
}];
9. Telegram Bot and Voice Alert Setup
- Open Telegram.
- Search for BotFather.
- Create a new bot.
- Copy the Bot Token.
- Send a message to your bot.
- Obtain the Chat ID.
- Configure Telegram credentials in n8n.
- Use the Send Message node for text alerts.
- Use a Text-to-Speech service to generate audio.
- Send the generated audio using Telegram.
Example Emergency Alert
🚨 VEHICLE ACCIDENT ALERT 🚨
Vehicle ID: ESP32_VEHICLE_001
Severity: CRITICAL
Severity Score: 85
Acceleration: 8.4 g
Gyroscope: 245.6
Speed: 65.2 km/h
Tilt: 43.5°
Vibration: Detected
Battery: 12.4 V
Location:
Latitude: 17.4123
Longitude: 78.4567
Immediate assistance may be required.
Voice Message
Emergency alert. A critical vehicle accident has been detected.
The estimated accident severity is critical.
The vehicle location has been identified.
Emergency assistance may be required immediately.
10. Google Sheets Integration
| Timestamp | Vehicle ID | Acceleration | Gyro | Vibration | Speed | Tilt | Severity | Score | Latitude | Longitude | Battery |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 2026-07-18 | ESP32_VEHICLE_001 | 8.4 | 245.6 | 1 | 65.2 | 43.5 | CRITICAL | 85 | 17.4123 | 78.4567 | 12.4 |
11. ThingSpeak Cloud Dashboard
| Field | Data |
|---|---|
| Field 1 | Acceleration |
| Field 2 | Gyroscope |
| Field 3 | Speed |
| Field 4 | Tilt |
| Field 5 | Battery Voltage |
| Field 6 | Severity Score |
| Field 7 | Accident Status |
field1 = 8.4
field2 = 245.6
field3 = 65.2
field4 = 43.5
field5 = 12.4
field6 = 85
field7 = 1
12. ESP32 Source Code
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
const char* webhookURL =
"https://YOUR_N8N_DOMAIN/webhook/vehicle-accident";
#define VIBRATION_PIN 27
#define BUZZER_PIN 26
void setup() {
Serial.begin(115200);
pinMode(VIBRATION_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
Wire.begin();
mpu.initialize();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected");
}
void loop() {
int16_t ax, ay, az;
int16_t gx, gy, gz;
mpu.getMotion6(
&ax,
&ay,
&az,
&gx,
&gy,
&gz
);
float accelerationX = ax / 16384.0;
float accelerationY = ay / 16384.0;
float accelerationZ = az / 16384.0;
float acceleration =
sqrt(
accelerationX * accelerationX +
accelerationY * accelerationY +
accelerationZ * accelerationZ
);
float gyro =
sqrt(
gx * gx +
gy * gy +
gz * gz
) / 131.0;
int vibration = digitalRead(VIBRATION_PIN);
if (acceleration > 3.0 || vibration == HIGH) {
digitalWrite(BUZZER_PIN, HIGH);
sendDataToN8N(
acceleration,
gyro,
vibration
);
delay(10000);
digitalWrite(BUZZER_PIN, LOW);
}
delay(1000);
}
void sendDataToN8N(
float acceleration,
float gyro,
int vibration
) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(webhookURL);
http.addHeader(
"Content-Type",
"application/json"
);
String jsonData = "{";
jsonData += "\"device_id\":\"ESP32_VEHICLE_001\",";
jsonData += "\"acceleration\":";
jsonData += String(acceleration, 2);
jsonData += ",";
jsonData += "\"gyro\":";
jsonData += String(gyro, 2);
jsonData += ",";
jsonData += "\"vibration\":";
jsonData += String(vibration);
jsonData += ",";
jsonData += "\"speed\":0,";
jsonData += "\"tilt\":0,";
jsonData += "\"battery_voltage\":12.4";
jsonData += "}";
int responseCode = http.POST(jsonData);
Serial.print("HTTP Response: ");
Serial.println(responseCode);
http.end();
}
}
13. PHP IoT Web Dashboard
This PHP page can be hosted on XAMPP, WAMP, LAMP, a VPS, or a PHP-enabled web server. It can be connected to a database, n8n webhook, ThingSpeak API, or another IoT backend.
Example PHP Dynamic Data Section
<?php
$vehicleStatus = "ONLINE";
$accidentStatus = "NORMAL";
$severityScore = 0;
$acceleration = 1.1;
$speed = 54;
$battery = 12.6;
?>
<h2>Vehicle Monitoring Dashboard</h2>
<p>Vehicle Status:
<?= $vehicleStatus ?>
</p>
<p>Accident Status:
<?= $accidentStatus ?>
</p>
<p>Severity Score:
<?= $severityScore ?>
</p>
<p>Acceleration:
<?= $acceleration ?> g
</p>
<p>Speed:
<?= $speed ?> km/h
</p>
<p>Battery:
<?= $battery ?> V
</p>
14. AI Power Consumption Prediction
The system can monitor battery voltage and current to calculate power consumption.
Power = Voltage × Current
Example:
Voltage = 12.4 V
Current = 4.5 A
Power = 12.4 × 4.5
Power = 55.8 W
Power Prediction Logic
const voltage = Number($json.battery_voltage || 0);
const current = Number($json.current || 0);
const power = voltage * current;
let prediction = "NORMAL";
if (power > 150) {
prediction = "HIGH POWER CONSUMPTION";
}
if (power > 250) {
prediction = "CRITICAL POWER CONSUMPTION";
}
return [{
json: {
...$json,
calculated_power: power,
power_prediction: prediction
}
}];
15. Testing Plan
| Test | Input Condition | Expected Result |
|---|---|---|
| Normal Driving | Acceleration 1.2 g, low vibration | Normal monitoring |
| Minor Impact | Acceleration 3.5 g | Minor accident |
| Moderate Impact | Acceleration 5.5 g, gyro 160 | Moderate alert |
| Severe Impact | Acceleration 8.5 g, vibration high, tilt 50 degrees | Critical text and voice alert |
16. Future Enhancements
- GSM or 4G LTE emergency communication.
- ESP32-CAM or Raspberry Pi camera integration.
- Machine learning models such as Random Forest, XGBoost, or Neural Networks.
- Automatic emergency service integration.
- Driver health monitoring.
- Fire and smoke detection.
- Fleet management dashboard.
- Multi-vehicle cloud monitoring.
- Predictive vehicle maintenance.
- Voice-based AI conversation after an accident.
17. Conclusion
The AI Smart Vehicle Accident Severity Prediction System combines ESP32 IoT sensing, AI-based accident analysis, n8n workflow automation, Telegram notifications, voice alerts, Google Sheets data storage, ThingSpeak cloud monitoring, and PHP web dashboard technology.
The ESP32 operates as the edge device, collecting real-time sensor information. The n8n automation system processes and routes the data. The AI Agent analyzes the accident situation and predicts severity. Telegram provides immediate communication, while Google Sheets and ThingSpeak provide storage and visualization.
The system is expandable and can be developed into a complete smart transportation safety platform for personal vehicles, public transportation, fleet management, insurance systems, and smart city applications.

No comments:
Post a Comment