Monday, 28 September 2026

AI River Cleaning Boat with Autonomous Navigation

AI River-Cleaning Boat — Complete Project Documentation

This project combines an ESP32 autonomous surface boat, floating-waste collection mechanism, sensors, IoT telemetry , n8n automation, an AI agent, Telegram alerts/voice notifications, Google Sheets logging, and a ThingSpeak dashboard.

The ESP32 handles real-time sensing and motor control; n8n acts as the cloud automation/AI layer. ESP32 supports Wi-Fi station mode for Internet-connected IoT operation. Espressif Systems+1

1. Project objective

The boat is designed to:

  • Detect and collect floating plastic/waste.

  • Navigate autonomously along a predefined route.

  • Measure water/environment parameters.

  • Detect obstacles.

  • Monitor battery and motor status.

  • Send telemetry to an IoT cloud.

  • Log operating data in Google Sheets.

  • Use n8n to process sensor events.

  • Use an AI agent to interpret abnormal conditions.

  • Send Telegram text and voice alerts.

  • Provide a web dashboard.

  • Allow authorized remote commands.

  • Automatically stop when dangerous conditions are detected.

Example operating scenario

Boat starts
    ↓
ESP32 initializes sensors
    ↓
GPS + obstacle sensors checked
    ↓
Battery checked
    ↓
Motors start
    ↓
Autonomous navigation
    ↓
Floating waste detected
    ↓
Collector motor activated
    ↓
Waste collected
    ↓
Sensor data → n8n
    ↓
AI Agent analyzes status
    ↓
Google Sheets + ThingSpeak updated
    ↓
If abnormal:
    ↓
Telegram alert + voice notification

2. Overall system architecture

                         ┌──────────────────────┐
                         │     RIVER / LAKE      │
                         │                      │
                         │ Floating Plastic     │
                         │ Obstacles            │
                         │ Water                │
                         └──────────┬───────────┘
                                    │
                         Sensors / Collector
                                    │
                         ┌──────────▼───────────┐
                         │        ESP32         │
                         │                      │
                         │ GPS                  │
                         │ Ultrasonic/ToF       │
                         │ Water sensors        │
                         │ Battery monitor      │
                         │ Motor control        │
                         │ Collector control    │
                         │ Wi-Fi                │
                         └──────────┬───────────┘
                                    │
                              HTTPS / JSON
                                    │
                    ┌───────────────▼───────────────┐
                    │             n8n                │
                    │       Automation Server       │
                    │                               │
                    │ Webhook → Processing          │
                    │ AI Agent → Decision support   │
                    │ Google Sheets                 │
                    │ Telegram                     │
                    │ ThingSpeak                   │
                    └───────┬─────────┬─────────────┘
                            │         │
                 ┌──────────▼───┐ ┌──▼─────────────┐
                 │ Google Sheets│ │ ThingSpeak     │
                 │ Data logging │ │ IoT Dashboard  │
                 └──────────────┘ └────────────────┘
                            │
                       ┌────▼─────┐
                       │ Telegram │
                       │           │
                       │ Text      │
                       │ Voice     │
                       │ Commands  │
                       └───────────┘

n8n is particularly suitable here because it provides workflow automation and AI capabilities and can connect applications through APIs. n8n Documentation


3. Major hardware components

Controller

Component Purpose
ESP32 DevKit Main controller
GPS module Position/navigation
Ultrasonic/ToF sensors Obstacle detection
IMU Heading/orientation
Motor driver/ESC Propulsion
DC motors/BLDC motors Boat propulsion
Servo motors Rudder/steering
Conveyor motor Waste collection
Water-level sensor Collector/bin monitoring
Current sensor Motor/battery monitoring
Voltage divider Battery measurement
Battery Boat power
Solar panel Optional charging
Buzzer/LED Local warning
Waterproof enclosure Electronics protection

Recommended sensor arrangement

                         FRONT
                           ↑
                    ┌─────────────┐
                    │   GPS       │
                    │             │
              ┌─────┴─────────────┴─────┐
              │                          │
      LEFT    │       ESP32              │   RIGHT
      ToF ───►│                          │◄── ToF
              │                          │
              │   Battery Monitor        │
              │   IMU                    │
              └────────────┬─────────────┘
                           │
                    Collection Area
                           │
                  ┌────────▼────────┐
                  │ Conveyor / Net   │
                  │ Waste Collector  │
                  └─────────────────┘
                           │
                    ┌──────▼──────┐
                    │ Waste Bin   │
                    └─────────────┘

                  ← Propulsion →

4. Electrical architecture

A practical design separates the motor power from the ESP32/sensor power.

                 MAIN BATTERY
                 12V / 24V
                     │
             ┌───────┴────────┐
             │                │
             ▼                ▼
       Motor Driver/ESC    DC-DC Buck
             │                │
             ▼                ▼
        Propulsion        5V / 3.3V
          Motors              │
                              ▼
                           ESP32
                              │
        ┌─────────────────────┼─────────────────┐
        │          │          │         │        │
       GPS        IMU       ToF       Current   Water
                              │       Sensor    Sensor

Important: do not power large motors directly from the ESP32 5-V/3.3-V rail.

Use a suitable regulator and common ground, with appropriate fusing and waterproof connectors.


5. Example ESP32 pin assignment

This is an example—not a universal pinout. Adapt it to your exact ESP32 board and peripherals.

ESP32 GPIO Device
GPIO 16 GPS RX
GPIO 17 GPS TX
GPIO 21 I²C SDA
GPIO 22 I²C SCL
GPIO 25 Left motor PWM
GPIO 26 Right motor PWM
GPIO 27 Collector motor
GPIO 32 Battery ADC
GPIO 33 Current sensor
GPIO 34 Water-level input
GPIO 18 Left obstacle sensor
GPIO 19 Right obstacle sensor
GPIO 23 Emergency-stop input
GPIO 2 Status LED

Keep ADC/input voltage limits in mind when designing the battery-voltage measurement circuit.


6. Schematic diagram

                         +----------------+
                         |    BATTERY     |
                         |   12/24 V      |
                         +-------+--------+
                                 |
                +----------------+----------------+
                |                                 |
                ▼                                 ▼
        +---------------+                 +---------------+
        | Motor Driver  |                 | DC-DC Buck    |
        +-------+-------+                 +-------+-------+
                |                                 |
          +-----+-----+                           |
          |           |                           ▼
          ▼           ▼                    +-------------+
       Left Motor  Right Motor             |    ESP32    |
                                           +------+------+ 
                                                  |
       +----------------------+-------------------+----------------+
       |          |           |           |        |               |
       ▼          ▼           ▼           ▼        ▼               ▼
      GPS        IMU        ToF        Current   Water          Collector
    Module      Sensor     Sensors     Sensor    Sensor           Motor

Motor-driver concept

ESP32 GPIO25 ─────► LEFT PWM ─────► Motor Driver ─────► Left Motor

ESP32 GPIO26 ─────► RIGHT PWM ────► Motor Driver ─────► Right Motor

ESP32 GPIO27 ─────► COLLECTOR ────► MOSFET/Driver ────► Conveyor Motor

ESP32 GND ─────────────────────────► Driver GND
Battery GND ───────────────────────► Common GND

For a higher-power boat, use properly rated marine/automotive motor drivers or ESCs rather than a small hobby driver.


7. Autonomous navigation concept

The navigation algorithm can use GPS waypoints.

             START
               │
               ▼
         Read GPS position
               │
               ▼
       Calculate distance
       to current waypoint
               │
       ┌───────┴────────┐
       │                │
   Far away          Reached
       │                │
       ▼                ▼
 Calculate heading   Next waypoint
       │                │
       ▼                │
 Check obstacle       │
       │                │
 ┌─────┴─────┐         │
 │           │         │
Clear      Obstacle    │
 │           │         │
 ▼           ▼         │
Forward    Avoidance   │
 │           │         │
 └─────┬─────┘         │
       │               │
       └───────┬───────┘
               ▼
          Continue route

For a prototype, waypoint navigation can use:

  • GPS position

  • Desired waypoint

  • Current heading

  • Heading error

  • Obstacle distance

The ESP32 should always retain local control authority. Cloud/AI commands should not directly control motors without safety checks.


8. AI-agent architecture

The AI should be an advisory/decision layer, not the only safety controller.

ESP32
 │
 │ sensor JSON
 ▼
n8n Webhook
 │
 ▼
Validate JSON
 │
 ▼
Calculate derived values
 │
 ▼
AI Agent
 │
 ├──► Normal
 │
 ├──► Warning
 │
 ├──► Critical
 │
 └──► Maintenance
 │
 ▼
Decision
 │
 ├─────────────► Google Sheets
 │
 ├─────────────► ThingSpeak
 │
 └─────────────► Telegram

Example AI input:

