Tuesday, 21 July 2026

AI-Based Smart Water Leakage Detection and Alert System

``` AI-Based Smart Water Leakage Detection and Alert System ```
```

AI-Based Smart Water Leakage Detection and Alert System

ESP32 + IoT + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak Cloud Dashboard


AI-Powered ESP32 Agentic IoT n8n Automation Telegram Alerts Cloud Dashboard ```
```

1. Complete Project Overview

The AI-Based Smart Water Leakage Detection and Alert System is an intelligent Agentic IoT platform designed to detect water leakage, abnormal water consumption, pipe bursts, continuous water flow, and unusual water usage.

The ESP32 acts as the main IoT controller. It collects data from water flow sensors, leakage sensors, temperature sensors, and optional water-level sensors.

The collected data is transmitted through Wi-Fi to a PHP IoT API, n8n automation workflow, ThingSpeak cloud dashboard, Google Sheets, and an AI Agent.

When the AI Agent detects a possible water leakage, the system automatically generates Telegram text alerts, voice notifications, data logs, and maintenance alerts.

```
```

2. Main Project Objectives

Water Leakage Detection

Detect abnormal water flow and physical water leakage.

AI-Based Analysis

Analyze sensor data and calculate leakage probability.

Telegram Notification

Send instant Telegram alerts when leakage is detected.

Voice Notification

Automatically generate and send voice alerts.

Cloud Monitoring

Display real-time data using ThingSpeak.

Historical Data

Store sensor information in Google Sheets.

```
```

3. Complete System Architecture

```

+-------------------------------------------------------------+
|                     WATER PIPELINE                          |
|                                                             |
|        +----------------+       +----------------+          |
|        | Water Flow     |       | Water Leakage  |          |
|        | Sensor         |       | Sensor         |          |
|        +--------+-------+       +--------+-------+          |
|                 |                         |                |
+-----------------+-------------------------+----------------+
|
v
+------------------------+
|        ESP32            |
|                        |
| Sensor Reading         |
| Wi-Fi Communication    |
| Local Alarm             |
+-----------+------------+
|
+-----------+------------+
|                        |
v                        v
+---------------+       +------------------+
| PHP IoT API   |       | ThingSpeak Cloud |
+-------+-------+       +------------------+
|
v
+---------------+
| MySQL Database|
+-------+-------+
|
v
+---------------+
| IoT Webpage   |
| Dashboard     |
+---------------+

ESP32
|
v
n8n Webhook
|
v
AI Agent
|
+------------------+
|                  |
v                  v
Telegram Alert   Google Sheets
|
v
Voice Notification 
```

4. Hardware Components List

Component Quantity Purpose
ESP32 DevKit V1 1 Main IoT controller
YF-S201 Water Flow Sensor 1 or more Measures water flow
Water Leakage Sensor 1 or more Detects physical water presence
DS18B20 Temperature Sensor 1 Measures pipe temperature
HC-SR04 Ultrasonic Sensor Optional Measures tank water level
Buzzer 1 Local warning
Red LED 1 Leakage indication
Green LED 1 Normal operation indication
OLED Display 1 Local data display
5V Power Supply 1 Power source
Waterproof Enclosure 1 Protects electronics
```
```

5. ESP32 Pin Configuration

ESP32 Pin Component
GPIO 27 Water Flow Sensor Signal
GPIO 34 Leakage Sensor Analog Output
GPIO 4 DS18B20 Temperature Sensor
GPIO 5 Buzzer
GPIO 2 Red LED
GPIO 15 Green LED
GPIO 21 OLED SDA
GPIO 22 OLED SCL
```
```

6. Circuit Schematic Diagram

                     +----------------------+
                     |        ESP32         |
                     |                      |
                     | GPIO27 <-------------| FLOW SENSOR
                     |                      |
                     | GPIO34 <-------------| LEAK SENSOR
                     |                      |
                     | GPIO4  <-------------| DS18B20
                     |                      |
                     | GPIO5  --------------> BUZZER
                     |                      |
                     | GPIO2  --------------> RED LED
                     |                      |
                     | GPIO15 --------------> GREEN LED
                     |                      |
                     | GPIO21 <-------------> OLED SDA
                     | GPIO22 <-------------> OLED SCL
                     |                      |
                     | 3.3V ---------------> SENSOR VCC
                     | GND ----------------> COMMON GROUND
                     +----------------------+

   +------------------+
   | WATER FLOW SENSOR|
   +------------------+
      VCC  ----------> ESP32 VCC
      GND  ----------> ESP32 GND
      SIGNAL --------> GPIO27


   +------------------+
   | LEAK SENSOR      |
   +------------------+
      VCC  ----------> ESP32 VCC
      GND  ----------> ESP32 GND
      ANALOG --------> GPIO34


   +------------------+
   | DS18B20 SENSOR   |
   +------------------+
      VCC  ----------> 3.3V
      GND  ----------> GND
      DATA ----------> GPIO4
Electrical Safety:

Water and electricity must be properly isolated. Use waterproof connectors, insulated wiring, low-voltage DC power, fuse protection, and a waterproof enclosure.

```
```

7. Complete System Flowchart

START
Initialize ESP32, Sensors and Wi-Fi
Read Water Flow Sensor
Read Leakage Sensor
Calculate Flow Rate and Total Water Consumption
Is Abnormal Flow or Leakage Detected?
Send Data to PHP API, n8n and ThingSpeak
AI Agent Analyzes Sensor Data
Calculate Leakage Probability
If Critical: Telegram Alert + Voice Notification
Store Data in Google Sheets and MySQL
Update IoT Dashboard
Repeat Continuously
```
```

8. Water Leakage Detection Logic

Continuous Flow Detection

```

