Saturday, 25 July 2026

Smart Automatic Street Light System Using Microcontroller

Smart Automatic Street Light System Using Microcontroller

1. Project Title

Microcontroller-Based Smart Automatic Street Light Control System Using LDR and PIR Sensor


2. Project Aim

The aim of this project is to design and develop an automatic street light system that controls street lights intelligently according to ambient light conditions and human/vehicle movement.

The system automatically:

  • Turns the street light ON at night.
  • Turns the street light OFF during daytime.
  • Detects movement using a PIR sensor.
  • Operates the light at full brightness when movement is detected.
  • Reduces brightness or turns the light OFF when no movement is detected.
  • Helps to save electrical energy.

3. Project Abstract

The Smart Automatic Street Light System is a microcontroller-based energy-saving system designed to control street lights automatically without manual operation. The system uses an LDR (Light Dependent Resistor) to detect the intensity of surrounding light and a PIR motion sensor to detect the movement of people or vehicles.

During the daytime, the LDR detects sufficient sunlight and the microcontroller keeps the street light switched OFF. During the night, when the light intensity decreases, the microcontroller automatically activates the street light. When motion is detected by the PIR sensor, the street light can operate at full brightness. When no motion is detected for a specific period, the system can reduce the brightness or switch the light OFF.

An Arduino Uno microcontroller is used as the main control unit. The system improves energy efficiency, reduces electricity consumption, and provides automatic and intelligent street lighting.


4. Block Diagram

                 ┌────────────────────┐
                 │   Sunlight / Dark  │
                 └─────────┬──────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ LDR Sensor   │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │              │
                    │              │
                    │   Arduino    │
                    │     Uno      │
                    │              │
                    └──────┬───────┘
                           ▲
                           │
                    ┌──────┴───────┐
                    │              │
                    │ PIR Sensor   │
                    │ Motion Detect│
                    │              │
                    └──────────────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ MOSFET /     │
                    │ Relay Driver │
                    └──────┬───────┘
                           │
                           ▼
                    ┌──────────────┐
                    │ LED Street   │
                    │ Light        │
                    └──────────────┘

             ┌──────────────────────┐
             │ 5V DC Power Supply   │
             └──────────┬───────────┘
                        │
                        ▼
                    Arduino Uno


5. Components Required

No. Component Quantity Purpose
1 Arduino Uno 1 Main microcontroller
2 LDR Sensor 1 Detects day and night
3 10 kΩ Resistor 1 LDR voltage divider
4 PIR Motion Sensor HC-SR501 1 Detects human/vehicle movement
5 LED Street Light / High-Power LED 1 Lighting output
6 Logic-Level MOSFET, e.g. IRLZ44N 1 Controls high-power LED
7 220 Ω Resistor 1 LED protection, if required
8 5 V Power Supply 1 Powers Arduino and sensors
9 External LED Power Supply 1 Powers high-power street LED
10 Breadboard 1 Prototype circuit
11 Jumper Wires As required Connections
12 Arduino USB Cable 1 Programming

Optional Components

  • LCD 16×2 display
  • OLED display
  • RTC module
  • ESP8266/ESP32 for IoT monitoring
  • Solar panel
  • Battery
  • Rain sensor
  • Ultrasonic sensor

6. System Working Principle

The project works in the following sequence:

Daytime

  1. The LDR receives strong sunlight.
  2. The LDR output value indicates bright conditions.
  3. Arduino detects daytime.
  4. The street light remains OFF.
Bright Light → LDR Detects Day → Arduino → Street Light OFF


Nighttime Without Movement

  1. The LDR detects darkness.
  2. Arduino turns the street light ON.
  3. If no motion is detected by the PIR sensor, the light can operate at reduced brightness.
Darkness → LDR Detects Night → Arduino
                         ↓
                  No Movement
                         ↓
                 Low Brightness


Nighttime With Movement

  1. The LDR detects darkness.
  2. The PIR sensor detects a person or vehicle.
  3. Arduino receives the motion signal.
  4. The street light operates at full brightness.