{
  "device_id": "RIVERBOAT_01",
  "battery": 38,
  "battery_voltage": 11.7,
  "gps_lat": 17.385,
  "gps_lon": 78.486,
  "speed": 1.2,
  "obstacle_distance": 2.8,
  "collector_current": 1.7,
  "waste_bin_level": 72,
  "water_level": 0.4,
  "motor_temperature": 48,
  "status": "RUNNING"
}

AI output should be structured:

{
  "severity": "WARNING",
  "summary": "Battery is approaching the configured return threshold.",
  "recommended_action": "RETURN_TO_BASE",
  "send_alert": true,
  "reason": "Battery is below the configured operating threshold."
}

Do not allow an AI model to bypass hard-coded emergency conditions.


9. n8n master workflow

                    ┌─────────────┐
                    │ ESP32       │
                    └──────┬──────┘
                           │
                           ▼
                    ┌─────────────┐
                    │ Webhook     │
                    └──────┬──────┘
                           ▼
                    ┌─────────────┐
                    │ Validate    │
                    │ JSON        │
                    └──────┬──────┘
                           ▼
                    ┌─────────────┐
                    │ Normalize   │
                    │ Data        │
                    └──────┬──────┘
                           ▼
                    ┌─────────────┐
                    │ AI Agent    │
                    └──────┬──────┘
                           │
                ┌──────────┼───────────┐
                ▼          ▼           ▼
             Normal     Warning     Critical
                │          │           │
                ▼          ▼           ▼
           ThingSpeak   Telegram    Telegram
                │          │       Voice/Text
                ▼          ▼           │
          Google Sheets   Sheets        ▼
                │                      Action
                └──────────┬────────────┘
                           ▼
                     Response
                           │
                           ▼
                         ESP32

n8n has built-in Telegram support for sending messages and other Telegram operations. n8n Documentation


10. ESP32 → n8n communication

Use an HTTPS POST request.

Example endpoint

POST https://YOUR-N8N-DOMAIN/webhook/riverboat

Example JSON

{
  "device_id": "RIVERBOAT_01",
  "timestamp": 1720000000,
  "latitude": 17.385044,
  "longitude": 78.486671,
  "battery_voltage": 12.1,
  "battery_percent": 65,
  "speed": 1.3,
  "heading": 92,
  "obstacle_left": 4.2,
  "obstacle_right": 6.8,
  "waste_level": 58,
  "collector_current": 1.2,
  "temperature": 42,
  "mode": "AUTO"
}

11. ESP32 Arduino firmware

Below is a working architectural starting point rather than a finished marine-certified controller.

#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";

const char* N8N_URL =
  "https://YOUR-N8N-DOMAIN/webhook/riverboat";

#define LEFT_MOTOR_PIN      25
#define RIGHT_MOTOR_PIN     26
#define COLLECTOR_PIN       27
#define BATTERY_PIN         32
#define CURRENT_PIN         33
#define EMERGENCY_PIN       23

unsigned long lastSend = 0;

void connectWiFi()
{
  WiFi.begin(WIFI_SSID, WIFI_PASS);

  Serial.print("Connecting");

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.println(WiFi.localIP());
}

float readBatteryVoltage()
{
  int raw = analogRead(BATTERY_PIN);

  // Replace with calibration for your voltage-divider circuit.
  float voltage = (raw / 4095.0) * 3.3;

  // Example divider correction:
  voltage *= 4.0;

  return voltage;
}

float readCurrent()
{
  int raw = analogRead(CURRENT_PIN);

  // Replace with calibration for your current sensor.
  float voltage = (raw / 4095.0) * 3.3;

  return voltage;
}

void stopBoat()
{
  ledcWrite(0, 0);
  ledcWrite(1, 0);

  digitalWrite(COLLECTOR_PIN, LOW);
}

void sendTelemetry()
{
  if (WiFi.status() != WL_CONNECTED)
  {
    connectWiFi();
  }

  float battery = readBatteryVoltage();
  float current = readCurrent();

  StaticJsonDocument<1024> doc;

  doc["device_id"] = "RIVERBOAT_01";
  doc["battery_voltage"] = battery;
  doc["current_sensor"] = current;
  doc["mode"] = "AUTO";
  doc["emergency"] = digitalRead(EMERGENCY_PIN) == LOW;

  // Replace these placeholders with real sensor readings.
  doc["latitude"] = 17.385044;
  doc["longitude"] = 78.486671;
  doc["speed"] = 1.2;
  doc["heading"] = 90;
  doc["obstacle_left"] = 5.0;
  doc["obstacle_right"] = 5.0;
  doc["waste_level"] = 40;

  String payload;
  serializeJson(doc, payload);

  HTTPClient http;

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

  int response = http.POST(payload);

  Serial.print("n8n response: ");
  Serial.println(response);

  http.end();
}

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

  pinMode(COLLECTOR_PIN, OUTPUT);
  pinMode(EMERGENCY_PIN, INPUT_PULLUP);

  ledcAttach(LEFT_MOTOR_PIN, 1000, 8);
  ledcAttach(RIGHT_MOTOR_PIN, 1000, 8);

  connectWiFi();

  stopBoat();
}

void loop()
{
  if (digitalRead(EMERGENCY_PIN) == LOW)
  {
    stopBoat();

    Serial.println("EMERGENCY STOP");
    delay(1000);
    return;
  }

  if (millis() - lastSend > 15000)
  {
    lastSend = millis();

    sendTelemetry();
  }

  delay(20);
}

The current Arduino ESP32 documentation is based on Arduino-ESP32 3.3.12 / ESP-IDF 5.5, so check the installed core version when adapting PWM/API calls. Espressif Systems


12. n8n Webhook workflow

Create:

Webhook
   ↓
Code / Edit Fields
   ↓
IF – Safety Check
   ↓
AI Agent
   ↓
Switch – Severity

Webhook

Method:

POST

Path:

riverboat

Expected input:

{
  "device_id": "RIVERBOAT_01",
  "battery_voltage": 12.1,
  "battery_percent": 65,
  "obstacle_left": 4.2,
  "obstacle_right": 6.8,
  "waste_level": 58,
  "mode": "AUTO"
}

13. n8n safety workflow

Use deterministic rules before the AI agent.

                 Sensor Data
                      │
                      ▼
              Battery < 20%?
                /          \
              YES           NO
               │             │
               ▼             ▼
         CRITICAL       Obstacle < 1m?
                            /      \
                          YES       NO
                           │         │
                           ▼         ▼
                       CRITICAL    AI Agent

Example n8n Code node:

const d = $json;

let severity = "NORMAL";

if (d.battery_percent !== undefined &&
    d.battery_percent < 20) {
  severity = "CRITICAL";
}

if (d.obstacle_left !== undefined &&
    d.obstacle_left < 1.0) {
  severity = "CRITICAL";
}

if (d.obstacle_right !== undefined &&
    d.obstacle_right < 1.0) {
  severity = "CRITICAL";
}

if (d.waste_level !== undefined &&
    d.waste_level > 90) {
  severity = "WARNING";
}

return [{
  json: {
    ...d,
    safety_severity: severity
  }
}];

14. AI Agent prompt

Use an AI agent only after deterministic safety processing.

You are the monitoring assistant for an autonomous river-cleaning boat.

Your job is to analyze telemetry and report operational conditions.

Rules:

1. Never override emergency-stop conditions.
2. Never claim that a dangerous condition is safe.
3. Do not invent sensor values.
4. Use only the supplied telemetry.
5. Identify battery, obstacle, motor, collector and communication problems.
6. Return valid JSON.
7. If a critical deterministic safety flag is present, report CRITICAL.
8. Recommend stopping or returning to base when appropriate.
9. Do not directly authorize unsafe motor operation.

Return:

{
  "severity": "NORMAL|WARNING|CRITICAL",
  "summary": "...",
  "recommended_action": "...",
  "send_alert": true,
  "reason": "..."
}

15. Google Sheets database

Create a spreadsheet:

RiverBoat_Logs

Columns:

Timestamp
Device_ID
Latitude
Longitude
Battery_Voltage
Battery_Percent
Speed
Heading
Obstacle_Left
Obstacle_Right
Waste_Level
Collector_Current
Motor_Temperature
Mode
AI_Severity
AI_Summary
Action

Workflow:

ESP32
 ↓
n8n Webhook
 ↓
Data processing
 ↓
Google Sheets → Append Row

This creates a historical operational database without requiring a dedicated SQL server.


16. ThingSpeak dashboard

Create a ThingSpeak channel with fields such as:

Field 1 = Battery %
Field 2 = Speed
Field 3 = Waste %
Field 4 = Obstacle Distance
Field 5 = Motor Temperature
Field 6 = Collector Current
Field 7 = Latitude
Field 8 = Longitude

ThingSpeak provides REST APIs for writing and reading channel data. MathWorks+1

An update can use:

https://api.thingspeak.com/update

with parameters such as:

api_key=YOUR_WRITE_KEY
field1=65
field2=1.2
field3=58
field4=4.2
field5=42
field6=1.2

ThingSpeak documents both GET and POST methods for channel updates. MathWorks

n8n flow

Webhook
   ↓
Edit Fields
   ↓
HTTP Request
   ↓
ThingSpeak

17. Telegram notification system

Telegram can operate as the human interface.

                    TELEGRAM
                       │
           ┌───────────┴───────────┐
           │                       │
        Commands                 Alerts
           │                       │
           ▼                       ▼
     Telegram Trigger          n8n
           │                       │
           ▼                       ▼
       AI Agent              Message/Voice
           │
           ▼
        ESP32/API

Telegram's Bot API supports HTTP-based bot communication, including webhooks and sendVoice for voice messages. Telegram


18. Telegram commands

Useful commands:

/start
/status
/location
/battery
/waste
/stop
/resume
/auto
/manual
/collector
/return
/help

Example:

/status

Response:

🚤 RIVERBOAT STATUS

Mode: AUTO
Battery: 65%
Speed: 1.2 m/s
Waste bin: 58%
Obstacle: 4.2 m
Collector: RUNNING
GPS: Available
System: NORMAL

19. Telegram voice alert

Example event:

Battery < configured threshold
          ↓
        n8n
          ↓
     AI analysis
          ↓
      CRITICAL
          ↓
Generate voice message
          ↓
Telegram sendVoice

Example spoken message:

“River Boat warning. Battery level is low. The boat should return to the charging station.”

The exact voice-generation service can be selected according to your deployment; n8n then sends the resulting audio through Telegram.


20. Telegram emergency conversation

User

/status

Bot

🚤 Boat Status

Mode: AUTO
Battery: 71%
Waste: 43%
Obstacle: 3.8 m
GPS: OK
System: NORMAL

User

/waste

Bot

🗑 Waste collection

Container: 43%
Collector motor: ON
Estimated remaining capacity: 57%

Automatic alert

🚨 RIVERBOAT ALERT

Battery: 18%
Status: CRITICAL
Action: RETURN_TO_BASE

Reason:
Battery has crossed the configured return threshold.

21. AI Telegram agent

A more advanced architecture is:

             Telegram User
                    │
                    ▼
             Telegram Trigger
                    │
                    ▼
                 AI Agent
              /     |      \
             /      |       \
        Status    Sensors   Control
          Tool      Tool      Tool
           │         │         │
           ▼         ▼         ▼
        Google    ThingSpeak  n8n/API
        Sheets

The AI agent can answer:

User:
"What is the boat doing?"

Agent:
"The boat is operating in AUTO mode,
travelling at 1.2 m/s. Battery is 65%.
The collector is active and the waste
container is approximately 58% full."

For control commands, implement authorization and deterministic safety checks.


22. Web IoT dashboard

A simple dashboard can contain:

┌───────────────────────────────────────────────┐
│          AI RIVER CLEANING BOAT               │
├───────────────────────────────────────────────┤
│                                               │
│ Battery             65%       🟢              │
│ Speed               1.2 m/s                   │
│ Waste               58%                      │
│ Motor Temperature   42 °C                    │
│                                               │
│ GPS                                             │
│ ┌───────────────────────────────────────────┐ │
│ │                                           │ │
│ │              BOAT ●                       │ │
│ │                                           │ │
│ └───────────────────────────────────────────┘ │
│                                               │
│ System: NORMAL                                │
│ Collector: ON                                 │
│ Navigation: AUTO                              │
│                                               │
├───────────────────────────────────────────────┤
│ Latest AI Message                             │
│ "Boat operating normally."                    │
└───────────────────────────────────────────────┘

23. Webpage architecture

ESP32
  │
  ├──────────────► n8n
  │                 │
  │                 ├────► Google Sheets
  │                 │
  │                 ├────► ThingSpeak
  │                 │
  │                 └────► AI
  │
  └────► Optional direct API

Browser
   │
   ▼
Dashboard API
   │
   ▼
Latest boat state

The dashboard should display:

  • Current GPS position

  • Battery

  • Speed

  • Heading

  • Waste level

  • Obstacle distance

  • Motor temperature

  • Collector state

  • Connection state

  • AI status

  • Last update

  • Route

  • Alerts


24. Waste collection mechanism

One practical arrangement is a front conveyor.

             BOAT MOVEMENT
                  ↑
                  │
        Floating waste
          ○   □   △
           \  |  /
            \ | /
       ┌─────▼──────┐
       │ Collection │
       │   ramp     │
       └─────┬──────┘
             │
       ╔═════▼═════╗
       ║ CONVEYOR  ║
       ║ ↑ ↑ ↑ ↑   ║
       ╚═════╤═════╝
             │
             ▼
        ┌───────────┐
        │ Waste Bin │
        └───────────┘

The conveyor should be physically isolated from the propellers.


25. Collector control algorithm

Read waste detection
       │
       ▼
Waste detected?
    /       \
  NO         YES
  │           │
  ▼           ▼
Continue    Start conveyor
navigation      │
                ▼
          Monitor current
                │
       ┌────────┴────────┐
       │                 │
 Normal current     Excess current
       │                 │
       ▼                 ▼
Continue           Stop conveyor
                       │
                       ▼
                  Send alert

Current monitoring is important because a jammed conveyor can damage the motor or wiring.


26. Autonomous obstacle avoidance

Example:

               FRONT

        LEFT       CENTER       RIGHT

       Sensor       Sensor       Sensor
         │            │            │
         ▼            ▼            ▼
        4m           0.7m          5m

                       X
                    OBSTACLE

                    ↓
             Stop / turn right

Simple logic:

if (centerDistance < 1.0) {
    stopBoat();

    if (leftDistance > rightDistance) {
        turnLeft();
    } else {
        turnRight();
    }
}

For a real river environment, don't rely on one ultrasonic sensor. Water reflections, waves, vegetation, floating objects and environmental conditions can produce unreliable readings.


27. Navigation state machine

                  ┌──────────────┐
                  │    START     │
                  └──────┬───────┘
                         ▼
                  ┌──────────────┐
                  │   SELF TEST  │
                  └──────┬───────┘
                         ▼
                  ┌──────────────┐
                  │ GPS ACQUIRED │
                  └──────┬───────┘
                         ▼
                  ┌──────────────┐
                  │ AUTO NAV     │◄─────────────┐
                  └──────┬───────┘              │
                         │                      │
            ┌────────────┼─────────────┐        │
            ▼            ▼             ▼        │
        OBSTACLE     LOW BATTERY    BIN FULL    │
            │            │             │        │
            ▼            ▼             ▼        │
         AVOID       RETURN HOME     RETURN     │
            │            │             │        │
            └────────────┴─────────────┘        │
                         │                      │
                         ▼                      │
                    SAFE STATE ────────────────┘

28. Data flow

Sensors
  │
  ▼
ESP32
  │
  ├── Navigation
  ├── Motor control
  ├── Safety
  └── Telemetry
          │
          ▼
       HTTPS
          │
          ▼
        n8n
          │
     ┌────┼────┐
     ▼    ▼    ▼
    AI  Sheets ThingSpeak
     │
     ▼
 Telegram

29. Example n8n workflows

Workflow A — Telemetry

Webhook
 ↓
Validate
 ↓
Edit Fields
 ↓
Google Sheets
 ↓
HTTP Request → ThingSpeak
 ↓
Respond to Webhook

Workflow B — AI monitoring

Webhook
 ↓
Safety Rules
 ↓
AI Agent
 ↓
Switch
 ├── NORMAL → Log
 ├── WARNING → Telegram
 └── CRITICAL → Telegram + Voice

Workflow C — Telegram commands

Telegram Trigger
       ↓
Extract command
       ↓
Switch
 ├── /status
 ├── /location
 ├── /battery
 ├── /stop
 ├── /return
 └── /collector
       ↓
Authorization
       ↓
Safety validation
       ↓
ESP32 command API
       ↓
Telegram response

30. ESP32 command API

You can expose a secure command endpoint through your cloud architecture rather than exposing the ESP32 directly to the Internet.

Example commands:

{
  "command": "RETURN_TO_BASE",
  "device_id": "RIVERBOAT_01",
  "request_id": "abc123"
}

Possible command set:

STOP
START
AUTO
MANUAL
RETURN_TO_BASE
COLLECTOR_ON
COLLECTOR_OFF
STATUS

The ESP32 should validate every command.

For example:

if (command == "STOP") {
    stopBoat();
}

But:

if (command == "START") {
    if (batteryOK &&
        gpsOK &&
        obstacleSystemOK &&
        !emergencyStop) {

        startBoat();
    }
}

31. Security architecture

Never put these directly into publicly visible firmware:

Telegram Bot Token
n8n credentials
Google credentials
AI API key
ThingSpeak write key

Instead:

ESP32
  │
  │ HTTPS
  ▼
