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

 

No comments:

Post a Comment