Darkness + Motion Detected
             ↓
         Arduino
             ↓
      Full Brightness


7. Schematic Diagram

Basic Connection Diagram

                    +5V
                     │
                     │
                 ┌───┴───┐
                 │  LDR  │
                 └───┬───┘
                     │
                     ├────────────── A0
                     │
                 ┌───┴───┐
                 │ 10kΩ  │
                 │Resistor│
                 └───┬───┘
                     │
                    GND


       PIR SENSOR HC-SR501

       VCC ─────────────── 5V
       GND ─────────────── GND
       OUT ─────────────── D2


       ARDUINO UNO

       D9 ──────────────── Gate
                              │
                              ▼
                         ┌────────┐
                         │ MOSFET │
                         └───┬────┘
                             │
                             │ Drain
                             ▼
                       LED STREET LIGHT
                             │
                             │
                            GND

       MOSFET Source ─────── GND


8. Arduino Pin Connection Table

Component Component Pin Arduino Pin
LDR Voltage Divider Output A0
LDR VCC 5V
LDR Resistor Other side GND
PIR Sensor VCC 5V
PIR Sensor GND GND
PIR Sensor OUT D2
MOSFET Gate Gate D9
MOSFET Source Source GND
LED Street Light Positive External +V
LED Street Light Negative MOSFET Drain

Important

For a high-power LED street light, do not power the LED directly from an Arduino GPIO pin. Use a suitable:

  • MOSFET driver
  • LED driver circuit
  • External power supply

9. Step-by-Step Construction

Step 1: Prepare the Arduino Uno

Connect the Arduino Uno to your computer using the USB cable.

The Arduino will be the main controller that receives:

  • LDR sensor input
  • PIR sensor input

and controls:

  • Street light output

Step 2: Connect the LDR Sensor

The LDR is used to detect light intensity.

Connection

5V ─── LDR ───┬─── A0
              │
             10kΩ
              │
             GND

The junction between the LDR and the 10 kΩ resistor is connected to:

Arduino A0

Function

  • Bright light → one range of analog values
  • Darkness → another range of analog values

The Arduino reads the value using:

analogRead(A0);


Step 3: Connect the PIR Sensor

The PIR sensor detects movement.

Connections

PIR VCC  → Arduino 5V
PIR GND  → Arduino GND
PIR OUT  → Arduino Digital Pin 2

The PIR output will be:

HIGH → Motion detected
LOW  → No motion


Step 4: Connect the MOSFET

The MOSFET works as an electronic switch.

Connections

Arduino D9 → MOSFET Gate
MOSFET Source → GND
MOSFET Drain → LED Negative
LED Positive → External Power Supply Positive

A common ground must be connected:

Arduino GND ─── External Power Supply GND


Step 5: Connect the Street Light

For a simple demonstration, you can use an LED.

For a real street light, use a suitable high-power LED module with an appropriate driver.

Basic Concept

External +V
    │
    ▼
LED Street Light
    │
    ▼
MOSFET Drain
    │
MOSFET Source
    │
   GND


10. Control Logic

The control algorithm is:

START
  │
  ▼
Read LDR Value
  │
  ▼
Is it Daytime?
 ┌───────────────┐
 │               │
YES             NO
 │               │
 ▼               ▼
Light OFF    Read PIR Sensor
                  │
                  ▼
          Is Motion Detected?
             ┌────────┴────────┐
             │                 │
            YES               NO
             │                 │
             ▼                 ▼
       Full Brightness    Low Brightness
             │                 │
             └────────┬────────┘
                      │
                      ▼
                  Repeat


11. Example Arduino Program

// Smart Automatic Street Light System
// Arduino Uno + LDR + PIR + MOSFET

const int LDR_PIN = A0;
const int PIR_PIN = 2;
const int LIGHT_PIN = 9;

int ldrValue;
int pirState;