IF flow_rate > minimum_flow
AND flow continues for a long duration
AND no expected water usage is detected

THEN

```
Possible Water Leakage

Sudden Water Flow Detection

```

Previous Flow = 0 L/min

Current Flow = 20 L/min

IF sudden_flow_change > threshold

THEN

```
Possible Pipe Burst

Physical Leakage Sensor Detection

```

IF leak_sensor_value > threshold

THEN

```
Immediate Water Leakage Alert
```
```

9. Complete ESP32 Source Code


```

#include 
#include 
#include 
#include 

const char* WIFI_SSID =
"YOUR_WIFI_NAME";

const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";

const char* SERVER_URL =
"http://YOUR_SERVER_ADDRESS/water-leakage/api/receive_data.php";

const char* THINGSPEAK_API_KEY =
"YOUR_THINGSPEAK_WRITE_API_KEY";

const char* THINGSPEAK_URL =
"http://api.thingspeak.com/update";

#define FLOW_SENSOR_PIN 27
#define LEAK_SENSOR_PIN 34
#define TEMP_SENSOR_PIN 4
#define BUZZER_PIN 5
#define RED_LED_PIN 2
#define GREEN_LED_PIN 15

OneWire oneWire(TEMP_SENSOR_PIN);

DallasTemperature temperatureSensor(
&oneWire
);

volatile unsigned long pulseCount = 0;

float flowRate = 0.0;

float totalLiters = 0.0;

float temperature = 0.0;

unsigned long lastTime = 0;

unsigned long lastSendTime = 0;

const float FLOW_CALIBRATION = 7.5;

const float MIN_LEAK_FLOW = 0.5;

const unsigned long LEAK_TIME_LIMIT =
300000;

unsigned long continuousFlowStart = 0;

void IRAM_ATTR pulseCounter()
{
pulseCount++;
}

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

```
pinMode(
    FLOW_SENSOR_PIN,
    INPUT_PULLUP
);

pinMode(
    LEAK_SENSOR_PIN,
    INPUT
);

pinMode(
    BUZZER_PIN,
    OUTPUT
);

pinMode(
    RED_LED_PIN,
    OUTPUT
);

pinMode(
    GREEN_LED_PIN,
    OUTPUT
);

digitalWrite(
    BUZZER_PIN,
    LOW
);

digitalWrite(
    RED_LED_PIN,
    LOW
);

digitalWrite(
    GREEN_LED_PIN,
    HIGH
);

temperatureSensor.begin();

attachInterrupt(
    digitalPinToInterrupt(
        FLOW_SENSOR_PIN
    ),
    pulseCounter,
    RISING
);

WiFi.begin(
    WIFI_SSID,
    WIFI_PASSWORD
);

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

    Serial.print(".");
}

Serial.println();

Serial.println(
    "WiFi Connected"
);

Serial.println(
    WiFi.localIP()
);

lastTime = millis();
```

}

void loop()
{
readFlowData();

```
readTemperature();

detectLeakage();

if (
    millis()
    -
    lastSendTime
    >=
    30000
)
{
    sendDataToPHP();

    sendDataToThingSpeak();

    lastSendTime =
    millis();
}

delay(1000);
```

}

void readFlowData()
{
unsigned long currentTime =
millis();

```
if (
    currentTime
    -
    lastTime
    >=
    1000
)
{
    noInterrupts();

    unsigned long pulses =
    pulseCount;

    pulseCount = 0;

    interrupts();

    flowRate =
    pulses
    /
    FLOW_CALIBRATION;

    float litersPerSecond =
    flowRate
    /
    60.0;

    totalLiters +=
    litersPerSecond;

    Serial.print(
        "Flow Rate: "
    );

    Serial.print(
        flowRate
    );

    Serial.println(
        " L/min"
    );

    lastTime =
    currentTime;
}
```

}

void readTemperature()
{
temperatureSensor.requestTemperatures();

```
temperature =
temperatureSensor.getTempCByIndex(
    0
);
```

}

void detectLeakage()
{
int leakValue =
analogRead(
LEAK_SENSOR_PIN
);

```
bool physicalLeakDetected =
leakValue > 1500;

bool continuousFlow =
flowRate > MIN_LEAK_FLOW;

if (
    continuousFlow
)
{
    if (
        continuousFlowStart
        ==
        0
    )
    {
        continuousFlowStart =
        millis();
    }
}

else
{
    continuousFlowStart =
    0;
}

bool longContinuousFlow =
continuousFlowStart > 0
&&
millis()
-
continuousFlowStart
>
LEAK_TIME_LIMIT;

if (
    physicalLeakDetected
    ||
    longContinuousFlow
)
{
    digitalWrite(
        RED_LED_PIN,
        HIGH
    );

    digitalWrite(
        GREEN_LED_PIN,
        LOW
    );

    digitalWrite(
        BUZZER_PIN,
        HIGH
    );

    Serial.println(
        "POSSIBLE WATER LEAKAGE"
    );
}

else
{
    digitalWrite(
        RED_LED_PIN,
        LOW
    );

    digitalWrite(
        GREEN_LED_PIN,
        HIGH
    );

    digitalWrite(
        BUZZER_PIN,
        LOW
    );
}
```

}

