Tuesday, 21 July 2026

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

```

Monday, 20 July 2026

AI-Based Smart Retail Inventory Monitoring System

Yes. Below is the same complete Smart Retail Inventory Monitoring project converted into a PHP-based project structure, with the web dashboard, APIs, database, AI logic, n8n integration, Telegram alerts, Google Sheets integration, ThingSpeak integration, and documentation pages. Important: ESP32 firmware must remain .ino/Arduino C++ code because ESP32 cannot execute PHP. PHP is used for the web server, APIs, database, AI logic, cloud integration, and dashboard. 1. Complete PHP Project Structure smart-retail-inventory/ │ ├── index.php ├── dashboard.php ├── products.php ├── alerts.php ├── predictions.php ├── settings.php │ ├── config/ │ ├── database.php │ ├── config.php │ └── api_keys.php │ ├── api/ │ ├── esp32_data.php │ ├── inventory.php │ ├── products.php │ ├── alerts.php │ ├── prediction.php │ ├── telegram.php │ ├── thingspeak.php │ └── google_sheets.php │ ├── ai/ │ ├── inventory_ai.php │ ├── consumption_prediction.php │ └── reorder_prediction.php │ ├── includes/ │ ├── header.php │ ├── footer.php │ ├── navbar.php │ └── functions.php │ ├── assets/ │ ├── css/ │ │ └── style.css │ └── js/ │ └── dashboard.js │ ├── database/ │ └── smart_retail.sql │ ├── n8n/ │ └── inventory_workflow.json │ ├── documentation/ │ ├── project_description.php │ ├── components.php │ ├── circuit.php │ ├── flowchart.php │ ├── installation.php │ └── future_enhancements.php │ └── esp32/ └── smart_retail_inventory.ino 2. config/database.php connect_error) { die( "Database connection failed: " . $conn->connect_error ); } $conn->set_charset("utf8mb4"); ?> 3. config/config.php 4. config/api_keys.php "YOUR_N8N_SECRET_KEY", "esp32" => "YOUR_ESP32_SECRET_KEY", "telegram" => "YOUR_TELEGRAM_BOT_TOKEN", "thingspeak" => "YOUR_THINGSPEAK_WRITE_API_KEY" ]; ?> 5. Database SQL File database/smart_retail.sql CREATE DATABASE IF NOT EXISTS smart_retail; USE smart_retail; CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100) NOT NULL UNIQUE, product_name VARCHAR(200) NOT NULL, rfid_uid VARCHAR(100), category VARCHAR(100), unit_weight FLOAT DEFAULT 0, minimum_stock INT DEFAULT 10, reorder_level INT DEFAULT 10, supplier_name VARCHAR(200), supplier_contact VARCHAR(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE inventory ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT DEFAULT 0, weight FLOAT DEFAULT 0, temperature FLOAT DEFAULT 0, humidity FLOAT DEFAULT 0, daily_consumption FLOAT DEFAULT 0, predicted_consumption FLOAT DEFAULT 0, days_remaining FLOAT DEFAULT 0, stock_status VARCHAR(50), risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (product_id) REFERENCES products(product_id) ); CREATE TABLE inventory_history ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT, weight FLOAT, temperature FLOAT, humidity FLOAT, recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE alerts ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), alert_type VARCHAR(100), message TEXT, severity VARCHAR(50), sent_to_telegram BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE predictions ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), average_daily_consumption FLOAT, predicted_consumption FLOAT, estimated_days_remaining FLOAT, recommended_reorder_quantity INT, risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); 6. includes/header.php <?= SITE_NAME ?> 7. includes/navbar.php 8. includes/footer.php

AI Smart Retail Inventory Monitoring System

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

9. includes/functions.php 10. Main Dashboard index.php query( "SELECT i.*, p.product_name, p.category FROM inventory i LEFT JOIN products p ON i.product_id = p.product_id ORDER BY i.id DESC" ); $total_products = $conn->query( "SELECT COUNT(*) AS total FROM products" )->fetch_assoc()["total"]; $low_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'LOW_STOCK'" )->fetch_assoc()["total"]; $out_of_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'OUT_OF_STOCK'" )->fetch_assoc()["total"]; ?> AI Smart Retail Dashboard

AI Smart Retail Inventory Dashboard

Total Products

Low Stock Products

Out of Stock

AI Agent

ONLINE

fetch_assoc() ) { ?>
Product ID Product Name Quantity Weight Temperature Humidity Daily Consumption Days Remaining Status Risk
11. ESP32 Data API api/esp32_data.php This PHP file receives data from ESP32. false, "message" => "Invalid JSON data" ]); exit; } $product_id = $data["product_id"] ?? ""; $quantity = intval( $data["quantity"] ?? 0 ); $weight = floatval( $data["weight"] ?? 0 ); $temperature = floatval( $data["temperature"] ?? 0 ); $humidity = floatval( $data["humidity"] ?? 0 ); $product_query = $conn->prepare( "SELECT minimum_stock FROM products WHERE product_id = ?" ); $product_query->bind_param( "s", $product_id ); $product_query->execute(); $product_result = $product_query->get_result(); if ( $product_result->num_rows == 0 ) { echo json_encode([ "success" => false, "message" => "Product not found" ]); exit; } $product = $product_result->fetch_assoc(); $minimum_stock = $product["minimum_stock"]; $status = calculateStockStatus( $quantity, $minimum_stock ); $risk = calculateRiskLevel( $quantity, $minimum_stock ); $insert = $conn->prepare( "INSERT INTO inventory ( product_id, quantity, weight, temperature, humidity, stock_status, risk_level ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $insert->bind_param( "isddsss", $product_id, $quantity, $weight, $temperature, $humidity, $status, $risk ); $insert->execute(); $history = $conn->prepare( "INSERT INTO inventory_history ( product_id, quantity, weight, temperature, humidity ) VALUES (?, ?, ?, ?, ?)" ); $history->bind_param( "isddd", $product_id, $quantity, $weight, $temperature, $humidity ); $history->execute(); echo json_encode([ "success" => true, "product_id" => $product_id, "quantity" => $quantity, "stock_status" => $status, "risk_level" => $risk ]); ?> 12. Product Registration products.php prepare( "INSERT INTO products ( product_id, product_name, rfid_uid, category, unit_weight, minimum_stock, supplier_name ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $stmt->bind_param( "ssssdis", $product_id, $product_name, $rfid_uid, $category, $unit_weight, $minimum_stock, $supplier_name ); $stmt->execute(); } ?> Product Management

Add Retail Product








13. AI Inventory Logic ai/inventory_ai.php prepare( "SELECT quantity, daily_consumption FROM inventory WHERE product_id = ? ORDER BY id DESC LIMIT 1" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $data = $result->fetch_assoc(); if (!$data) { echo json_encode([ "success" => false, "message" => "No inventory data" ]); exit; } $quantity = $data["quantity"]; $daily_consumption = $data["daily_consumption"]; $days_remaining = calculateDaysRemaining( $quantity, $daily_consumption ); if ($days_remaining <= 1) { $risk = "CRITICAL"; } elseif ($days_remaining <= 3) { $risk = "HIGH"; } elseif ($days_remaining <= 7) { $risk = "MEDIUM"; } else { $risk = "LOW"; } echo json_encode([ "product_id" => $product_id, "current_stock" => $quantity, "daily_consumption" => $daily_consumption, "estimated_days_remaining" => $days_remaining, "risk_level" => $risk ]); ?> 14. Consumption Prediction ai/consumption_prediction.php prepare( "SELECT quantity, recorded_at FROM inventory_history WHERE product_id = ? ORDER BY recorded_at ASC" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $records = []; while ( $row = $result->fetch_assoc() ) { $records[] = $row; } if ( count($records) < 2 ) { echo json_encode([ "success" => false, "message" => "Insufficient historical data" ]); exit; } $consumption_values = []; for ( $i = 1; $i < count($records); $i++ ) { $previous = $records[$i - 1]["quantity"]; $current = $records[$i]["quantity"]; $consumption = $previous - $current; if ($consumption > 0) { $consumption_values[] = $consumption; } } if ( count($consumption_values) == 0 ) { $average_consumption = 0; } else { $average_consumption = array_sum( $consumption_values ) / count( $consumption_values ); } echo json_encode([ "product_id" => $product_id, "average_daily_consumption" => round( $average_consumption, 2 ) ]); ?> 15. Reorder Prediction ai/reorder_prediction.php $current_stock, "daily_consumption" => $daily_consumption, "lead_time" => $lead_time, "safety_stock" => $safety_stock, "recommended_reorder_quantity" => $reorder_quantity ]); ?> 16. Telegram Alert PHP File api/telegram.php TELEGRAM_CHAT_ID, "text" => $message ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $data ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); return $response; } $product = $_POST["product"] ?? ""; $quantity = $_POST["quantity"] ?? ""; $status = $_POST["status"] ?? ""; $message = "🚨 SMART RETAIL INVENTORY ALERT 🚨\n\n" . "Product: " . $product . "\n\n" . "Current Stock: " . $quantity . "\n\n" . "Status: " . $status . "\n\n" . "Please check inventory."; $response = sendTelegramMessage( $message ); echo $response; ?> 17. Telegram Voice Notification api/telegram_voice.php TELEGRAM_CHAT_ID, "voice" => new CURLFile( $audio_file, "audio/mpeg", "inventory_alert.mp3" ) ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_fields ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 18. ThingSpeak PHP Integration api/thingspeak.php true, "response" => $response ]); ?> 19. Google Sheets Integration Through n8n PHP sends inventory data to n8n: api/google_sheets.php $_POST["product_id"], "quantity" => $_POST["quantity"], "weight" => $_POST["weight"], "temperature" => $_POST["temperature"], "humidity" => $_POST["humidity"], "stock_status" => $_POST["stock_status"] ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, N8N_WEBHOOK_URL ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ] ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 20. n8n Workflow JSON n8n/inventory_workflow.json { "name": "AI Smart Retail Inventory Automation", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "inventory" }, "name": "ESP32 PHP Webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 200, 300 ] }, { "parameters": { "jsCode": "const data = $json;\nconst quantity = Number(data.quantity || 0);\nconst minimumStock = 10;\nlet status = 'NORMAL';\nif (quantity <= 0) {\n status = 'OUT_OF_STOCK';\n} else if (quantity <= minimumStock) {\n status = 'LOW_STOCK';\n}\nreturn [{json: {...data, stock_status: status, alert_required: status !== 'NORMAL'}}];" }, "name": "AI Inventory Analysis", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 450, 300 ] }, { "parameters": { "conditions": { "boolean": [ { "value1": "={{$json.alert_required}}", "value2": true } ] } }, "name": "Low Stock Decision", "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 700, 300 ] }, { "parameters": { "chatId": "YOUR_TELEGRAM_CHAT_ID", "text": "🚨 INVENTORY ALERT 🚨\nProduct: {{$json.product_id}}\nQuantity: {{$json.quantity}}\nStatus: {{$json.stock_status}}" }, "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "typeVersion": 1, "position": [ 950, 200 ] }, { "parameters": { "operation": "append", "documentId": "YOUR_GOOGLE_SHEET_ID", "sheetName": "Inventory" }, "name": "Google Sheets", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4, "position": [ 950, 400 ] } ], "connections": { "ESP32 PHP Webhook": { "main": [ [ { "node": "AI Inventory Analysis", "type": "main", "index": 0 } ] ] }, "AI Inventory Analysis": { "main": [ [ { "node": "Low Stock Decision", "type": "main", "index": 0 } ] ] }, "Low Stock Decision": { "main": [ [ { "node": "Telegram Alert", "type": "main", "index": 0 } ], [ { "node": "Google Sheets", "type": "main", "index": 0 } ] ] } } } 21. PHP Flowchart Page documentation/flowchart.php

Smart Retail Inventory Flowchart

START
ESP32 Initializes
Connect Wi-Fi
Read RFID Product
Read Weight
Read Temperature
Read Humidity
Send JSON Data
PHP API / n8n Webhook
AI Inventory Analysis
Check Stock Level
LOW STOCK?
Telegram Voice Alert
Google Sheets Update
ThingSpeak Update
PHP Dashboard
22. PHP Project Description Page documentation/project_description.php

AI-Based Smart Retail Inventory Monitoring System

Project Description

This project is an AI-powered IoT inventory monitoring system designed to automatically monitor retail products using ESP32, RFID, load cells, environmental sensors, PHP, MySQL, n8n automation, Telegram notifications, Google Sheets and ThingSpeak.

The ESP32 collects product and inventory data and sends it through Wi-Fi to the PHP API or n8n webhook.

The AI Agent analyzes current stock, historical consumption, stock depletion rate and future inventory requirements.

When the inventory reaches a critical level, the system automatically sends Telegram text and voice notifications.

Inventory information is stored in MySQL and Google Sheets and visualized through a PHP dashboard and ThingSpeak cloud platform.

Main Technologies

  • ESP32
  • RFID
  • Load Cell
  • PHP
  • MySQL
  • n8n
  • AI Agent
  • Telegram
  • Google Sheets
  • ThingSpeak
23. PHP Components Page documentation/components.php

Hardware Components

Component Purpose
ESP32 Main IoT controller
RFID RC522 Product identification
Load Cell Stock weight measurement
HX711 Load cell amplifier
DHT22 Temperature and humidity
OLED Display Local data display
Buzzer Local alert
24. CSS File assets/css/style.css body { font-family: Arial; margin: 0; padding: 20px; background: #f4f4f4; } .navbar { background: #222; padding: 20px; margin-bottom: 30px; } .navbar a { color: white; margin-right: 20px; text-decoration: none; } .dashboard-cards { display: flex; gap: 20px; flex-wrap: wrap; } .card { background: white; padding: 25px; min-width: 200px; border-radius: 10px; box-shadow: 0 0 10px rgba( 0, 0, 0, 0.15 ); } table { width: 100%; border-collapse: collapse; margin-top: 30px; background: white; } th, td { padding: 12px; border: 1px solid #ddd; } th { background: #222; color: white; } input, button { padding: 12px; margin: 8px; } button { cursor: pointer; } .flowchart { text-align: center; font-size: 20px; } .flowchart div { background: white; padding: 20px; margin: 10px auto; max-width: 500px; border-radius: 10px; box-shadow: 0 0 8px rgba( 0, 0, 0, 0.2 ); } 25. ESP32 to PHP API Connection In the ESP32 source code, the endpoint becomes: #define PHP_API_URL \ "https://your-domain.com/smart-retail/api/esp32_data.php" The ESP32 sends: { "product_id": "MILK001", "quantity": 5, "weight": 5200, "temperature": 28.5, "humidity": 61.4 } to: api/esp32_data.php PHP then: Receive JSON ↓ Validate Data ↓ Find Product ↓ Calculate Stock Status ↓ Calculate Risk ↓ Save MySQL Data ↓ Save History ↓ Send Response 26. Final PHP-Based System Architecture ┌──────────────────────────────┐ │ ESP32 │ │ │ │ RFID + Load Cell + DHT22 │ └──────────────┬───────────────┘ │ │ HTTP POST JSON ▼ ┌──────────────────────────────┐ │ PHP API SERVER │ │ │ │ esp32_data.php │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ MySQL │ │ │ │ Products │ │ Inventory │ │ History │ │ Alerts │ │ Predictions │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ PHP AI LOGIC │ │ │ │ Stock Analysis │ │ Consumption Prediction │ │ Reorder Prediction │ └──────────────┬───────────────┘ │ ┌───────┼────────┐ ▼ ▼ ▼ n8n Telegram ThingSpeak │ │ │ ▼ ▼ ▼ AI Voice Cloud Agent Alerts Dashboard │ ▼ Google Sheets 27. Complete Working Sequence 1. Product enters the retail shelf. 2. RFID identifies the product. 3. Load cell measures the product weight. 4. ESP32 reads environmental conditions. 5. ESP32 sends JSON data to PHP. 6. PHP validates the data. 7. PHP stores data in MySQL. 8. AI logic calculates stock status. 9. AI predicts future consumption. 10. AI estimates remaining stock days. 11. AI calculates reorder quantity. 12. n8n receives inventory data. 13. n8n updates Google Sheets. 14. n8n updates ThingSpeak. 15. Telegram text alert is sent. 16. Voice notification is generated. 17. Telegram voice alert is delivered. 18. PHP dashboard displays current status. 19. Store manager takes action. 28. Important Deployment Configuration For local testing: XAMPP Apache MySQL PHP Project location: C:\xampp\htdocs\smart-retail\ Open: http://localhost/smart-retail/ For Internet access: PHP Hosting MySQL Database HTTPS Domain n8n Cloud or VPS Telegram Bot Google Sheets API ThingSpeak Channel Final Result This PHP version gives you the complete software architecture for: ESP32 + RFID + Load Cell + DHT22 + PHP + MySQL + AI Inventory Prediction + n8n Automation + Telegram Text Alerts + Telegram Voice Notifications + Google Sheets + ThingSpeak + PHP IoT Web Dashboard. The only part that should not be written in PHP is the ESP32 firmware, because the ESP32 requires Arduino C++/C code to directly control sensors and hardware.