n8n
  │
  ├── Credentials
  ├── AI API
  ├── Telegram token
  ├── Google credentials
  └── ThingSpeak key

Use HTTPS and authentication for the webhook.

Telegram also supports webhook secret tokens for authenticating webhook requests. Telegram


32. Failure handling

The boat should continue safely even when the Internet disappears.

                 Internet lost
                      │
                      ▼
                   ESP32
                      │
          ┌───────────┴───────────┐
          │                       │
       Sensors                 Internet
          │                       │
          ▼                       X
     Local control            unavailable
          │
          ▼
   Safe operating mode

Recommended behavior:

Failure Response
Wi-Fi lost Continue local safety logic
GPS lost Reduce/stop autonomous navigation
Low battery Return/stop
Motor overcurrent Stop affected motor
Collector jam Stop collector
Bin full Stop collection/return
Obstacle detected Avoid/stop
ESP32 watchdog reset Motors default OFF
Emergency button Immediate motor stop

33. Watchdog and failsafe concept

                 ESP32
                   │
              Watchdog timer
                   │
             ┌─────▼─────┐
             │ Main loop │
             └─────┬─────┘
                   │
             heartbeat OK?
              /          \
            YES           NO
             │             │
             ▼             ▼
        Continue       Reset/SAFE
                            │
                            ▼
                       Motors OFF

Motor drivers should also be arranged so that a loss of control signal produces a safe state.


34. Suggested project directory

AI-River-Cleaning-Boat/
│
├── firmware/
│   ├── riverboat.ino
│   ├── config.h
│   ├── navigation.cpp
│   ├── navigation.h
│   ├── sensors.cpp
│   ├── sensors.h
│   ├── motors.cpp
│   ├── motors.h
│   └── telemetry.cpp
│
├── n8n/
│   ├── telemetry-workflow.json
│   ├── telegram-workflow.json
│   └── ai-monitor-workflow.json
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── documentation/
│   ├── architecture.md
│   ├── wiring.md
│   ├── installation.md
│   └── testing.md
│
└── README.md

35. Software installation

For ESP32:

  1. Install Arduino IDE.

  2. Install ESP32 board support.

  3. Select your ESP32 board.

  4. Install required libraries.

  5. Configure Wi-Fi.

  6. Configure n8n endpoint.

  7. Upload firmware.

  8. Open Serial Monitor.

  9. Verify Wi-Fi.

  10. Verify telemetry.

Espressif's official documentation provides the current Arduino-ESP32 installation and API references. Espressif Systems+1

Required libraries can include:

WiFi
HTTPClient
ArduinoJson
Wire
TinyGPSPlus

depending on the sensors and navigation hardware selected.


36. n8n setup

Deploy n8n using either:

n8n Cloud

or

Self-hosted n8n
       │
       ▼
Docker / VPS

Create credentials for:

Google Sheets
Telegram
AI provider

Then create:

Webhook → Processing → AI → Sheets → ThingSpeak → Telegram

n8n provides both cloud and self-hosting options in its documentation. n8n Documentation


37. Testing procedure

Do not begin testing in a river.

Stage 1 — Bench

Test:

ESP32
 ↓
Sensors
 ↓
Motor driver
 ↓
Telemetry

Stage 2 — Motors unloaded

Verify:

Forward
Reverse
Left
Right
Stop
Collector ON/OFF
Emergency STOP

Stage 3 — Dry-land obstacle tests

Test sensor behavior.

Stage 4 — Controlled water tank

Test:

Buoyancy
Waterproofing
Propulsion
Collector
Battery
GPS

Stage 5 — Controlled outdoor water

Use a supervised environment.

Stage 6 — River deployment

Only after:

Emergency stop ✓
GPS ✓
Obstacle detection ✓
Battery monitoring ✓
Communication ✓
Failsafe ✓
Waterproofing ✓
Manual recovery ✓

38. Test cases

Test Expected result
Wi-Fi disconnected Local safety remains active
Battery low Return/stop
Obstacle < threshold Boat avoids/stops
Bin full Collector stops
Conveyor jam Overcurrent detected
GPS unavailable Autonomous mode restricted
Emergency switch Motors immediately stop
n8n unavailable ESP32 remains safe
Telegram unavailable Boat remains safe
AI unavailable Deterministic safety still works
ESP32 reboot Motors start OFF
Sensor disconnected Fault detected

39. Complete system sequence

POWER ON
   │
   ▼
ESP32 BOOT
   │
   ▼
SELF TEST
   │
   ├── FAIL ──► SAFE MODE
   │
   ▼
GPS + SENSOR CHECK
   │
   ▼
CONNECT Wi-Fi
   │
   ▼
START TELEMETRY
   │
   ▼
AUTO NAVIGATION
   │
   ▼
SCAN FOR OBSTACLES
   │
   ├── Obstacle ──► AVOID
   │
   ▼
SCAN FOR WASTE
   │
   ├── Waste ──► COLLECTOR ON
   │
   ▼
MONITOR BATTERY
   │
   ├── Low ──► RETURN
   │
   ▼
SEND DATA TO n8n
   │
   ▼
AI ANALYSIS
   │
   ├── Normal
   ├── Warning ──► Telegram
   └── Critical ─► Voice + Telegram
   │
   ▼
Google Sheets
   │
   ▼
ThingSpeak
   │
   ▼
CONTINUE MISSION

40. Key design principle

The most important architectural separation is:

                 SAFETY
                   ▲
                   │
             ESP32 LOCAL
                   │
        ┌──────────┴──────────┐
        │                     │
   Motor control          Sensors
        │                     │
        └──────────┬──────────┘
                   │
                TELEMETRY
                   │
                   ▼
                  n8n
                   │
              AI AGENT
                   │
       ┌───────────┼───────────┐
       ▼           ▼           ▼
    Telegram    Sheets     ThingSpeak

AI/n8n should enhance monitoring and automation; it should not be the sole mechanism preventing a collision, runaway boat, motor failure, or unsafe operation.

ThingSpeak's REST interface is appropriate for telemetry, while Telegram's Bot API provides the messaging/voice-alert layer. MathWorks+1

<h2 dir="ltr">Project<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
Summary</h2>
<p dir="ltr"><strong>AI River Cleaning Boat with Autonomous Navigation</strong> is an IoT-based floating robotic<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
system built around an <strong>ESP32</strong>. It autonomously navigates waterways, detects obstacles, collects floating waste, monitors its own condition, and sends<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
telemetry to a cloud automation system.</p>
<h3 dir="ltr">Core architecture</h3>
<pre dir="ltr"><code>Sensors
&darr;
ESP32
├── GPS navigation
├── Obstacle detection
├── Battery monitoring
├── Motor control
└── Waste collection
&darr;
Wi-Fi/HTTPS
&darr;
n8n
&darr;
AI Agent
┌────┼─────┐
&darr; &darr; &darr;
Telegram Sheets ThingSpeak
</code><!--portal--><!--comp--><!--/comp--><!--/portal--></pre>
<h3 dir="ltr">Main hardware</h3>
<ul>
<li>
<p dir="ltr">ESP32</p>
</li>
<li>
<p dir="ltr">GPS module</p>
</li>
<li>
<p dir="ltr">Ultrasonic/ToF obstacle sensors</p>
</li>
<li>
<p dir="ltr">IMU<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
</p>
</li>
<li>
<p dir="ltr">Motor driver/ESC</p>
</li>
<li>
<p dir="ltr">Propulsion motors</p>
</li>
<li>
<p dir="ltr">Conveyor/collection motor<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
</p>
</li>
<li>
<p dir="ltr">Waste bin</p>
</li>
<li>
<p dir="ltr">Battery + DC-DC converter</p>
</li>
<li>
<p dir="ltr">Current/voltage sensors</p>
</li>
<li>
<p dir="ltr">Emergency-stop switch</p>
</li>
<li>
<p dir="ltr">Waterproof electronics enclosure</p>
</li>
</ul>
<h3 dir="ltr">Main software</h3>
<ul>
<li>
<p dir="ltr"><strong>ESP32 Arduino firmware</strong> &mdash; sensors, navigation, motors and safety</p>
</li>
<li>
<p dir="ltr"><strong>n8n</strong> &mdash; automation and integration</p>
</li>
<li>
<p dir="ltr"><strong>AI Agent</strong> &mdash; telemetry analysis and recommendations</p>
</li>
<li>
<p dir="ltr"><strong>Telegram Bot</strong> &mdash; status, commands and alerts</p>
</li>
<li>
<p dir="ltr"><strong>Google Sheets</strong> &mdash; historical data logging</p>
</li>
<li>
<p dir="ltr"><strong>ThingSpeak</strong> &mdash; IoT telemetry dashboard</p>
</li>
<li>
<p dir="ltr"><strong>Web dashboard</strong> &mdash; live boat status</p>
</li>
</ul>
<h3 dir="ltr">Automation</h3>
<pre dir="ltr"><code>ESP32 telemetry
&darr;
n8n Webhook
&darr;
Safety checks
&darr;
AI analysis
&darr;
┌─────┼─────────┐
&darr; &darr; &darr;
Normal Warning Critical
&darr; &darr;
Telegram Telegram
+ Voice
&darr;
Google Sheets
&darr;
ThingSpeak
</code><!--portal--><!--comp--><!--/comp--><!--/portal--></pre>
<h3 dir="ltr">Important safety concept</h3>
<p dir="ltr">The <strong>ESP32 remains responsible for real-time safety</strong>. AI and n8n should not be trusted as the sole<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
emergency-control mechanism.</p>
<p dir="ltr">Examples:</p>
<ul>
<li>
<p dir="ltr">Low battery &rarr; return/stop</p>
</li>
<li>
<p dir="ltr">Obstacle too close &rarr; stop/avoid</p>
</li>
<li>
<p dir="ltr">Conveyor jam &rarr; stop collector</p>
</li>
<li>
<p dir="ltr">Full waste bin &rarr; stop collection</p>
</li>
<li>
<p dir="ltr">GPS failure &rarr; restrict autonomous operation</p>
</li>
<li>
<p dir="ltr">Emergency switch &rarr; immediate motor shutdown</p>
</li>
<li>
<p dir="ltr">Internet failure &rarr; local ESP32 failsafe continues</p>
</li>
</ul>
<h3 dir="ltr">Final project workflow</h3>
<pre dir="ltr"><code>POWER ON
&darr;
SELF TEST
&darr;
GPS/SENSOR CHECK
&darr;
AUTONOMOUS NAVIGATION
&darr;
OBSTACLE DETECTION
&darr;
WASTE DETECTION
&darr;
COLLECT WASTE
&darr;
SEND TELEMETRY
&darr;
n8n + AI AGENT
&darr;
Sheets + ThingSpeak
&darr;
Telegram/Voice Alerts
&darr;
CONTINUE / RETURN TO BASE
</code><!--portal--><!--comp--><!--/comp--><!--/portal--></pre>
<p dir="ltr">This gives<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
you a complete <strong>ESP32 + Autonomous Boat + IoT + n8n + AI Agent + Telegram + Google Sheets + ThingSpeak</strong> project architecture suitable<?marker name="assistant-pending-38d85a97-3f2d-43f9-82fb-292b06f577fc-pending-tail"?>
for turning into a prototype, academic project, or final-year engineering project.</p>
<p>&nbsp;</p>