void sendDataToPHP()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}

```
HTTPClient http;

http.begin(
    SERVER_URL
);

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

String jsonData =
"{";

jsonData +=
"\"device_id\":\"ESP32_WATER_001\",";

jsonData +=
"\"flow_rate\":"
+
String(flowRate)
+
",";

jsonData +=
"\"total_liters\":"
+
String(totalLiters)
+
",";

jsonData +=
"\"temperature\":"
+
String(temperature)
+
",";

jsonData +=
"\"leak_sensor\":"
+
String(
    analogRead(
        LEAK_SENSOR_PIN
    )
);

jsonData +=
"}";

int httpCode =
http.POST(
    jsonData
);

Serial.println(
    httpCode
);

http.end();
```

}

void sendDataToThingSpeak()
{
if (
WiFi.status()
!=
WL_CONNECTED
)
{
return;
}

```
HTTPClient http;

String url =
String(
    THINGSPEAK_URL
)
+
"?api_key="
+
THINGSPEAK_API_KEY
+
"&field1="
+
String(
    flowRate
)
+
"&field2="
+
String(
    totalLiters
)
+
"&field3="
+
String(
    temperature
)
+
"&field4="
+
String(
    analogRead(
        LEAK_SENSOR_PIN
    )
);

http.begin(
    url
);

int httpCode =
http.GET();

Serial.println(
    httpCode
);

http.end();
```

} 
```

10. PHP and MySQL Backend Architecture

```

water-leakage/

├── index.php

├── dashboard.php

├── config.php

├── api/

│   ├── receive_data.php

│   ├── get_latest_data.php

│   └── get_history.php

├── database/

│   └── water_leakage.sql

├── css/

│   └── style.css

└── js/

```
└── dashboard.js
```
```

11. MySQL Database


```

CREATE DATABASE water_leakage;

USE water_leakage;

CREATE TABLE sensor_data (

```
id INT AUTO_INCREMENT PRIMARY KEY,

device_id VARCHAR(100),

flow_rate FLOAT,

total_liters FLOAT,

temperature FLOAT,

leak_sensor INT,

leakage_status VARCHAR(50),

ai_probability FLOAT,

created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
```

); 
```

12. PHP Configuration File


```

connect_error
)
{
die(
"Database connection failed"
);
}

?> 
```

13. PHP ESP32 API


```


"error",

```
        "message" =>
        "Invalid JSON data"
    ]
);

exit;
```

}

$device_id =
$data["device_id"]
??
"UNKNOWN";

$flow_rate =
floatval(
$data["flow_rate"]
??
0
);

$total_liters =
floatval(
$data["total_liters"]
??
0
);

$temperature =
floatval(
$data["temperature"]
??
0
);

$leak_sensor =
intval(
$data["leak_sensor"]
??
0
);

$leakage_status =
"NORMAL";

if (
$flow_rate > 0.5
&&
$leak_sensor > 1500
)
{
$leakage_status =
"POSSIBLE_LEAKAGE";
}

$sql =
"
INSERT INTO sensor_data
(
device_id,
flow_rate,
total_liters,
temperature,
leak_sensor,
leakage_status
)
VALUES (?, ?, ?, ?, ?, ?)
";

$stmt =
$conn->prepare(
$sql
);

$stmt->bind_param(
"sdddis",

```
$device_id,

$flow_rate,

$total_liters,

$temperature,

$leak_sensor,

$leakage_status
```

);

$stmt->execute();