int darknessThreshold = 500;

void setup() {
  pinMode(PIR_PIN, INPUT);
  pinMode(LIGHT_PIN, OUTPUT);

  Serial.begin(9600);

  analogWrite(LIGHT_PIN, 0);
}

void loop() {

  // Read LDR value
  ldrValue = analogRead(LDR_PIN);

  // Read PIR motion sensor
  pirState = digitalRead(PIR_PIN);

  Serial.print("LDR Value: ");
  Serial.print(ldrValue);

  Serial.print(" | PIR: ");
  Serial.println(pirState);

  // Night condition
  if (ldrValue < darknessThreshold) {

    // Motion detected
    if (pirState == HIGH) {
      analogWrite(LIGHT_PIN, 255);
      Serial.println("Night + Motion: Full Brightness");
    }

    // No motion
    else {
      analogWrite(LIGHT_PIN, 80);
      Serial.println("Night + No Motion: Low Brightness");
    }
  }

  // Day condition
  else {
    analogWrite(LIGHT_PIN, 0);
    Serial.println("Daytime: Light OFF");
  }

  delay(500);
}


12. How the Program Works

LDR Reading

ldrValue = analogRead(LDR_PIN);

This reads the light intensity from the LDR circuit.


PIR Reading

pirState = digitalRead(PIR_PIN);

This checks whether motion is detected.


Night Detection

if (ldrValue < darknessThreshold)

The Arduino checks whether the environment is dark.

The value:

darknessThreshold = 500;

may need to be adjusted according to your LDR circuit.


Full Brightness

analogWrite(LIGHT_PIN, 255);

This produces maximum PWM output.


Low Brightness

analogWrite(LIGHT_PIN, 80);

This reduces the brightness.


Light OFF

analogWrite(LIGHT_PIN, 0);

This switches the street light OFF.


13. Testing Procedure

Test 1: Daylight Test

  1. Place the LDR under bright light.
  2. Open the Serial Monitor.
  3. Check the LDR value.
  4. The street light should turn OFF.

Test 2: Darkness Test

  1. Cover the LDR with your hand.
  2. Check the LDR value.
  3. The system should detect night.
  4. The street light should turn ON at low brightness.

Test 3: Motion Test

  1. Keep the LDR covered.
  2. Move in front of the PIR sensor.
  3. The PIR output becomes HIGH.
  4. The street light should turn to full brightness.

14. Advantages

  • Automatic operation
  • Saves electrical energy
  • Reduces manual control
  • Uses low-cost components
  • Easy to expand
  • Improves street-light efficiency
  • Can be powered using solar energy
  • Suitable for smart-city applications

15. Applications

  • Roads and highways
  • Residential streets
  • College and school campuses
  • Parking areas
  • Industrial areas
  • Rural roads
  • Smart-city infrastructure
  • Solar street-light systems

16. Future Enhancements

The project can be upgraded with:

IoT Monitoring

Use ESP32 to monitor:

  • Light status
  • Power consumption
  • Fault conditions

Solar Power

Add:

Solar Panel → Charge Controller → Battery → LED Street Light

Fault Detection

The system can detect:

  • LED failure
  • Overcurrent
  • Low battery
  • Cable failure

Automatic Brightness Control

Use PWM to control the LED brightness based on:

  • Ambient light
  • Motion
  • Time of day

17. Final Project Summary

LDR SENSOR
     │
     ▼
Detect Day/Night
     │
     ▼
   ARDUINO UNO
     ▲
     │
PIR MOTION SENSOR
     │
     ▼
Detect Movement
     │
     ▼
MOSFET DRIVER
     │
     ▼
LED STREET LIGHT

Final System Operation

Daytime → Light OFF

Night + No Motion → Low Brightness

Night + Motion Detected → Full Brightness

This is a strong Microcontroller Systems course project because it demonstrates sensor interfacing, analog input, digital input, PWM output, transistor/MOSFET switching, and embedded control logic in one practical application.

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