AI River Cleaning Boat — Mind Map

                         🚤 AI RIVER CLEANING BOAT
                                  │
        ┌─────────────────────────┼─────────────────────────┐
        │                         │                         │
        ▼                         ▼                         ▼
   🤖 HARDWARE                🧠 SOFTWARE               ☁️ CLOUD/IoT
        │                         │                         │
        ├─ ESP32                  ├─ Arduino IDE            ├─ n8n
        ├─ GPS                    ├─ ESP32 Firmware          ├─ AI Agent
        ├─ IMU                    ├─ Navigation             ├─ ThingSpeak
        ├─ ToF/Ultrasonic         ├─ Sensor Processing      ├─ Google Sheets
        ├─ Battery Sensor         ├─ Motor Control          └─ Web Dashboard
        ├─ Current Sensor        └─ Safety Logic
        ├─ Motor Driver
        ├─ Propulsion Motors
        ├─ Collector Motor
        └─ Waste Bin
                                  │
                                  ▼
                         🧭 AUTONOMOUS NAVIGATION
                                  │
                         ┌────────┼────────┐
                         │        │        │
                         ▼        ▼        ▼
                       GPS     Heading   Waypoints
                         │        │        │
                         └────────┼────────┘
                                  ▼
                           Obstacle Avoidance
                                  │
                         ┌────────┴────────┐
                         ▼                 ▼
                       Clear            Obstacle
                         │                 │
                         ▼                 ▼
                      Forward         Stop / Turn
                         
        ┌─────────────────────────┼─────────────────────────┐
        │                         │                         │
        ▼                         ▼                         ▼
   🗑️ WASTE COLLECTION       📡 TELEMETRY              🚨 SAFETY
        │                         │                         │
        ├─ Waste detection        ├─ Battery                ├─ Emergency stop
        ├─ Conveyor               ├─ GPS                    ├─ Low battery
        ├─ Motor                  ├─ Speed                  ├─ Obstacle
        ├─ Collection ramp        ├─ Heading                ├─ Motor overcurrent
        └─ Waste-level sensor    ├─ Waste level            ├─ GPS failure
                                  └─ Temperature             └─ Communication loss
                                        │
                                        ▼
                                  HTTPS / JSON
                                        │
                                        ▼
                                      n8n
                                        │
                         ┌──────────────┼──────────────┐
                         │              │              │
                         ▼              ▼              ▼
                    Safety Rules     AI Agent      Data Processing
                         │              │              │
                         └──────────────┼──────────────┘
                                        │
                    ┌───────────────────┼───────────────────┐
                    │                   │                   │
                    ▼                   ▼                   ▼
              📱 TELEGRAM          📊 GOOGLE SHEETS    📈 THINGSPEAK
                    │                   │                   │
                    ├─ Status           ├─ Telemetry       ├─ Dashboard
                    ├─ Alerts           ├─ GPS             ├─ Battery
                    ├─ Voice            ├─ Battery          ├─ Speed
                    ├─ /stop            ├─ Waste            ├─ Waste
                    ├─ /status          └─ AI events        └─ Temperature
                    ├─ /return
                    └─ /battery
                                        │
                                        ▼
                              🌐 WEB DASHBOARD
                                        │
                         ┌──────────────┼──────────────┐
                         ▼              ▼              ▼
                       GPS Map       Live Status      Alerts
                         │              │              │
                         └──────────────┼──────────────┘
                                        ▼
                                👨‍💻 HUMAN OPERATOR
                                        │
                              Monitor / Command
                                        │
                                        ▼
                                      BOAT

Core idea

ESP32 = real-time control + safety

n8n = automation + integration

AI Agent = intelligent telemetry interpretation

Telegram = operator communication

Google Sheets = historical records

ThingSpeak = IoT visualization

Web Dashboard = centralized monitoring

 

AI RFID Inventory Management System with Predictive Analytics

AI RFID Inventory Management System — Full Project Documentation

Below is a complete project structure for an AI-powered RFID inventory system using ESP32 + RFID + n8n + AI Agent + Telegram voice alerts + Google Sheets + ThingSpeak/cloud dashboard.

1. Project Overview

The system automatically identifies inventory using RFID tags, processes the readings through an ESP32, sends data to n8n, stores inventory records in Google Sheets, visualizes sensor/inventory data on ThingSpeak, and uses an AI Agent to analyze events and generate alerts.

Main functions

  • RFID-based item identification

  • Automatic inventory counting

  • ESP32 IoT gateway

  • Wi-Fi/cloud connectivity

  • n8n workflow automation

  • AI-powered inventory analysis

  • Low-stock prediction

  • Missing/unauthorized-item detection

  • Telegram notifications

  • Telegram voice alerts

  • Google Sheets inventory database

  • ThingSpeak dashboard

  • Web-based inventory dashboard

  • Automated reports and summaries


2. Overall Architecture

                 ┌──────────────────────┐
                 │      RFID TAGS       │
                 │  Item ID / UID Data  │
                 └──────────┬───────────┘
                            │
                            ▼
                 ┌──────────────────────┐
                 │      RFID RC522      │
                 │    RFID Reader       │
                 └──────────┬───────────┘
                            │ SPI
                            ▼
                 ┌──────────────────────┐
                 │       ESP32          │
                 │ RFID + Wi-Fi + IoT   │
                 └──────────┬───────────┘
                            │ HTTPS / MQTT
                            ▼
                 ┌──────────────────────┐
                 │       n8n            │
                 │ Automation Workflow  │
                 └──────────┬───────────┘
                            │
          ┌─────────────────┼─────────────────┐
          ▼                 ▼                 ▼
 ┌────────────────┐ ┌────────────────┐ ┌────────────────┐
 │ Google Sheets  │ │   AI Agent     │ │   ThingSpeak   │
 │ Inventory DB   │ │ Analysis/Logic │ │ Cloud Dashboard│
 └────────────────┘ └───────┬────────┘ └────────────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │    Telegram     │
                    │ Text + Voice    │
                    │     Alerts      │
                    └─────────────────┘

3. Hardware Required

Component Purpose
ESP32 DevKit Main IoT controller
RC522 RFID reader Reads RFID tags
RFID cards/tags Inventory identification
OLED/LCD Local status display
Buzzer Local alarm
LEDs Status indication
Push button Manual inventory operation
Wi-Fi Internet connection
5V power supply ESP32 power
Jumper wires Connections
Breadboard/PCB Prototype