echo json_encode(
[
"status" =>
"success",

```
    "leakage_status" =>
    $leakage_status
]
```

);

?> 
```

14. n8n Automation Workflow

```

ESP32
|
v
Webhook
|
v
Receive JSON
|
v
Calculate Leakage Risk
|
v
AI Agent
|
v
Leakage Probability
|
v
IF Risk >= 60%
|
+---------------------+
|                     |
v                     v
Telegram Alert      Google Sheets
|                     |
v                     v
Voice Alert          Data Logging
|
v
Maintenance Action 
```

n8n Workflow JSON


```

{
"name":
"AI Water Leakage Detection",

```
"nodes":
[

    {
        "name":
        "ESP32 Webhook",

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

        "parameters":
        {
            "path":
            "water-leakage",

            "httpMethod":
            "POST"
        }
    },

    {
        "name":
        "Calculate Leakage Risk",

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

        "parameters":
        {
            "jsCode":
            "const data = $json.body || $json;

            let risk = 0;

            if (data.flow_rate > 0.5)
            {
                risk += 25;
            }

            if (data.leak_sensor > 1500)
            {
                risk += 50;
            }

            if (data.flow_rate > 5)
            {
                risk += 25;
            }

            return [{
                json: {
                    ...data,
                    leakage_probability: risk,
                    timestamp:
                    new Date().toISOString()
                }
            }];"
        }
    },

    {
        "name":
        "Leakage Detected?",

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

        "parameters":
        {
            "condition":
            "leakage_probability >= 60"
        }
    },

    {
        "name":
        "Telegram Alert",

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

        "parameters":
        {
            "text":
            "WATER LEAKAGE ALERT"
        }
    },

    {
        "name":
        "Google Sheets Log",

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

        "parameters":
        {
            "operation":
            "append"
        }
    }

]
```

} 
```

15. Telegram Bot Setup

  1. Open Telegram.
  2. Search for BotFather.
  3. Send: /start
  4. Send: /newbot
  5. Enter the bot name.
  6. Enter a unique bot username.
  7. Copy the generated bot token.
  8. Configure the token inside n8n.
Example Telegram Alert
```

WATER LEAKAGE DETECTED

Device:
ESP32_WATER_001

Flow Rate:
5.8 L/min

Leakage Probability:
94%

Action:
Inspect the water pipeline immediately. 
```
```
```

16. Voice Notification Automation

```

Leakage Detected
|
v
AI Creates Alert Text
|
v
Text-to-Speech Service
|
v
Generate Audio File
|
v
Telegram Send Voice Message 
```

Example voice message:

Warning. Possible water leakage has been detected. The current flow rate is 5.8 liters per minute. Please inspect the water pipeline immediately.
```
```

17. Google Sheets Integration

Create a Google Sheet with the following columns:

Column Description
Timestamp Event time
Device ID ESP32 device identity
Flow Rate Current water flow
Total Liters Total water consumption
Temperature Pipe temperature
Leak Sensor Leakage sensor value
AI Probability Leakage probability
AI Decision Normal or Leakage
```
```

18. ThingSpeak Cloud Dashboard Setup

Field Data
Field 1 Flow Rate
Field 2 Total Water Consumption
Field 3 Temperature
Field 4 Leakage Sensor
Field 5 AI Leakage Probability
Field 6 Daily Consumption Prediction
```
```

19. AI Leakage Detection Logic

```

Current Flow Rate
+
Historical Average Flow
+
Flow Duration
+
Time of Day
+
Leak Sensor Value
+
Daily Water Consumption
|
v
AI Agent Analysis
|
v
Leakage Probability
|
+----------------------+
|                      |
v                      v
Normal Usage            Possible Leakage
|                      |
v                      v
Data Logging             Telegram Alert
|
v
Voice Alert 
```

Example AI Decision

Flow Rate: 5.8 L/min

Time: 02:30 AM

Historical Average: 0.2 L/min

Leakage Probability: 94%

Recommendation: Immediately inspect the main water pipeline.

```
```

20. AI Water Consumption Prediction

```

Average Daily Consumption

=

## Total Water Used

Number of Days 
```
```

IF current_usage

>

historical_average
*
1.5

THEN

HIGH CONSUMPTION ALERT 
```

Example

```

Historical Average = 800 Liters

Threshold = 800 x 1.5

Threshold = 1200 Liters

Current Consumption = 1500 Liters

Result:

ABNORMAL WATER CONSUMPTION 
```

21. Complete End-to-End Data Flow

```

Water Flow
|
v
Flow Sensor
|
v
ESP32
|
+--------------------> Local Buzzer
|
+--------------------> PHP API
|                            |
|                            v
|                      MySQL Database
|                            |
|                            v
|                      IoT Web Dashboard
|
+--------------------> ThingSpeak
|
+--------------------> n8n Webhook
|
v
AI Agent
|
v
Leakage Probability
|
+-------------+-------------+
|             |             |
v             v             v
Telegram      Voice Alert    Google Sheets
Message       Audio Alert    Data Logging 
```

22. Step-by-Step Installation

Step 1: Hardware Installation

Connect the water flow sensor, leakage sensor, temperature sensor, buzzer, LEDs, and optional ultrasonic sensor to the ESP32.

Step 2: ESP32 Programming

Install Arduino IDE and ESP32 board support. Install required libraries. Configure Wi-Fi and API credentials. Upload the ESP32 program.

Step 3: Web Server Setup

Install Apache, PHP, and MySQL. Copy the project files to the server. Create the water_leakage database.

Step 4: API Testing

Send test JSON data to the PHP API and confirm that the data is inserted into the MySQL database.

Step 5: n8n Configuration

Configure the webhook, AI Agent, IF condition, Telegram node, voice notification node, and Google Sheets node.

Step 6: ThingSpeak Configuration

Create a ThingSpeak channel and configure the required fields.

Step 7: Complete Testing

Test normal flow, small leakage, continuous flow, and pipe burst conditions.

```
```

23. Testing Procedure

Test Input Expected Result
Normal Condition Flow = 0 Normal Status
Small Leakage Low Continuous Flow Warning Alert
Major Leakage High Flow Telegram + Voice Alert
Pipe Burst Sudden Very High Flow Critical Alert
```
```

24. Security Recommendations

Never expose Wi-Fi passwords, Telegram bot tokens, ThingSpeak API keys, database passwords, or AI API keys inside public source code.

Use environment variables, server-side configuration, HTTPS, authentication, and encrypted credentials.

```
```

25. Future Enhancements

Automatic Water Valve Control

Add a relay and solenoid valve. Automatically close the main water supply when critical leakage is detected.

Multiple ESP32 Nodes

Install sensors in kitchens, bathrooms, gardens, tanks, and industrial pipelines.

Predictive Maintenance

Predict pipe degradation, repeated leakage, increasing water usage, and possible future failures.

Mobile Application

Create Android, iOS, Flutter, or React Native applications.

AI Voice Assistant

Ask the AI system: "Is there any water leakage?"

```
```

26. Final Project Summary

This project combines ESP32, IoT sensors, Wi-Fi, PHP, MySQL, n8n automation, AI Agent technology, Telegram notifications, voice alerts, Google Sheets, and ThingSpeak cloud monitoring.

The result is an intelligent Agentic IoT water management platform capable of monitoring water flow, detecting leakage, analyzing abnormal usage, predicting consumption, and automatically notifying users.

```
```

27. Recommended Final Project Title

AI-Powered Agentic IoT-Based Smart Water Leakage Detection and Predictive Water Consumption Monitoring System Using ESP32, n8n Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak Cloud Dashboard

```
```

AI-Based Smart Water Leakage Detection and Alert System

ESP32 | AI Agent | Agentic IoT | n8n | Telegram Voice Alerts | Google Sheets | ThingSpeak

Smart Water Monitoring System 🚀

```

AI-Based Smart Voice Assistant for Elderly People

AI-Based Smart Voice Assistant for Elderly People

AI-Based Smart Voice Assistant for Elderly People

ESP32 + IoT + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak Cloud Dashboard + PHP IoT Webpage


AI-Powered ESP32 Agentic IoT n8n Automation Telegram Alerts Google Sheets ThingSpeak

1. Complete Project Overview

The AI-Based Smart Voice Assistant for Elderly People is an intelligent IoT healthcare and safety system designed to assist senior citizens in their daily lives.

The system uses an ESP32 microcontroller connected to environmental sensors, motion sensors, emergency buttons, optional health sensors, microphone modules, speakers, and display modules.

Sensor information is transmitted through Wi-Fi to an IoT server and n8n automation platform. The n8n workflow uses an AI Agent to analyze the elderly person's condition and automatically generate notifications.

Main Objective

  • Monitor elderly people remotely.
  • Detect emergency situations.
  • Provide voice-based assistance.
  • Send automatic Telegram notifications.
  • Generate Telegram voice alerts.
  • Store data in Google Sheets.
  • Display data using ThingSpeak.
  • Predict abnormal power consumption.
  • Detect unusual inactivity.
  • Provide AI-based risk analysis.

2. Major System Features

Emergency SOS

The elderly person can press an emergency button. The ESP32 immediately sends an emergency event to the n8n AI automation system.

Voice Assistant

The system can process voice commands such as medication reminders, emergency assistance, temperature requests, and appliance control.

AI Monitoring

The AI Agent analyzes sensor data and classifies the situation as normal, low risk, medium risk, high risk, or critical.

Telegram Voice Alerts

Caregivers can receive text messages and voice notifications through Telegram.

Cloud Dashboard

Sensor values can be monitored using a PHP IoT webpage and ThingSpeak cloud dashboard.

Data Logging

All important events can be stored in Google Sheets and MySQL.

3. Components List

Hardware Components

Component Purpose
ESP32 DevKit Main IoT controller
DHT22 / DHT11 Temperature and humidity measurement
PIR Sensor Motion and activity detection
Push Button Emergency SOS button
OLED Display Display sensor information
Buzzer Local emergency alarm
Speaker Voice notifications
MAX30102 Optional pulse and heart-rate monitoring
LDR Light monitoring
Relay Module Appliance control
Microphone Module Voice input

4. Overall System Architecture

┌─────────────────────────────┐ │ ELDERLY PERSON │ │ │ │ Voice Commands │ │ Emergency Button │ │ Medication Reminder │ └──────────────┬──────────────┘ │ ▼ ┌─────────────────────────────┐ │ ESP32 │ │ │ │ Temperature Sensor │ │ Humidity Sensor │ │ PIR Motion Sensor │ │ Emergency Button │ │ Buzzer / Speaker │ │ OLED Display │ │ Optional Health Sensors │ └──────────────┬──────────────┘ │ Wi-Fi ▼ ┌─────────────────────────────┐ │ IoT WEB DASHBOARD │ │ PHP + MySQL │ └──────────────┬──────────────┘ │ ▼ ┌─────────────────────────────┐ │ n8n AUTOMATION │ │ │ │ Webhook │ │ AI Agent │ │ Decision Logic │ │ Telegram Bot │ │ Google Sheets │ │ Voice Notification │ └──────┬──────────┬───────────┘ │ │ ▼ ▼ ┌────────────┐ ┌──────────────┐ │ TELEGRAM │ │ GOOGLE SHEETS│ │ VOICE ALERT │ │ DATA LOGGING │ └────────────┘ └──────────────┘ │ ▼ ┌─────────────────────┐ │ THINGSPEAK CLOUD │ │ Sensor Graphs │ │ Historical Data │ │ Analytics │ └─────────────────────┘

5. Circuit Schematic Diagram

┌─────────────────┐ │ ESP32 │ │ │ DHT22 DATA ─────▶│ GPIO 4 │ │ │ PIR OUT ────────▶│ GPIO 27 │ │ │ SOS BUTTON ─────▶│ GPIO 26 │ │ │ BUZZER ──────────│ GPIO 25 │ │ │ RELAY ───────────│ GPIO 33 │ │ │ OLED SDA ────────│ GPIO 21 │ OLED SCL ────────│ GPIO 22 │ │ │ Wi-Fi ───────────│ Wi-Fi │ └────────┬────────┘ │ ▼ INTERNET │ ┌─────────────────┼─────────────────┐ │ │ │ ▼ ▼ ▼ n8n AI Agent ThingSpeak PHP Webpage │ │ │ ▼ ▼ ▼ Telegram Cloud Graph MySQL Voice Alert Dashboard Database

DHT22 Connections


DHT22 VCC  → ESP32 3.3V

DHT22 GND  → ESP32 GND

DHT22 DATA → ESP32 GPIO 4
    

PIR Connections


PIR VCC → ESP32 5V

PIR GND → ESP32 GND

PIR OUT → ESP32 GPIO 27
    

Emergency Button


Button Pin 1 → ESP32 GPIO 26

Button Pin 2 → ESP32 GND

ESP32 Configuration:

INPUT_PULLUP
    

OLED Connections


OLED VCC → ESP32 3.3V

OLED GND → ESP32 GND

OLED SDA → ESP32 GPIO 21

OLED SCL → ESP32 GPIO 22
    

6. Complete System Flowchart

┌─────────────┐ │ START │ └──────┬──────┘ ▼ ┌──────────────────┐ │ ESP32 Connect WiFi│ └────────┬─────────┘ ▼ ┌─────────────────────────┐ │ Read All Sensors │ │ Temperature │ │ Humidity │ │ Motion │ │ SOS Button │ └─────────────┬───────────┘ ▼ ┌─────────────────────┐ │ SOS Button Pressed? │ └───────┬─────────┬───┘ │ YES │ NO ▼ ▼ ┌──────────────┐ ┌────────────────┐ │ Emergency │ │ Check Sensors │ │ Event │ └───────┬────────┘ └──────┬───────┘ ▼ │ ┌───────────────┐ │ │ Abnormal Data?│ │ └──────┬────────┘ │ │ └──────────┬───────┘ ▼ ┌─────────────────────┐ │ Send Data to n8n │ └──────────┬──────────┘ ▼ ┌─────────────────────┐ │ AI Agent Analysis │ └──────────┬──────────┘ ▼ ┌────────────────────────┐ │ Determine Alert Level │ └────────────┬───────────┘ ▼ ┌────────────────────────────────────┐ │ Telegram + Voice + Google Sheets │ └─────────────────┬──────────────────┘ ▼ ┌─────────────────────┐ │ Update Dashboard │ └──────────┬──────────┘ ▼ LOOP

7. ESP32 Source Code

The ESP32 program connects to Wi-Fi, reads sensors, activates the emergency buzzer, sends data to n8n, sends values to ThingSpeak, and displays information on the OLED display.


#include <WiFi.h>

#include <HTTPClient.h>

#include <DHT.h>

#include <Wire.h>

#include <Adafruit_GFX.h>

#include <Adafruit_SSD1306.h>


#define DHTPIN 4

#define DHTTYPE DHT22


#define PIR_PIN 27

#define SOS_BUTTON 26

#define BUZZER_PIN 25

#define RELAY_PIN 33


#define SCREEN_WIDTH 128

#define SCREEN_HEIGHT 64


DHT dht(

    DHTPIN,

    DHTTYPE

);


Adafruit_SSD1306 display(

    SCREEN_WIDTH,

    SCREEN_HEIGHT,

    &Wire,

    -1

);


const char* ssid =

    "YOUR_WIFI_NAME";


const char* password =

    "YOUR_WIFI_PASSWORD";


String n8nWebhook =

    "https://YOUR_N8N_DOMAIN/webhook/elderly-monitoring";


String thingSpeakURL =

    "https://api.thingspeak.com/update";


String thingSpeakAPIKey =

    "YOUR_THINGSPEAK_API_KEY";


unsigned long lastSendTime = 0;


const unsigned long sendInterval = 30000;


void setup() {

    Serial.begin(115200);

    pinMode(

        PIR_PIN,

        INPUT

    );

    pinMode(

        SOS_BUTTON,

        INPUT_PULLUP

    );

    pinMode(

        BUZZER_PIN,

        OUTPUT

    );

    pinMode(

        RELAY_PIN,

        OUTPUT

    );

    digitalWrite(

        BUZZER_PIN,

        LOW

    );

    digitalWrite(

        RELAY_PIN,

        LOW

    );

    dht.begin();

    Wire.begin(

        21,

        22

    );

    if (

        !display.begin(

            SSD1306_SWITCHCAPVCC,

            0x3C

        )

    ) {

        Serial.println(

            "OLED initialization failed"

        );

        while (true);

    }

    display.clearDisplay();

    display.setTextSize(1);

    display.setTextColor(

        SSD1306_WHITE

    );

    display.setCursor(

        0,

        0

    );

    display.println(

        "Elderly AI Assistant"

    );

    display.display();

    WiFi.begin(

        ssid,

        password

    );

    while (

        WiFi.status() != WL_CONNECTED

    ) {

        delay(500);

        Serial.print(".");

    }

    Serial.println();

    Serial.println(

        "WiFi Connected"

    );

    Serial.println(

        WiFi.localIP()

    );

}


void loop() {

    float temperature =

        dht.readTemperature();

    float humidity =

        dht.readHumidity();

    int motion =

        digitalRead(

            PIR_PIN

        );

    int sos =

        digitalRead(

            SOS_BUTTON

        );

    bool emergency =

        (

            sos == LOW

        );

    if (

        isnan(

            temperature

        ) ||

        isnan(

            humidity

        )

    ) {

        Serial.println(

            "Sensor reading failed"

        );

        return;

    }

    updateDisplay(

        temperature,

        humidity,

        motion,

        emergency

    );

    if (

        emergency

    ) {

        digitalWrite(

            BUZZER_PIN,

            HIGH

        );

        sendEmergencyAlert(

            temperature,

            humidity,

            motion

        );

        delay(5000);

        digitalWrite(

            BUZZER_PIN,

            LOW

        );

    }

    if (

        millis()

        -

        lastSendTime

        >

        sendInterval

    ) {

        sendSensorData(

            temperature,

            humidity,

            motion,

            emergency

        );

        sendThingSpeakData(

            temperature,

            humidity,

            motion

        );

        lastSendTime =

            millis();

    }

    delay(1000);

}
    

8. n8n Automation Workflow

┌───────────────┐ │ Webhook Node │ └───────┬───────┘ ▼ ┌────────────────┐ │ Parse JSON Data│ └───────┬────────┘ ▼ ┌────────────────┐ │ AI Agent │ └───────┬────────┘ ▼ ┌──────────────────────┐ │ Emergency Decision │ └───────┬──────────────┘ │ ┌────┴─────┐ ▼ ▼ YES NO │ │ ▼ ▼ Telegram Normal Log Alert Google Sheets │ │ ▼ ▼ Voice ThingSpeak Alert Dashboard

n8n Workflow Nodes

  1. Webhook Node
  2. JSON Processing Node
  3. AI Agent Node
  4. Risk Decision Node
  5. Telegram Notification Node
  6. Voice Generation Node
  7. Google Sheets Node
  8. ThingSpeak HTTP Request Node

Example n8n Workflow JSON


{
    "nodes": [

        {
            "name":
            "ESP32 Webhook",

            "type":
            "Webhook",

            "method":
            "POST",

            "path":
            "elderly-monitoring"
        },

        {
            "name":
            "AI Analysis",

            "type":
            "AI Agent"
        },

        {
            "name":
            "Risk Decision",

            "type":
            "IF"
        },

        {
            "name":
            "Telegram Alert",

            "type":
            "Telegram"
        },

        {
            "name":
            "Google Sheets Log",

            "type":
            "Google Sheets"
        },

        {
            "name":
            "Voice Notification",

            "type":
            "Text to Speech"
        }

    ]
}
    

9. Telegram Bot Setup

Step 1: Open Telegram

Search for BotFather.

Step 2: Create a Bot


/newbot
    

Step 3: Copy the Bot Token


123456789:ABCxxxxxxxxxxxxxxxx
    

Example Telegram Alert


🚨 CRITICAL ELDERLY ALERT 🚨

Device: ELDERLY_001

Emergency Status: ACTIVE

Temperature: 41°C

Humidity: 75%

Motion: NOT DETECTED

Risk Level: CRITICAL

AI Recommendation:

Immediately contact the elderly person's caregiver.
    

10. Google Sheets Integration

Google Sheets is used for historical data logging and monitoring.

Column Description
Timestamp Event date and time
Device ID ESP32 device identifier
Temperature Temperature value
Humidity Humidity value
Motion Motion detection result
Emergency Emergency status
Risk Level AI classification
AI Recommendation AI-generated response

11. ThingSpeak Cloud Dashboard

ThingSpeak can be used to visualize sensor information using real-time graphs.

Field Data
Field 1 Temperature
Field 2 Humidity
Field 3 Motion
Field 4 Emergency Status
Field 5 Power Consumption
Field 6 AI Prediction

12. AI Power Consumption Prediction

The AI system can analyze historical power consumption data from the ESP32 and identify abnormal trends.


IF power consumption increases continuously

AND sensor values remain normal

THEN

    classify as:

    "Possible power inefficiency"


ELSE IF power increases suddenly

THEN

    classify as:

    "Possible hardware fault"


ELSE

    classify as:

    "Normal power consumption"
    

Example

Time Power
08:00 2.1 W
09:00 2.4 W
10:00 2.6 W
11:00 2.9 W
12:00 3.3 W

13. Voice Notification Automation

ESP32 Emergency Event ↓ n8n Webhook ↓ AI Agent ↓ Critical Condition ↓ Generate Text Message ↓ Text-to-Speech ↓ Audio File ↓ Telegram Voice Message

"Emergency alert.

The elderly person has activated
the SOS button.

Please provide immediate assistance."
    

14. MySQL Database Design


CREATE DATABASE elderly_ai_system;


CREATE TABLE sensor_data (

    id INT AUTO_INCREMENT PRIMARY KEY,

    device_id VARCHAR(50),

    temperature FLOAT,

    humidity FLOAT,

    motion INT,

    emergency BOOLEAN,

    risk_level VARCHAR(30),

    ai_message TEXT,

    power_consumption FLOAT,

    created_at

    TIMESTAMP

    DEFAULT CURRENT_TIMESTAMP

);
    

15. PHP IoT Web Dashboard Design

Temperature

31.2 °C

Humidity

65 %

Motion

Detected

Emergency

Normal

Risk Level

LOW

AI Recommendation

Continue Monitoring

16. AI Alert Levels

Level Condition Action
NORMAL Normal sensor values Store data
LOW RISK Slightly unusual activity Continue monitoring
MEDIUM RISK Long inactivity or high temperature Telegram notification
HIGH RISK Dangerous environment Telegram plus voice alert
CRITICAL SOS button activated Immediate emergency alert

17. Elderly Inactivity Detection

No Motion Detected ↓ AI Checks Duration ↓ Unusual Inactivity? ↓ YES ↓ Medium-Risk Notification ↓ Caregiver Alert

The system can detect unusual periods of inactivity. For example, if no movement is detected for several hours, the AI Agent can notify the caregiver.

18. Project Folder Structure


elderly-ai-assistant/

│

├── esp32/

│   └── elderly_ai_assistant.ino

│

├── php/

│   ├── index.php

│   ├── dashboard.php

│   ├── api/

│   │   ├── sensor_data.php

│   │   ├── get_latest_data.php

│   │   └── emergency.php

│   │

│   ├── config/

│   │   └── database.php

│   │

│   └── assets/

│       ├── css/

│       └── js/

│

├── database/

│   └── elderly_ai_system.sql

│

├── n8n/

│   └── elderly_ai_workflow.json

│

└── documentation/

    └── project_report.html
    

19. Step-by-Step Installation Procedure

  1. Assemble the ESP32 and sensors.
  2. Install the required Arduino libraries.
  3. Configure the Wi-Fi credentials.
  4. Create the ThingSpeak channel.
  5. Create the Telegram bot.
  6. Configure the n8n Webhook.
  7. Configure the AI Agent.
  8. Create the Google Sheet.
  9. Configure Telegram credentials.
  10. Upload the ESP32 source code.
  11. Test the sensors.
  12. Test the emergency button.
  13. Verify Telegram notifications.
  14. Verify Google Sheets logging.
  15. Verify ThingSpeak graphs.

20. Testing Table

Test Expected Result
Power ON ESP32 starts
Wi-Fi Available ESP32 connects
DHT Sensor Temperature displayed
PIR Movement Motion detected
SOS Pressed Emergency alert generated
High Temperature Risk classification generated
Telegram Notification received
Google Sheets New row created
ThingSpeak Graph updated

21. Future Enhancements

  • AI-based fall detection using ESP32-CAM.
  • GPS location tracking.
  • Automatic emergency calling.
  • Smart medication dispenser.
  • Face recognition.
  • Advanced health anomaly detection.
  • Machine learning-based activity prediction.
  • Solar-powered operation.
  • Battery monitoring.
  • Multi-home caregiver management.

22. Deployment Guide

Small Home Deployment

ESP32 ↓ Home Wi-Fi ↓ n8n Cloud ↓ AI Agent ↓ Telegram Caregiver Alert

Multi-Home Deployment

ESP32 Device 1 ESP32 Device 2 ESP32 Device 3 ↓ Central n8n Server ↓ AI Agent ↓ Multiple Caregivers

Each ESP32 device should have a unique device ID.


ELDERLY_001

ELDERLY_002

ELDERLY_003
    

23. Complete Project Workflow

┌─────────────────────┐ │ Elderly Person │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ Voice / SOS / Motion│ │ Environmental Data │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ ESP32 │ │ Sensor Processing │ └──────────┬──────────┘ │ Wi-Fi ▼ ┌─────────────────────┐ │ PHP IoT Server │ │ MySQL Database │ └──────────┬──────────┘ │ ▼ ┌─────────────────────┐ │ n8n Webhook │ └──────────┬──────────┘ ▼ ┌─────────────────────┐ │ AI Agent │ │ Risk Analysis │ │ Decision Making │ └──────────┬──────────┘ │ ┌─────┴─────┐ ▼ ▼ NORMAL EMERGENCY │ │ ▼ ▼ Google Telegram Sheets Alert │ │ ▼ ▼ ThingSpeak Voice Alert Dashboard │ ▼ Caregiver
Final Project Result:

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

This project creates a complete intelligent Agentic IoT elderly-care ecosystem capable of monitoring sensor conditions, detecting emergencies, analyzing data using AI, predicting abnormal behavior, sending Telegram and voice alerts, and storing historical information.

24. Important Safety Note

This project is an educational and IoT monitoring system. It should not be treated as a certified medical device. Emergency alerts should always be verified by a caregiver or qualified healthcare professional. When using relays with AC mains appliances, use proper electrical isolation and qualified supervision.

AI-Based Smart Voice Assistant for Elderly People

ESP32 | AI Agent | n8n | Telegram | Google Sheets | ThingSpeak | IoT Dashboard

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

```