Optional:

  • ESP32-S3

  • Multiple RFID readers

  • Load cell + HX711

  • DHT22

  • IR sensor

  • GPS

  • Barcode scanner

  • Relay

  • Servo

  • Camera


4. RFID Inventory Concept

Every inventory item receives an RFID tag.

Example:

RFID UID: A3 7B 91 2C

        ↓

Item ID: ITEM-001

        ↓

Product: Arduino ESP32

        ↓

Category: Electronics

        ↓

Quantity: 25

        ↓

Minimum Stock: 5

When the tag is detected, ESP32 sends:

{
  "device_id": "ESP32-001",
  "rfid_uid": "A37B912C",
  "timestamp": "2026-09-28T20:30:00",
  "event": "RFID_DETECTED"
}

5. RC522–ESP32 Wiring

Use the ESP32's VSPI pins.

RC522 ESP32
SDA/SS GPIO 5
SCK GPIO 18
MOSI GPIO 23
MISO GPIO 19
IRQ Not connected
GND GND
RST GPIO 22
3.3V 3.3V

Important: RC522 is a 3.3 V device. Do not power the RC522 from 5 V.


6. Basic Circuit Diagram

                 ESP32
          ┌──────────────────┐
          │                  │
 GPIO 5 ──┤ SS               │
GPIO 18 ──┤ SCK              │
GPIO 23 ──┤ MOSI             │
GPIO 19 ──┤ MISO             │
GPIO 22 ──┤ RST              │
      GND ─┤ GND              │
     3.3V ─┤ 3V3              │
          │                  │
          └──────────────────┘
             │ │ │ │ │
             │ │ │ │ │
             ▼ ▼ ▼ ▼ ▼

          ┌─────────────┐
          │    RC522    │
          │             │
          │ SDA         │
          │ SCK         │
          │ MOSI        │
          │ MISO        │
          │ RST         │
          │ GND         │
          │ 3.3V        │
          └─────────────┘

Optional indicators:

ESP32 GPIO 2 ───► GREEN LED ───► GND
ESP32 GPIO 4 ───► RED LED ─────► GND
ESP32 GPIO 15 ───► Buzzer ─────► GND

Use appropriate current-limiting resistors for LEDs.


7. Software Architecture

ESP32 Firmware
      │
      ├── RFID Driver
      ├── Wi-Fi Manager
      ├── JSON Generator
      ├── HTTP Client
      └── Local Alert
              │
              ▼
          n8n Webhook
              │
              ▼
       Data Validation
              │
              ▼
       Inventory Lookup
              │
       ┌──────┴──────┐
       ▼             ▼
   Known Item     Unknown RFID
       │             │
       ▼             ▼
 Update Stock     Security Alert
       │             │
       └──────┬──────┘
              ▼
          AI Agent
              │
       ┌──────┼────────┐
       ▼      ▼        ▼
    Predict  Analyze  Recommend
       │      │        │
       └──────┼────────┘
              ▼
       Google Sheets
              │
       ┌──────┴───────┐
       ▼              ▼
 ThingSpeak        Telegram
 Dashboard        Notification
                       │
                       ▼
                  Voice Alert

8. ESP32 Arduino Code

Install:

  • ESP32 board package

  • MFRC522 library

  • WiFi library

  • HTTPClient library

  • ArduinoJson library

Example firmware:

#include <WiFi.h>
#include <HTTPClient.h>
#include <SPI.h>
#include <MFRC522.h>
#include <ArduinoJson.h>

#define SS_PIN 5
#define RST_PIN 22

MFRC522 rfid(SS_PIN, RST_PIN);

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";

const char* WEBHOOK_URL =
  "https://YOUR_N8N_SERVER/webhook/rfid-inventory";

#define GREEN_LED 2
#define RED_LED 4
#define BUZZER 15

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

  pinMode(GREEN_LED, OUTPUT);
  pinMode(RED_LED, OUTPUT);
  pinMode(BUZZER, OUTPUT);

  SPI.begin();
  rfid.PCD_Init();

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();
  Serial.println("WiFi connected");
  Serial.println(WiFi.localIP());
}

String getUID() {

  String uid = "";

  for (byte i = 0; i < rfid.uid.size; i++) {

    if (rfid.uid.uidByte[i] < 0x10)
      uid += "0";

    uid += String(
      rfid.uid.uidByte[i],
      HEX
    );
  }

  uid.toUpperCase();

  return uid;
}

void sendRFID(String uid) {

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

  HTTPClient http;

  http.begin(WEBHOOK_URL);

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

  StaticJsonDocument<512> doc;

  doc["device_id"] = "ESP32-001";
  doc["rfid_uid"] = uid;
  doc["event"] = "RFID_DETECTED";
  doc["device_ip"] = WiFi.localIP().toString();

  String payload;

  serializeJson(doc, payload);

  int response =
    http.POST(payload);

  Serial.print("HTTP Response: ");
  Serial.println(response);

  if (response >= 200 && response < 300) {

    digitalWrite(GREEN_LED, HIGH);

    tone(BUZZER, 2000, 100);

    delay(200);

    digitalWrite(GREEN_LED, LOW);

  } else {

    digitalWrite(RED_LED, HIGH);

    tone(BUZZER, 500, 500);

    delay(500);

    digitalWrite(RED_LED, LOW);
  }

  http.end();
}

void loop() {

  if (!rfid.PICC_IsNewCardPresent())
    return;

  if (!rfid.PICC_ReadCardSerial())
    return;

  String uid = getUID();

  Serial.print("RFID: ");
  Serial.println(uid);

  sendRFID(uid);

  rfid.PICC_HaltA();

  delay(1500);
}

9. n8n Automation Workflow

The central automation can be:

Webhook
   │
   ▼
Validate JSON
   │
   ▼
Extract RFID UID
   │
   ▼
Google Sheets Lookup
   │
   ▼
IF Item Exists?
  /       \
YES       NO
 │         │
 ▼         ▼
Update    Security
Stock     Alert
 │         │
 ▼         ▼
AI Agent  Telegram
 │
 ▼
Inventory Analysis
 │
 ├── Low stock?
 ├── Abnormal usage?
 ├── Missing item?
 ├── Reorder required?
 └── Daily summary?
       │
       ▼
 Google Sheets
       │
       ▼
 ThingSpeak
       │
       ▼
 Telegram

10. n8n Nodes

Recommended nodes:

  1. Webhook

  2. Set

  3. Code

  4. Google Sheets

  5. IF

  6. AI Agent

  7. HTTP Request

  8. Telegram

  9. Google Sheets Update

  10. Schedule Trigger

Example:

[Webhook]
     ↓
[Validate RFID]
     ↓
[Google Sheets Lookup]
     ↓
[IF Item Exists]
   ↙       ↘
 YES       NO
  ↓         ↓
[Update] [Telegram]
  ↓
[AI Agent]
  ↓
[Inventory Decision]
  ↓
[Google Sheets]
  ↓
[ThingSpeak]
  ↓
[Telegram]

11. Google Sheets Database

Create a spreadsheet named:

AI_RFID_INVENTORY

Sheet: Inventory

RFID_UID Item_ID Product Category Quantity Min_Stock Location Status
A37B912C ITEM001 ESP32 Electronics 25 5 Rack-A1 OK
B52190AA ITEM002 RFID Card Electronics 100 20 Rack-A2 OK

Sheet: Transactions

Timestamp RFID Item Event Quantity Device
2026-09-28 20:00 A37B912C ESP32 IN 1 ESP32-001

Sheet: Alerts

Time Type RFID Message Severity
20:05 LOW_STOCK A37B912C ESP32 stock low HIGH

12 . AI Agent

The AI Agent should not directly control physical hardware without validation. Instead, it analyzes structured inventory data and returns a controlled decision .

Example AI input:

{
  "item": "ESP32",
  "quantity": 4,
  "minimum_stock": 5,
  "daily_usage": 2,
  "last_7_days_usage": 14
}

AI output:

{
  "status": "LOW_STOCK",
  "risk": "HIGH",
  "estimated_days_remaining": 2,
  "recommendation": "Create replenishment request"
}

13 . AI Agent Prompt

You are an Inventory Management AI Agent.

Your task is to analyze RFID inventory events.

Available information:

- RFID UID
- Item ID
- Product name
- Current quantity
- Minimum stock
- Historical usage
- Recent transactions
- Location

Rules:

1. Identify low-stock conditions.
2. Identify unusual inventory activity.
3. Calculate approximate inventory consumption.
4. Estimate remaining inventory duration when enough data exists.
5. Identify unknown RFID tags.
6. Recommend replenishment when appropriate.
7. Never invent missing inventory information.
8. Return structured JSON.
9. Do not directly execute dangerous physical actions.

Return:

{
  "status": "",
  "risk": "",
  "analysis": "",
  "recommended_action": "",
  "alert_required": true/false
}

14. Predictive Analytics

The system becomes more useful when historical RFID transactions are analyzed.

For example:

Monday     10 units
Tuesday     8 units
Wednesday  12 units
Thursday   11 units
Friday     15 units

Average consumption:

Average =
(10 + 8 + 12 + 11 + 15) / 5

= 11.2 units/day

If stock is 45:

Estimated stock life =
45 / 11.2

≈ 4 days

The system can therefore generate:

⚠ INVENTORY FORECAST

Product: ESP32
Current stock: 45
Average daily usage: 11.2
Estimated remaining days: 4
Minimum stock: 20

Recommendation:
Prepare replenishment.

15. Telegram Alerts

n8n can send a Telegram message such as:

🚨 INVENTORY ALERT

Product: ESP32 DevKit
RFID: A37B912C

Current Stock: 4
Minimum Stock: 5

Average Usage: 2/day
Estimated Remaining: 2 days

Risk: HIGH

Recommended Action:
Replenishment required.

16. Telegram Voice Alert

The workflow can be:

Inventory Event
      ↓
AI Agent
      ↓
Alert Required?
      ↓
Generate Message
      ↓
Text-to-Speech
      ↓
Audio File
      ↓
Telegram Send Audio

Example spoken notification:

“Inventory alert. ESP32 stock has fallen below the minimum level. Current stock is four units. Replenishment is recommended.”


17. Unknown RFID Detection

This is an important security feature.

RFID detected
      ↓
Google Sheets lookup
      ↓
Is UID registered?
    /       \
  YES       NO
   │         │
   ▼         ▼
Normal     Security
operation   alert
             │
             ▼
          Telegram

Example:

🚨 UNKNOWN RFID

UID: 93A1F27B
Device: ESP32-001
Time: 20:15:31
Location: Warehouse A

Action:
Verify inventory item.

18. ThingSpeak Integration

ThingSpeak can provide IoT visualization.

Possible fields:

Field 1 = Total Inventory
Field 2 = RFID Events
Field 3 = Low Stock Items
Field 4 = Unknown Tags
Field 5 = Daily Consumption
Field 6 = Inventory Risk

Example:

             THINGSPEAK
        ┌─────────────────────┐
        │ Total Items: 1,245  │
        │ RFID Events:  328   │
        │ Low Stock:      7   │
        │ Unknown:         2   │
        └─────────────────────┘

19. Web Dashboard

A simple webpage can communicate with the backend:

┌──────────────────────────────────────────────┐
│       AI RFID INVENTORY DASHBOARD            │
├──────────────────────────────────────────────┤
│                                              │
│ Total Items       RFID Events     Low Stock  │
│     1,245             328             7      │
│                                              │
├──────────────────────────────────────────────┤
│ Inventory Status                              │
│                                              │
│ ESP32          ████████████████  45          │
│ RFID Cards     ██████████████████ 100        │
│ Sensors        ████████            18        │
│                                              │
├──────────────────────────────────────────────┤
│ AI FORECAST                                  │
│                                              │
│ ESP32: 4 days remaining                      │
│ Sensors: 8 days remaining                    │
│                                              │
├──────────────────────────────────────────────┤
│ Recent Alerts                                │
│                                              │
│ 🔴 ESP32 low stock                           │
│ 🟡 Unknown RFID detected                     │
│ 🟢 Inventory updated                         │
└──────────────────────────────────────────────┘

20. Example HTML Dashboard

<!DOCTYPE html>
<html>
<head>
  <title>AI RFID Inventory</title>

  <style>
    body {
      font-family: Arial;
      background: #101820;
      color: white;
      margin: 30px;
    }

    .dashboard {
      display: grid;
      grid-template-columns:
        repeat(3, 1fr);
      gap: 20px;
    }

    .card {
      background: #1d2a35;
      padding: 25px;
      border-radius: 15px;
    }

    .number {
      font-size: 35px;
      color: #00e5ff;
    }

    .alert {
      color: #ff5252;
    }
  </style>
</head>

<body>

<h1>AI RFID Inventory Dashboard</h1>

<div class="dashboard">

  <div class="card">
    <h3>Total Inventory</h3>
    <div class="number" id="inventory">
      0
    </div>
  </div>

  <div class="card">
    <h3>RFID Events</h3>
    <div class="number" id="events">
      0
    </div>
  </div>

  <div class="card">
    <h3>Low Stock</h3>
    <div class="number alert" id="lowstock">
      0
    </div>
  </div>

</div>

<script>

async function loadDashboard() {

  const response =
    await fetch(
      "https://YOUR-N8N-SERVER/webhook/dashboard"
    );

  const data =
    await response.json();

  document.getElementById(
    "inventory"
  ).innerText = data.inventory;

  document.getElementById(
    "events"
  ).innerText = data.events;

  document.getElementById(
    "lowstock"
  ).innerText = data.low_stock;
}

loadDashboard();

setInterval(
  loadDashboard,
  30000
);

</script>

</body>
</html>

21. Complete Data Flow

                   RFID TAG
                      │
                      ▼
                ┌───────────┐
                │   RC522   │
                └─────┬─────┘
                      │
                      ▼
                ┌───────────┐
                │   ESP32   │
                └─────┬─────┘
                      │
                Wi-Fi / HTTPS
                      │
                      ▼
                ┌───────────┐
                │    n8n    │
                └─────┬─────┘
                      │
             Validate Event
                      │
                      ▼
              Google Sheets
                      │
                      ▼
                Inventory
                 Lookup
                      │
             ┌────────┴────────┐
             │                 │
          Known              Unknown
             │                 │
             ▼                 ▼
       Update Record       Security Alert
             │
             ▼
          AI Agent
             │
      ┌──────┼───────┐
      │      │       │
      ▼      ▼       ▼
   Forecast Risk  Recommendation
      │      │       │
      └──────┼───────┘
             ▼
       Alert Decision
             │
       ┌─────┴─────┐
       ▼           ▼
   Dashboard    Telegram
                    │
             ┌──────┴──────┐
             ▼             ▼
           Text          Voice
           Alert          Alert

22. n8n Workflow for Low Stock

       RFID Webhook
             │
             ▼
       Read Inventory
             │
             ▼
       Calculate Stock
             │
             ▼
    Quantity < Minimum?
        /          \
      YES           NO
       │             │
       ▼             ▼
 Generate AI       Continue
 Analysis
       │
       ▼
 Generate Alert
       │
       ├──────────────► Google Sheets
       │
       ├──────────────► ThingSpeak
       │
       └──────────────► Telegram
                            │
                            ▼
                       Voice Alert

23. Daily AI Report

Use an n8n Schedule Trigger:

Every day at 8:00 PM
          ↓
Retrieve today's transactions
          ↓
Calculate:
- Items consumed
- Items added
- Low-stock products
- Unknown RFID events
- Average consumption
          ↓
AI Agent
          ↓
Generate summary
          ↓
Telegram

Example:

📊 DAILY INVENTORY REPORT

Total RFID Transactions: 328

Items Added: 85
Items Removed: 71

Low Stock:
• ESP32 – 4 units
• RFID Cards – 12 units

Unknown RFID Events:
2

Highest Consumption:
ESP32

AI Forecast:
ESP32 inventory may reach minimum
stock level within approximately 2 days.

System Status:
Operational

24. Agentic IoT Architecture

The project can be described as Agentic IoT because the AI layer does more than simply display sensor readings.

SENSE
  ↓
RFID + ESP32
  ↓
UNDERSTAND
  ↓
n8n + AI Agent
  ↓
REASON
  ↓
Predict inventory condition
  ↓
DECIDE
  ↓
Generate recommended action
  ↓
ACT
  ↓
Telegram / Dashboard / Database
  ↓
LEARN
  ↓
Historical inventory data

The important distinction is that the AI agent should operate within defined permissions and validation rules rather than being given unrestricted control over the physical system.


25. Recommended Project Folder

AI-RFID-INVENTORY/
│
├── ESP32/
│   ├── rfid_inventory.ino
│   ├── config.h
│   └── README.md
│
├── n8n/
│   ├── rfid_workflow.json
│   ├── alert_workflow.json
│   └── daily_report.json
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── database/
│   ├── inventory.csv
│   └── transactions.csv
│
├── documentation/
│   ├── architecture.md
│   ├── wiring.md
│   └── API.md
│
└── README.md

26. Project Operation — Step by Step

Step 1 — Build hardware

Connect:

ESP32 ↔ RC522
ESP32 ↔ LED
ESP32 ↔ Buzzer

Step 2 — Program ESP32

Install libraries and upload the RFID firmware.

Step 3 — Test RFID

Open Serial Monitor:

RFID Inventory System
WiFi connected
IP: 192.168.1.20

RFID detected:
A37B912C

Step 4 — Create n8n webhook

Example endpoint:

POST /webhook/rfid-inventory

Step 5 — Test webhook

Send:

{
  "device_id": "ESP32-001",
  "rfid_uid": "A37B912C",
  "event": "RFID_DETECTED"
}

Step 6 — Create Google Sheet

Add inventory and transaction tables.

Step 7 — Connect n8n to Google Sheets

Search the RFID UID.

Step 8 — Add AI Agent

Provide historical inventory information to the AI.

Step 9 — Add predictive analysis

Calculate:

Average Daily Consumption
Inventory Remaining
Estimated Days Remaining
Reorder Threshold

Step 10 — Add Telegram

Send text alerts.

Step 11 — Add voice

Convert alert text to speech and send the resulting audio through Telegram.

Step 12 — Add ThingSpeak

Publish inventory statistics.

Step 13 — Create dashboard

Display:

  • Inventory

  • RFID events

  • Low-stock products

  • Unknown RFID tags

  • AI forecast

  • Alerts

Step 14 — Test complete system

RFID
 ↓
ESP32
 ↓
n8n
 ↓
Google Sheets
 ↓
AI
 ↓
Prediction
 ↓
ThingSpeak
 ↓
Telegram
 ↓
Voice Alert

27. Example Final Demonstration

Place an RFID-tag ged ESP32 box near the RC522.

The reader detects:

A37B912C

ESP32 sends the event to n8n.

n8n finds:

Product: ESP32
Current quantity: 5
Minimum quantity: 5
Daily consumption: 2

AI determines that inventory is approaching its configured threshold.

The system updates:

Google Sheets
      +
ThingSpeak
      +
Dashboard

Telegram receives:

⚠️ INVENTORY WARNING

ESP32 stock: 5
Minimum: 5
Usage: 2/day

Inventory has reached
the configured minimum level.

Then the voice notification can say:

“Inventory warning. ESP32 stock has reached
the configured minimum level. Replenishment
should be reviewed.”

This gives you a complete RFID → ESP32 → n8n → AI → predictive analytics → Google Sheets → ThingSpeak → Telegram text/voice alert → web dashboard architecture suitable for a final-year project, IoT demonstration, or prototype deployment.

 

AI RFID Inventory Management — Mind Map

                         ┌──────────────────────────────┐
                         │  AI RFID INVENTORY SYSTEM    │
                         └──────────────┬───────────────┘
                                        │
          ┌─────────────────────────────┼─────────────────────────────┐
          │                             │                             │
          ▼                             ▼                             ▼
   ┌─────────────┐              ┌──────────────┐              ┌──────────────┐
   │   HARDWARE  │              │   SOFTWARE   │              │   AI LAYER   │
   └──────┬──────┘              └──────┬───────┘              └──────┬───────┘
          │                            │                             │
     ┌────┼─────┐                ┌─────┼──────┐               ┌─────┼──────┐
     │    │     │                │     │      │               │     │      │
     ▼    ▼     ▼                ▼     ▼      ▼               ▼     ▼      ▼
   ESP32 RC522 RFID             n8n  Google  ThingSpeak     AI    Forecast Analysis
          Tags                        Sheets
     │
     ├── Wi-Fi
     ├── LED
     ├── Buzzer
     └── OLED/LCD


                    ┌────────────────────────────────┐
                    │       RFID DATA FLOW           │
                    └───────────────┬────────────────┘
                                    │
                                    ▼
                              RFID Tag Read
                                    │
                                    ▼
                               RC522 Reader
                                    │
                                    ▼
                                  ESP32
                                    │
                                    ▼
                              JSON / HTTPS
                                    │
                                    ▼
                                  n8n
                                    │
                        ┌───────────┴───────────┐
                        │                       │
                        ▼                       ▼
                  Known RFID              Unknown RFID
                        │                       │
                        ▼                       ▼
                 Update Inventory        Security Alert
                        │
                        ▼
                    AI Agent
                        │
              ┌─────────┼─────────┐
              │         │         │
              ▼         ▼         ▼
          Stock      Usage      Risk
         Analysis   Analysis   Analysis
              │         │         │
              └─────────┼─────────┘
                        │
                        ▼
                 Predictive Analytics
                        │
              ┌─────────┼──────────┐
              │         │          │
              ▼         ▼          ▼
          Low Stock  Forecast  Reorder
                                    │
                                    ▼
                              Alert System
                                    │
                   ┌────────────────┼────────────────┐
                   │                │                │
                   ▼                ▼                ▼
              Telegram         Voice Alert      Dashboard
                   │
                   ▼
             Human Decision


        ┌───────────────────────────────────────────────┐
        │                 CLOUD LAYER                   │
        └──────────────────────┬────────────────────────┘
                               │
             ┌─────────────────┼─────────────────┐
             │                 │                 │
             ▼                 ▼                 ▼
        Google Sheets      ThingSpeak          n8n
             │                 │                 │
             ▼                 ▼                 ▼
        Inventory DB      IoT Charts       Automation
        Transactions      Statistics       Workflows
        Alert History     Trends           AI Agent


        ┌───────────────────────────────────────────────┐
        │                 USER LAYER                    │
        └──────────────────────┬────────────────────────┘
                               │
             ┌─────────────────┼─────────────────┐
             │                 │                 │
             ▼                 ▼                 ▼
        Web Dashboard       Telegram          Reports
             │                 │                 │
             ▼                 ▼                 ▼
        Live Inventory     Text Alert       Daily Report
        AI Forecast        Voice Alert       AI Summary
        Stock Status       Security Alert    Analytics

Simplified project hierarchy

AI RFID INVENTORY
│
├── 1. Hardware
│   ├── ESP32
│   ├── RC522
│   ├── RFID Tags
│   ├── LED
│   ├── Buzzer
│   └── Display
│
├── 2. IoT Communication
│   ├── Wi-Fi
│   ├── HTTP/HTTPS
│   ├── JSON
│   └── n8n Webhook
│
├── 3. Automation
│   ├── n8n
│   ├── Webhook
│   ├── Conditions
│   ├── Google Sheets
│   └── Telegram
│
├── 4. AI
│   ├── AI Agent
│   ├── Stock Analysis
│   ├── Consumption Analysis
│   ├── Forecasting
│   ├── Risk Detection
│   └── Recommendations
│
├── 5. Cloud
│   ├── Google Sheets
│   ├── ThingSpeak
│   └── n8n
│
├── 6. Notifications
│   ├── Telegram Text
│   ├── Telegram Voice
│   ├── Low Stock
│   └── Unknown RFID
│
└── 7. User Interface
    ├── Web Dashboard
    ├── Inventory Status
    ├── AI Forecast
    ├── Alerts
    └── Reports

 

Project Summary

The proposed project is an AI-powered RFID Inventory Management System combining ESP32, RFID, n8n automation, AI Agent, Google Sheets, ThingSpeak, Telegram, and a web dashboard.

Core workflow

RFID Tag
   ↓
RC522 RFID Reader
   ↓
ESP32
   ↓ Wi-Fi / HTTPS
n8n Automation
   ↓
Inventory Database
   ↓
AI Agent
   ↓
Predictive Analytics
   ├── Low-stock detection
   ├── Consumption analysis
   ├── Inventory forecasting
   ├── Unknown RFID detection
   └── Replenishment recommendation
   ↓
┌──────────────┬──────────────┬──────────────┐
Google Sheets  ThingSpeak     Telegram
Database       Dashboard      Text/Voice
                                  ↓
                             Web Dashboard

Main components

  • ESP32 — reads RFID tags and sends inventory events over Wi-Fi.

  • RC522 — identifies individual inventory items using RFID.

  • n8n — central automation/orchestration layer.

  • AI Agent — analyzes inventory history and generates forecasts/recommendations.

  • Google Sheets — stores inventory, transactions, and alerts.

  • ThingSpeak — provides IoT/cloud visualization.

  • Telegram — delivers real-time text and voice alerts.

  • Web dashboard — displays inventory status, alerts, and AI predictions.

Key features

  1. Automatic RFID-based inventory identification.

  2. Real-time inventory updates.

  3. Low-stock alerts.

  4. Unknown/unauthorized RFID detection.

  5. Historical consumption tracking.

  6. Predictive inventory forecasting.

  7. AI-generated recommendations.

  8. Telegram text notifications.

  9. Telegram voice notifications.

  10. Cloud dashboard and web interface.

  11. Daily AI-generated inventory reports.

  12. Centralized n8n automation.

Hardware

ESP32
RC522 RFID Reader
RFID Tags/Cards
LEDs
Buzzer
OLED/LCD (optional)
Wi-Fi
Power Supply

Software

Arduino IDE
ESP32 Firmware
n8n
Google Sheets
ThingSpeak
Telegram Bot
AI/LLM
HTML/CSS/JavaScript Dashboard

Project outcome

The final system transforms a conventional RFID reader into an agentic IoT inventory platform that can sense inventory, process events, analyze historical data, predict stock conditions, update cloud records, and automatically notify users.