AI Garbage-Collecting Boat with Autonomous Path Planning
ESP32 + IoT Web Dashboard + n8n + AI Agent + Telegram Voice Alerts + Google Sheets + ThingSpeak
Below is a complete reference architecture and implementation guide for a prototype autonomous floating garbage-collection boat. It is designed so that the boat can navigate and stop safely without depending on the cloud or AI, while n8n and the AI agent provide higher-level intelligence, logging, dashboards, commands, and notifications.
The ESP32 can operate as a Wi-Fi station and can also host an HTTP server/dashboard locally. Espressif Systems
1. Project title
AI-Powered Autonomous Garbage Collection Boat Using ESP32, IoT, n8n Automation, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak
Short title
Agentic AI IoT Garbage Collection Boat
2. Project abstract
The proposed system is a small autonomous surface vehicle designed to collect floating waste from ponds, lakes, canals, reservoirs, and similar water bodies.
The boat uses an ESP32 as its main embedded controller. Sensors such as GPS, ultrasonic distance sensors, compass/IMU, battery-voltage sensing and optional water-quality sensors provide information about the vehicle and its surroundings.
A motorized collection mechanism moves floating waste toward a storage basket.
The navigation system uses:
-
GPS for position
-
heading information for navigation
-
predefined cleaning waypoints
-
local obstacle detection
-
autonomous waypoint following
-
obstacle avoidance
-
return-to-home behavior
-
battery protection
-
emergency stop
An n8n automation server receives telemetry from the ESP32 and connects the boat to cloud services.
An AI agent analyzes the telemetry and can perform higher-level tasks such as:
-
interpreting operator commands putting it on open water, the propulsion, waterproofing, electrical protection, battery system, GPS/heading accuracy, obstacle detection, failsafes, and radio
-
recommending cleaning routes
-
detecting abnormal conditions
-
summarizing a cleaning mission
-
deciding when an operator should be notified
-
generating human-readable alerts
The system stores historical information in Google Sheets and ThingSpeak. ThingSpeak provides channels and REST/MQTT interfaces for IoT data; a channel can contain up to eight fields. MathWorks+1
Telegram provides operator notifications. n8n has a built-in Telegram integration capable of sending messages and audio. n8n Documentation
For voice notifications, a text-to-speech service generates an audio file and n8n sends it to Telegram. Telegram's sendVoice API supports voice messages, including OGG/Opus, MP3 and M4A formats. Telegram
3. Main objectives
The project has six major objectives.
Objective 1 — Autonomous movement
The boat should move from one GPS waypoint to another without continuous human control.
Objective 2 — Garbage collection
A front-mounted conveyor/scoop should collect floating waste.
Objective 3 — Obstacle avoidance
The boat should detect objects in front of it and change direction or stop.
Objective 4 — IoT monitoring
The operator should be able to see:
-
location
-
battery
-
speed
-
heading
-
obstacle distance
-
collection mechanism status
-
operating mode
-
mission status
Objective 5 — AI agent
The AI layer should understand telemetry and operator requests such as:
"Start cleaning zone A."
"Return the boat."
"How much garbage was collected?"
"Why did the boat stop?"
Objective 6 — Automatic notifications
The system should automatically send Telegram alerts for:
-
low battery
-
obstacle detected
-
mission completed
-
communication failure
-
motor fault
-
boat returned home
-
collection basket full
-
emergency stop
4. Overall system architecture
┌───────────────────────────┐
│ OPERATOR │
│ │
│ Telegram / Web Dashboard │
└─────────────┬─────────────┘
│
▼
┌─────────────────────┐
│ n8n │
│ Workflow Automation │
└─────────┬───────────┘
│
┌──────────────┼──────────────┐
│ │ │
▼ ▼ ▼
┌──────────┐ ┌───────────┐ ┌────────────┐
│ AI Agent │ │ Google │ │ ThingSpeak │
│ │ │ Sheets │ │ Dashboard │
└────┬─────┘ └───────────┘ └────────────┘
│
▼
┌────────────┐
│ TTS / Voice│
│ Generation │
└─────┬──────┘
│
▼
┌────────────┐
│ Telegram │
│ Voice Alert│
└────────────┘
Internet / Wi-Fi
│
▼
┌────────────────────┐
│ ESP32 │
│ │
│ Navigation Engine │
│ Safety Controller │
│ Web Server │
└─────────┬──────────┘
│
┌───────────────┼────────────────┐
│ │ │
▼ ▼ ▼
Sensors Motor Driver Collector
│ │ │
▼ ▼ ▼
GPS / IMU / Left + Right Conveyor /
Ultrasonic Propulsion Scoop Motor
5. Important engineering principle
Do not make the AI agent directly responsible for low-level motor control.
The correct architecture is:
AI
│
│ "Clean Zone A"
▼
Mission planner
│
│ validated waypoints
▼
ESP32 navigation controller
│
├── obstacle avoidance
├── emergency stop
├── motor control
├── battery protection
└── return-to-home
Not:
AI → motor PWM
The AI can make mistakes or become temporarily unavailable. The ESP32 must always be capable of stopping the boat.
6. Hardware block diagram
┌───────────────────┐
│ ESP32 │
│ │
│ Wi-Fi │
│ Web Server │
│ Navigation │
└─────────┬─────────┘
│
┌─────────────────────────┼─────────────────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌───────────┐ ┌────────────┐
│ GPS │ │ Compass / │ │ Ultrasonic │
│ NEO-6M │ │ IMU │ │ Sensors │
└────────────┘ └───────────┘ └────────────┘
│ │ │
└─────────────────────────┼─────────────────────┘
│
▼
┌─────────────────┐
│ Navigation │
│ Algorithm │
└───────┬─────────┘
│
┌───────────┴───────────┐
▼ ▼
┌───────────┐ ┌────────────┐
│ Motor │ │ Collection │
│ Driver │ │ Motor │
└─────┬─────┘ └──────┬─────┘
│ │
┌──────┴──────┐ ▼
▼ ▼ Conveyor
Left motor Right motor
7. Recommended hardware
| Component | Qty | Purpose |
|---|---|---|
| ESP32 DevKit | 1 | Main controller |
| GPS NEO-6M / equivalent | 1 | Position |
| QMC5883L/HMC5883L compass | 1 | Heading |
| HC-SR04 / waterproof ultrasonic | 2–3 | Obstacle detection |
| TB6612FNG / suitable motor driver | 1 | Propulsion |
| DC geared motors | 2 | Left/right propulsion |
| Servo or motorized scoop | 1 | Collection mechanism |
| High-current MOSFET driver | 1 | Conveyor motor |
| Li-ion/LiPo battery | 1 | Main power |
| 5 V buck converter | 1 | ESP32/sensors |
| Waterproof enclosure | 1 | Electronics |
| Floating hull | 1 | Boat body |
| Collection basket | 1 | Garbage storage |
| Emergency-stop switch | 1 | Safety |
| Fuse | 1 | Electrical protection |
| LED indicators | 3–4 | Status |
| Buzzer | 1 | Local alarm |
| Voltage divider | 1 | Battery measurement |
Optional advanced sensors
-
water-level sensor
-
turbidity sensor
-
TDS sensor
-
temperature sensor
-
camera
-
load cell for garbage weight
-
current sensor
-
INA219/INA226
-
ESP32-CAM
-
LoRa module
-
LTE module
8. Mechanical design
A catamaran-style hull is recommended because it provides good stability.
FRONT
↓
┌─────────────────┐
│ Garbage Funnel │
│ ↓ │
│ ┌─────┐ │
│ │Scoop│ │
│ └──┬──┘ │
└───────┼─────────┘
│
┌─────────▼─────────┐
│ Collection Basket │
└───────────────────┘
┌───────────┐ ┌───────────┐
│ │ │ │
│ LEFT │ │ RIGHT │
│ FLOAT │ │ FLOAT │
│ │ │ │
└───────────┘ └───────────┘
│ │
Motor L Motor R
REAR
The garbage funnel should guide floating objects toward the conveyor.
9. Electrical power architecture
Do not power the motors directly from the ESP32.
Recommended architecture:
BATTERY
│
MAIN FUSE
│
EMERGENCY STOP
│
┌────────┴─────────┐
│ │
▼ ▼
MOTOR DRIVER DC-DC BUCK
│ │
┌────┴────┐ │
▼ ▼ ▼
Motor L Motor R 5 V / 3.3 V
│
▼
ESP32
│
┌────────────┼───────────┐
▼ ▼ ▼
GPS Sensors Compass
10. Example ESP32 wiring
GPS
GPS NEO-6M ESP32
VCC → 3.3/5 V according to module
GND → GND
TX → GPIO 16
RX → GPIO 17
Ultrasonic
For a traditional HC-SR04, do not feed a 5 V Echo signal directly into a 3.3 V ESP32 GPIO. Use a resistor divider or a 3.3 V-compatible waterproof sensor.
HC-SR04
TRIG → ESP32 GPIO 5
ECHO ── 10kΩ ──┬── GPIO 18
│
20kΩ
│
GND
The exact resistor values can be adjusted to keep the GPIO voltage within the ESP32's allowed range.
11. Motor driver
For a dual-motor differential-drive boat:
ESP32 Motor Driver
───── ────────────
GPIO 25 ───────────────→ Left PWM
GPIO 26 ───────────────→ Left IN1
GPIO 27 ───────────────→ Left IN2
GPIO 32 ───────────────→ Right PWM
GPIO 33 ───────────────→ Right IN1
GPIO 14 ───────────────→ Right IN2
GND ───────────────────→ GND
Battery ───────────────→ Motor Power
Motor L ───────────────→ Motor A
Motor R ───────────────→ Motor B
Use a motor driver rated for the stall current of the motors, not merely their nominal running current.
12. Collection mechanism
One simple mechanism is:
Floating garbage
↓
┌───────┐
│ Funnel│
└───┬───┘
↓
┌───────────┐
│ Conveyor │
│ █ █ █ █ │
└─────┬─────┘
↓
┌────────────────┐
│ Garbage Basket │
└────────────────┘
The ESP32 can control the conveyor using a MOSFET.
ESP32 GPIO
│
220Ω
│
MOSFET Gate
│
MOSFET
│
Conveyor Motor
│
Battery
Add a flyback diode if using a brushed DC motor.
13. Autonomous navigation
The boat uses a combination of:
-
GPS position
-
waypoint navigation
-
heading estimation
-
obstacle detection
-
local avoidance
-
mission state machine
14. Waypoint system
A cleaning mission can be represented as:
Home
│
▼
WP1 ───────────────► WP2
│
▼
WP3 ◄─────────────── WP4
│
▼
WP5 ───────────────► WP6
│
▼
HOME
This is effectively a lawn-mower/sweep pattern.
Example:
struct Waypoint {
double lat;
double lon;
};
Waypoint mission[] = {
{17.450100, 78.380100},
{17.450100, 78.381000},
{17.450700, 78.381000},
{17.450700, 78.380100},
{17.451300, 78.380100},
{17.451300, 78.381000}
};
Replace these coordinates with the actual survey area.
15. Distance calculation
For GPS navigation, calculate distance using the Haversine equation.
┌───────────────┐
│ Current GPS │
│ lat/lon │
└───────┬───────┘
│
▼
Haversine
│
▼
Distance to WP
│
┌──────────┴──────────┐
│ │
> threshold < threshold
│ │
▼ ▼
Continue Next waypoint
Example:
double distanceMeters(
double lat1, double lon1,
double lat2, double lon2) {
const double R = 6371000.0;
double p1 = radians(lat1);
double p2 = radians(lat2);
double dp = radians(lat2 - lat1);
double dl = radians(lon2 - lon1);
double a = sin(dp/2) * sin(dp/2) +
cos(p1) * cos(p2) *
sin(dl/2) * sin(dl/2);
double c = 2 * atan2(sqrt(a), sqrt(1-a));
return R * c;
}
16. Bearing calculation
double bearingDegrees(
double lat1, double lon1,
double lat2, double lon2) {
double p1 = radians(lat1);
double p2 = radians(lat2);
double dl = radians(lon2 - lon1);
double y = sin(dl) * cos(p2);
double x = cos(p1) * sin(p2) -
sin(p1) * cos(p2) * cos(dl);
double brng = degrees(atan2(y, x));
return fmod(brng + 360.0, 360.0);
}
17. Steering algorithm
Calculate:
Target bearing
│
▼
Current heading
│
▼
Heading error
│
┌─────┴─────┐
▼ ▼
positive negative
▼ ▼
turn right turn left
Example:
float normalizeAngle(float angle) {
while (angle > 180) angle -= 360;
while (angle < -180) angle += 360;
return angle;
}
float headingError(float target, float current) {
return normalizeAngle(target - current);
}
Then:
float error = headingError(targetBearing, currentHeading);
int baseSpeed = 150;
int correction = constrain(error * 2.0, -100, 100);
int leftSpeed = baseSpeed + correction;
int rightSpeed = baseSpeed - correction;
This is a basic proportional controller.
18. Obstacle avoidance
Use multiple ultrasonic sensors if possible.
FRONT
↓
[ FRONT SENSOR ]
|
┌───────┴───────┐
│ │
LEFT SENSOR RIGHT SENSOR
│ │
▼ ▼
┌─────────────┐
│ BOAT │
└─────────────┘
Example logic:
Front distance > 2 m
│
▼
Continue
Front distance < 1.5 m
│
▼
STOP
│
▼
Compare left/right
│
┌─────┴─────┐
▼ ▼
Left clear Right clear
▼ ▼
Turn left Turn right
│
▼
Obstacle clear
│
▼
Resume waypoint
Pseudo-code:
if (frontDistance < 150) {
stopBoat();
if (leftDistance > rightDistance) {
turnLeft();
} else {
turnRight();
}
delay(700);
stopBoat();
}
For a real watercraft, use a more robust state machine rather than relying on a single delay.
19. Autonomous state machine
The software should use explicit states.
┌──────────────┐
│ IDLE │
└──────┬───────┘
│ START
▼
┌──────────────┐
│ STARTUP │
└──────┬───────┘
│ GPS OK
▼
┌──────────────┐
│ NAVIGATING │
└──────┬───────┘
│
┌──────────┼───────────┐
│ │ │
▼ ▼ ▼
Obstacle Low battery Mission
│ │ complete
▼ ▼ ▼
AVOIDING HOME HOME
│ │ │
└────┬─────┘ │
▼ ▼
RESUME DOCK
│ │
└────────┬────────┘
▼
IDLE
20. Safety states
The ESP32 should immediately stop propulsion if:
-
emergency stop is pressed
-
GPS becomes invalid for too long
-
battery voltage is below threshold
-
motor controller reports failure
-
communication watchdog expires
-
obstacle is dangerously close
-
water ingress sensor activates
Example:
bool emergencyStop = false;
bool lowBattery = false;
bool gpsFailure = false;
if (emergencyStop || lowBattery || gpsFailure) {
stopBoat();
collectorOff();
}
21. IoT architecture
The ESP32 periodically sends JSON telemetry.
Example:
{
"device_id": "BOAT001",
"mode": "AUTO",
"lat": 17.45012,
"lon": 78.38051,
"speed": 0.72,
"heading": 91.4,
"battery": 74.2,
"front_distance": 3.4,
"left_distance": 5.1,
"right_distance": 4.2,
"collector": true,
"garbage_count": 17,
"mission": "ZONE_A"
}
22. ESP32 → n8n
The ESP32 sends an HTTP POST:
ESP32
│
│ POST /boat-telemetry
▼
n8n Webhook
│
├── Validate
├── Store
├── AI analysis
├── Google Sheets
├── ThingSpeak
└── Telegram
n8n is specifically intended to connect applications/APIs and automate workflows, including AI functionality. n8n Documentation
23. n8n workflow 1 — telemetry
┌──────────────┐
│ Webhook │
│ /telemetry │
└──────┬───────┘
▼
┌──────────────┐
│ Validate JSON│
└──────┬───────┘
▼
┌──────────────┐
│ IF abnormal? │
└───┬──────┬───┘
│NO │YES
│ ▼
│ AI Agent
│ │
│ ▼
│ Alert
│
▼
Google Sheets
│
▼
ThingSpeak
24. n8n validation code
Use a Code node after the webhook:
const d = $json;
if (!d.device_id) {
throw new Error("Missing device_id");
}
if (typeof d.battery !== "number") {
throw new Error("Invalid battery value");
}
if (typeof d.lat !== "number" ||
typeof d.lon !== "number") {
throw new Error("Invalid GPS coordinates");
}
const alert = [];
if (d.battery < 20) {
alert.push("LOW_BATTERY");
}
if (d.front_distance < 1.0) {
alert.push("OBSTACLE");
}
if (d.gps_valid === false) {
alert.push("GPS_FAILURE");
}
return [{
json: {
...d,
alerts: alert,
alert_required: alert.length > 0
}
}];
25. AI Agent architecture
The AI agent should operate at the mission-management layer.
┌──────────────────────┐
│ AI AGENT │
│ │
│ Mission Interpreter │
│ Fault Analyzer │
│ Route Advisor │
│ Report Generator │
└─────────┬────────────┘
│
┌───────────────────┼────────────────────┐
▼ ▼ ▼
Telemetry Tool Mission Tool Alert Tool
│ │ │
▼ ▼ ▼
ESP32 Database Telegram
The agent might receive:
{
"battery": 18,
"front_distance": 0.7,
"speed": 0.2,
"mission_progress": 62,
"garbage_count": 143
}
It could produce:
{
"severity": "HIGH",
"action": "RETURN_HOME",
"reason": "Battery below mission safety threshold",
"operator_message":
"Battery is low. Boat is returning to the launch point."
}
26. AI Agent system prompt
Use a restrictive system instruction similar to:
You are the mission-management AI for an autonomous garbage-collection boat.
You do NOT directly control motor PWM.
You may:
1. Analyze telemetry.
2. Recommend a mission.
3. Recommend return-to-home.
4. Explain faults.
5. Generate operator alerts.
6. Summarize mission performance.
Safety rules:
- Never disable emergency stop.
- Never command movement when battery is critically low.
- Never override obstacle avoidance.
- Never command propulsion directly.
- Never invent sensor readings.
- Never assume GPS is valid if gps_valid is false.
- If uncertain, recommend STOP or RETURN_HOME.
All movement commands must be represented as high-level validated commands.
27. Natural-language commands
The operator can send:
Start cleaning zone A.
n8n:
Telegram
↓
Telegram Trigger
↓
AI Agent
↓
Command parser
↓
Safety validator
↓
ESP32
Example AI output:
{
"command": "START_MISSION",
"mission": "ZONE_A",
"speed_limit": 0.6
}
28. Do not allow arbitrary AI commands
Avoid:
{
"left_pwm": 243,
"right_pwm": 87
}
Instead use:
{
"command": "START_MISSION",
"mission": "ZONE_A"
}
or:
{
"command": "RETURN_HOME"
}
The ESP32 decides how to translate the high-level command into motor control.
29. Telegram conversation flow
Operator
Operator:
Start cleaning Zone A.
Telegram → n8n
Telegram Trigger
↓
AI Agent
↓
Safety Validator
↓
ESP32
Boat
ESP32:
Mission accepted.
GPS locked.
Starting autonomous cleaning.
Telegram
🤖 Boat:
Zone A cleaning started.
Battery: 94%
GPS: Locked
Obstacle distance: 5.2 m
Mode: AUTONOMOUS
30. Example emergency conversation
Boat → n8n:
Battery = 17%
Distance = 0.8m
Mission = Zone A
↓
AI Agent:
Battery low.
Recommend RETURN_HOME.
↓
Telegram:
🚨 WARNING
Battery is low.
The boat is returning to the home position.
Battery: 17%
Then a voice notification is generated:
"Warning. The garbage collection boat has low battery
and is returning to the home position."
OpenAI's current speech endpoint can generate audio from text and supports several output formats including MP3 and Opus. OpenAI Platform
31. Telegram voice architecture
AI Agent
│
▼
Alert text
│
▼
Text-to-Speech
│
▼
MP3/Opus
│
▼
Telegram Send Voice
│
▼
Operator phone
Telegram's Bot API exposes sendVoice; for voice messages it supports OGG/Opus and also MP3/M4A. Telegram
n8n's Telegram integration includes message and audio operations. n8n Documentation
32. Google Sheets logging
Create a spreadsheet:
Sheet: BoatTelemetry
| Timestamp | Device | Lat | Lon | Battery | Speed | Heading | Obstacle | Mode | Garbage |
|---|
Example:
2026-10-07 15:10:21
BOAT001
17.45012
78.38051
82
0.72
91
3.4
AUTO
17
Google Sheets provides an API operation for appending values to the next row of a logical table. Google Developers+1
33. Google Sheets n8n workflow
ESP32
│
▼
Webhook
│
▼
Set / Code
│
▼
Google Sheets
│
▼
Append Row
Recommended columns:
timestamp
device_id
latitude
longitude
battery
speed
heading
front_distance
left_distance
right_distance
collector_status
garbage_count
mission
mode
alert
34. ThingSpeak dashboard
Create a ThingSpeak channel:
Channel:
AI Garbage Boat 001
Recommended fields:
Field 1 = Battery
Field 2 = Speed
Field 3 = Heading
Field 4 = Front Distance
Field 5 = Garbage Count
Field 6 = Latitude
Field 7 = Longitude
Field 8 = Mission Progress
ThingSpeak accepts channel updates through its REST API. MathWorks
For example:
POST https://api.thingspeak.com/update.json
with:
api_key=YOUR_WRITE_KEY
field1=82
field2=0.72
field3=91
field4=3.4
field5=17
field6=17.45012
field7=78.38051
field8=62
ThingSpeak documents a free-license update interval of 15 seconds, while paid options can support faster updates; design the cloud telemetry interval accordingly. MathWorks
35. ThingSpeak architecture
ESP32
│
▼
n8n
┌────┴─────┐
▼ ▼
Google Sheets ThingSpeak
│
▼
Charts / Data
This is preferable to sending every high-frequency control-loop measurement to the cloud.
For example:
Motor control: 20–50 Hz local
Sensor processing: 5–20 Hz local
ESP32 telemetry: 1–2 Hz
ThingSpeak: ≥15 s for free plan
Google Sheets: 10–60 s
AI analysis: event-driven
36. IoT webpage
The ESP32 can host a local web interface.
Example:
┌───────────────────────────────────────────┐
│ 🚤 AI GARBAGE BOAT │
├───────────────────────────────────────────┤
│ │
│ STATUS 🟢 AUTONOMOUS │
│ │
│ Battery 82 % │
│ Speed 0.72 m/s │
│ Heading 91° │
│ Front 3.4 m │
│ Garbage 17 items │
│ │
│ Mission ZONE A │
│ Progress ████████████░░ 62% │
│ │
├───────────────────────────────────────────┤
│ │
│ [ START ] [ STOP ] [ RETURN HOME ] │
│ │
└───────────────────────────────────────────┘
37. Dashboard HTML
A basic dashboard can be served from the ESP32:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>AI Garbage Boat</title>
<style>
body {
font-family: Arial;
background:#07111f;
color:white;
margin:0;
padding:20px;
}
.card {
background:#12243a;
padding:20px;
margin:10px 0;
border-radius:15px;
}
.value {
font-size:28px;
color:#00e5ff;
}
button {
padding:15px 20px;
margin:5px;
border:0;
border-radius:10px;
font-weight:bold;
}
.start {
background:#00c853;
}
.stop {
background:#ff1744;
color:white;
}
.home {
background:#ffab00;
}
</style>
</head>
<body>
<h1>🚤 AI Garbage Boat</h1>
<div class="card">
Status:
<div id="mode" class="value">Loading...</div>
</div>
<div class="card">
Battery:
<div id="battery" class="value">--</div>
</div>
<div class="card">
Speed:
<div id="speed" class="value">--</div>
</div>
<div class="card">
Obstacle:
<div id="obstacle" class="value">--</div>
</div>
<div class="card">
Garbage:
<div id="garbage" class="value">--</div>
</div>
<button class="start"
onclick="command('START')">
START
</button>
<button class="stop"
onclick="command('STOP')">
STOP
</button>
<button class="home"
onclick="command('HOME')">
RETURN HOME
</button>
<script>
async function update() {
const r = await fetch('/api/status');
const d = await r.json();
document.getElementById('mode').innerText =
d.mode;
document.getElementById('battery').innerText =
d.battery + "%";
document.getElementById('speed').innerText =
d.speed + " m/s";
document.getElementById('obstacle').innerText =
d.front_distance + " m";
document.getElementById('garbage').innerText =
d.garbage_count;
}
async function command(c) {
await fetch('/api/command', {
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
command:c
})
});
update();
}
setInterval(update,2000);
update();
</script>
</body>
</html>
38. ESP32 software architecture
The firmware should be divided into modules:
main.cpp
│
├── WiFi Manager
├── Web Server
├── GPS Manager
├── Sensor Manager
├── Navigation Manager
├── Obstacle Manager
├── Motor Controller
├── Collector Controller
├── Battery Manager
├── Mission Manager
├── Telemetry Manager
└── Safety Manager
39. ESP32 firmware example
Below is a reference starting point rather than a finished production marine controller.
Libraries:
WiFi
WebServer
HTTPClient
TinyGPSPlus
ArduinoJson
ESP32Servo
Example:
#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <TinyGPSPlus.h>
#include <ESP32Servo.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* N8N_URL =
"https://YOUR-N8N-DOMAIN/webhook/boat-telemetry";
WebServer server(80);
TinyGPSPlus gps;
HardwareSerial GPSSerial(1);
// Motor pins
#define L_PWM 25
#define L_IN1 26
#define L_IN2 27
#define R_PWM 32
#define R_IN1 33
#define R_IN2 14
// Ultrasonic
#define FRONT_TRIG 5
#define FRONT_ECHO 18
#define LEFT_TRIG 19
#define LEFT_ECHO 21
#define RIGHT_TRIG 22
#define RIGHT_ECHO 23
// Collector
#define COLLECTOR_PIN 13
String mode = "IDLE";
float batteryVoltage = 0;
float frontDistance = 99;
float leftDistance = 99;
float rightDistance = 99;
int garbageCount = 0;
unsigned long lastTelemetry = 0;
void setup() {
Serial.begin(115200);
GPSSerial.begin(
9600,
SERIAL_8N1,
16,
17
);
pinMode(L_IN1, OUTPUT);
pinMode(L_IN2, OUTPUT);
pinMode(R_IN1, OUTPUT);
pinMode(R_IN2, OUTPUT);
pinMode(L_PWM, OUTPUT);
pinMode(R_PWM, OUTPUT);
pinMode(COLLECTOR_PIN, OUTPUT);
pinMode(FRONT_TRIG, OUTPUT);
pinMode(FRONT_ECHO, INPUT);
pinMode(LEFT_TRIG, OUTPUT);
pinMode(LEFT_ECHO, INPUT);
pinMode(RIGHT_TRIG, OUTPUT);
pinMode(RIGHT_ECHO, INPUT);
stopBoat();
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println(WiFi.localIP());
server.on("/api/status", HTTP_GET, []() {
StaticJsonDocument<512> doc;
doc["mode"] = mode;
doc["battery"] = batteryVoltage;
doc["front_distance"] = frontDistance;
doc["left_distance"] = leftDistance;
doc["right_distance"] = rightDistance;
doc["garbage_count"] = garbageCount;
String output;
serializeJson(doc, output);
server.send(
200,
"application/json",
output
);
});
server.on("/api/command", HTTP_POST, []() {
String body = server.arg("plain");
StaticJsonDocument<256> doc;
if (deserializeJson(doc, body)) {
server.send(
400,
"text/plain",
"Invalid JSON"
);
return;
}
String command = doc["command"];
if (command == "START") {
mode = "AUTO";
}
if (command == "STOP") {
mode = "STOP";
stopBoat();
}
if (command == "HOME") {
mode = "RETURN_HOME";
}
server.send(
200,
"text/plain",
"OK"
);
});
server.begin();
}
40. Ultrasonic function
float readDistance(
int trigPin,
int echoPin) {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
unsigned long duration =
pulseIn(echoPin, HIGH, 30000);
if (duration == 0)
return 99;
return duration * 0.0343 / 2.0;
}
Update sensors:
void updateSensors() {
frontDistance =
readDistance(
FRONT_TRIG,
FRONT_ECHO
);
leftDistance =
readDistance(
LEFT_TRIG,
LEFT_ECHO
);
rightDistance =
readDistance(
RIGHT_TRIG,
RIGHT_ECHO
);
}
41. Motor control
void motorLeft(int speed) {
speed = constrain(speed, -255, 255);
if (speed > 0) {
digitalWrite(L_IN1, HIGH);
digitalWrite(L_IN2, LOW);
}
else if (speed < 0) {
digitalWrite(L_IN1, LOW);
digitalWrite(L_IN2, HIGH);
}
else {
digitalWrite(L_IN1, LOW);
digitalWrite(L_IN2, LOW);
}
analogWrite(
L_PWM,
abs(speed)
);
}
void motorRight(int speed) {
speed = constrain(speed, -255, 255);
if (speed > 0) {
digitalWrite(R_IN1, HIGH);
digitalWrite(R_IN2, LOW);
}
else if (speed < 0) {
digitalWrite(R_IN1, LOW);
digitalWrite(R_IN2, HIGH);
}
else {
digitalWrite(R_IN1, LOW);
digitalWrite(R_IN2, LOW);
}
analogWrite(
R_PWM,
abs(speed)
);
}
For a particular Arduino-ESP32 core version, use the corresponding LEDC/PWM API if analogWrite() isn't supported by your installed core.
42. Stop function
void stopBoat() {
motorLeft(0);
motorRight(0);
digitalWrite(
COLLECTOR_PIN,
LOW
);
}
43. Obstacle avoidance
void obstacleAvoidance() {
if (frontDistance < 1.0) {
stopBoat();
delay(300);
if (leftDistance > rightDistance) {
motorLeft(-130);
motorRight(130);
} else {
motorLeft(130);
motorRight(-130);
}
delay(700);
stopBoat();
}
}
Again, for the final vehicle, replace fixed timing with measured heading/position-based turning.
44. Main loop
void loop() {
server.handleClient();
while (GPSSerial.available()) {
gps.encode(
GPSSerial.read()
);
}
updateSensors();
if (mode == "STOP") {
stopBoat();
return;
}
if (mode == "AUTO") {
obstacleAvoidance();
// waypoint navigation
// calculate bearing
// calculate heading error
// control motors
}
if (mode == "RETURN_HOME") {
obstacleAvoidance();
// Navigate to HOME coordinate
}
if (millis() -
lastTelemetry > 10000) {
sendTelemetry();
lastTelemetry = millis();
}
}
45. Telemetry function
void sendTelemetry() {
if (WiFi.status() != WL_CONNECTED)
return;
StaticJsonDocument<768> doc;
doc["device_id"] = "BOAT001";
doc["mode"] = mode;
if (gps.location.isValid()) {
doc["lat"] =
gps.location.lat();
doc["lon"] =
gps.location.lng();
} else {
doc["gps_valid"] = false;
}
doc["speed"] =
gps.speed.mps();
doc["battery"] =
batteryVoltage;
doc["front_distance"] =
frontDistance;
doc["left_distance"] =
leftDistance;
doc["right_distance"] =
rightDistance;
doc["garbage_count"] =
garbageCount;
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 HTTP: "
);
Serial.println(response);
http.end();
}
46. Battery measurement
Suppose your battery is higher than 3.3 V.
Use a voltage divider:
Battery +
│
│
R1
│
├────────── ESP32 ADC
│
R2
│
GND
Formula:
Vbattery = Vadc × (R1 + R2) / R2
Example:
#define BATTERY_ADC 34
float readBattery() {
int raw =
analogRead(BATTERY_ADC);
float voltage =
raw * 3.3 / 4095.0;
return voltage *
((100.0 + 33.0) / 33.0);
}
Choose resistor values based on the actual maximum battery voltage and ensure the ADC pin never exceeds its allowed input range.
47. Garbage detection
A simple collection system can use a sensor:
Garbage enters
│
▼
IR / ToF sensor
│
▼
Object detected
│
▼
garbageCount++
Example:
if (objectDetected) {
garbageCount++;
collectorOn();
}
For better results, use a load cell under the basket.
Then the system can report:
Garbage mass = 4.8 kg
instead of simply:
Garbage count = 143
48. Complete n8n architecture
I recommend creating several separate workflows rather than one giant workflow.
Workflow A — Telemetry
Webhook
↓
Validate
↓
Google Sheets
↓
ThingSpeak
↓
IF Alert
↓
AI Analyzer
Workflow B — Telegram commands
Telegram Trigger
↓
Speech-to-text (if voice)
↓
AI Agent
↓
Command Validator
↓
HTTP Request
↓
ESP32
↓
Telegram confirmation
Workflow C — Emergency alerts
Telemetry
↓
IF
┌──┴──────────┐
│ │
Normal Alarm
│
▼
AI Summary
│
┌────┴────┐
▼ ▼
Telegram TTS
│
▼
Telegram Voice
49. Voice-command workflow
This gives you two-way voice AI.
Operator
│
│ Voice message
▼
Telegram
│
▼
n8n
│
▼
Speech-to-text
│
▼
AI Agent
│
▼
Command
│
▼
Safety validator
│
▼
ESP32
For example:
"Return the boat to the starting point."
becomes:
{
"command": "RETURN_HOME"
}
50. AI-generated response
The AI can respond:
The boat has received the return-home command.
Current battery: 63%
Current distance from home: 148 m
Obstacle distance: 4.1 m
Return-home navigation started.
Then optionally generate a voice message.
51. n8n command validation
A Code node should whitelist commands:
const allowed = [
"START_MISSION",
"STOP",
"RETURN_HOME",
"PAUSE",
"RESUME"
];
const command = $json.command;
if (!allowed.includes(command)) {
throw new Error(
"Unauthorized command"
);
}
return [{
json: {
command
}
}];
This is an important security boundary.
52. ESP32 command API
Example:
POST /api/command
Payload:
{
"command": "RETURN_HOME"
}
ESP32 should accept only known commands.
if (command == "STOP") {
mode = "STOP";
}
else if (command == "RETURN_HOME") {
mode = "RETURN_HOME";
}
else if (command == "START_MISSION") {
mode = "AUTO";
}
else {
// reject
}
53. AI route planning
For a more advanced version, define a cleaning polygon:
P1 ───────────── P2
│ │
│ CLEANING │
│ AREA │
│ │
P4 ───────────── P3
The AI can receive:
{
"mission": "clean",
"area": "zone_A",
"battery": 82,
"boat_position": {
"lat": 17.4502,
"lon": 78.3804
}
}
and return:
{
"mission": "ZONE_A",
"waypoints": [
{
"lat": 17.4501,
"lon": 78.3801
},
{
"lat": 17.4501,
"lon": 78.3810
},
{
"lat": 17.4507,
"lon": 78.3810
},
{
"lat": 17.4507,
"lon": 78.3801
}
]
}
But the ESP32 must validate the route before accepting it.
54. Route validation
Reject a mission if:
Waypoint outside permitted area
↓
REJECT
Too many waypoints
↓
REJECT
Battery insufficient
↓
REJECT
GPS invalid
↓
REJECT
Example:
bool validWaypoint(
double lat,
double lon) {
if (lat < MIN_LAT ||
lat > MAX_LAT)
return false;
if (lon < MIN_LON ||
lon > MAX_LON)
return false;
return true;
}
55. Full data flow
┌────────────────┐
│ Floating Waste │
└───────┬────────┘
▼
Collection
mechanism
│
▼
Garbage basket
│
│
GPS ───────────┐ │
IMU ───────────┤ │
Ultrasonic ────┤ │
Battery ───────┤ │
▼ ▼
┌──────────────┐
│ ESP32 │
│ │
│ Navigation │
│ Safety │
│ Motor Ctrl │
└──────┬───────┘
│
Wi-Fi
│
▼
┌───────────┐
│ n8n │
└─────┬─────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
AI Agent Google Sheets ThingSpeak
│
▼
Decision
│
├───────────────┐
▼ ▼
Telegram ESP32
│
▼
Voice Alert
56. Failure scenarios
Wi-Fi failure
Wi-Fi lost
↓
ESP32 continues autonomous navigation
↓
Cloud unavailable
↓
Watchdog timer
↓
If prolonged failure:
RETURN HOME
AI failure
AI unavailable
↓
ESP32 continues current safe mission
↓
No new AI commands accepted
↓
Existing safety system remains active
GPS failure
GPS invalid
↓
STOP / safe mode
↓
Try GPS recovery
↓
If recovery fails
↓
RETURN / operator intervention
Low battery
Battery < 25%
↓
Warning
↓
Battery < 20%
↓
Stop collecting
↓
Return home
↓
Dock
57. Recommended battery policy
Example:
100–30% Normal
30–25% Warning
25–20% Reduce speed
20–15% Stop collection + return home
<15% Emergency return/stop
The exact values depend on the battery chemistry, motor current, hull, water conditions and measured endurance.
Do not blindly copy these thresholds into a real battery system.
58. Emergency stop
Physical emergency stop:
Battery
│
▼
[FUSE]
│
▼
[E-STOP]
│
├──────── Motor Driver
│
└──────── DC/DC → ESP32
For a prototype, at minimum the emergency-stop circuit should remove motor power. Software STOP should also command zero propulsion.
59. Communication security
Never expose:
/api/command
to the public Internet without authentication.
Use:
ESP32
↓
Authenticated HTTPS/API gateway
↓
n8n
or restrict ESP32 access to the local network/VPN.
Protect:
-
Wi-Fi password
-
n8n credentials
-
Telegram bot token
-
ThingSpeak API key
-
AI API key
-
Google credentials
ThingSpeak uses separate channel-level API keys for channel access. MathWorks
60. Project directory structure
A good final project can be organized as:
AI-Garbage-Boat/
│
├── firmware/
│ ├── boat_controller.ino
│ ├── navigation.cpp
│ ├── navigation.h
│ ├── motors.cpp
│ ├── motors.h
│ ├── sensors.cpp
│ ├── sensors.h
│ ├── telemetry.cpp
│ ├── telemetry.h
│ └── dashboard.html
│
├── n8n/
│ ├── telemetry-workflow.json
│ ├── telegram-workflow.json
│ ├── emergency-workflow.json
│ └── ai-agent-prompt.txt
│
├── hardware/
│ ├── wiring-diagram.png
│ ├── schematic.png
│ └── pcb/
│
├── docs/
│ ├── project-report.md
│ ├── installation.md
│ ├── testing.md
│ └── troubleshooting.md
│
└── README.md
61. Installation sequence
Step 1 — Build the hull
Install:
-
left motor
-
right motor
-
collection mechanism
-
basket
-
electronics enclosure
Step 2 — Install electronics
Mount:
ESP32
GPS
Compass
Ultrasonic sensors
Motor driver
MOSFET
Battery
Buck converter
Emergency stop
Keep the GPS and compass away from high-current motor wiring as much as practical.
Step 3 — Test motors manually
Before adding autonomous navigation:
START
STOP
FORWARD
REVERSE
LEFT
RIGHT
Test each motor separately.
Step 4 — Test sensors
Verify:
GPS latitude
GPS longitude
GPS fix
Speed
Heading
Front distance
Left distance
Right distance
Battery
Step 5 — Test web server
Connect your phone/laptop to the same Wi-Fi.
Open:
http://ESP32_IP_ADDRESS/
Verify dashboard.
Step 6 — Test n8n webhook
Send:
{
"device_id": "BOAT001",
"battery": 82,
"lat": 17.4501,
"lon": 78.3805,
"front_distance": 4.2
}
Verify n8n receives it.
Step 7 — Test Google Sheets
Verify every telemetry record becomes a new row.
Step 8 — Test ThingSpeak
Verify the eight configured fields.
Step 9 — Test Telegram
Send:
/test
and verify:
Boat online.
Step 10 — Test voice alert
Generate:
Boat battery is low. Returning home.
and send it as a Telegram voice message.
Step 11 — Test autonomous navigation without garbage
Use an empty water area.
Set:
Speed = low
Collector = OFF
Test waypoint navigation.
Step 12 — Test obstacle avoidance
Place a floating test object in front of the boat.
Expected:
Obstacle
↓
Stop
↓
Turn
↓
Clear obstacle
↓
Resume route
62. Testing matrix
| Test | Expected result |
|---|---|
| GPS unavailable | Boat does not start autonomous mission |
| Wi-Fi unavailable | Local navigation remains safe |
| n8n unavailable | ESP32 continues local safety logic |
| AI unavailable | No unsafe motor command |
| Front obstacle | Boat stops/avoids |
| Low battery | Return-home |
| Emergency stop | Motors stop |
| Telegram unavailable | Boat continues safely |
| ThingSpeak unavailable | Boat continues safely |
| Google Sheets unavailable | Boat continues safely |
| Mission completed | Boat returns home |
| Invalid AI command | Command rejected |
| Invalid waypoint | Mission rejected |
63. Example mission
Suppose the operator says:
Clean Zone A for 20 minutes.
The complete sequence becomes:
OPERATOR
│
▼
Telegram Voice
│
▼
n8n Trigger
│
▼
Speech-to-text
│
▼
AI Agent
│
▼
Mission interpretation
│
▼
Safety validator
│
▼
START_MISSION ZONE_A
│
▼
ESP32
│
▼
GPS navigation
│
┌───────┴────────┐
│ │
obstacle normal
│ │
▼ ▼
avoidance waypoint
│ │
└───────┬────────┘
▼
Garbage pickup
│
▼
Telemetry
│
▼
n8n
┌────────┼─────────┐
▼ ▼ ▼
Sheets ThingSpeak AI
│
▼
Telegram
64. Example Telegram report
🚤 AI Garbage Boat — Mission Report
Mission: Zone A
Duration: 18 min 42 sec
Distance travelled: 1.83 km
Battery used: 21%
Garbage collected: 4.6 kg
Obstacles detected: 7
Obstacle avoidance events: 5
GPS status: Good
Communication: Good
Mission status: COMPLETED
Boat has returned to the launch point.
65. Example voice alert
"Warning. The garbage collection boat has detected
a low battery condition. Collection has stopped and
the boat is returning to the launch point."
66. Example AI conversation
USER:
How is the boat doing?
AI:
Boat 001 is currently cleaning Zone A.
Battery: 68%
Speed: 0.64 m/s
Garbage collected: 3.8 kg
Mission progress: 57%
Front obstacle distance: 4.6 m
No critical faults detected.
Another:
USER:
Why did the boat stop?
AI:
The boat stopped because its front obstacle sensor
reported an object at 0.72 m. The local safety controller
stopped propulsion and initiated obstacle avoidance.
The AI did not directly control the motors.
67. AI agent tools
For a more advanced n8n implementation, expose tools such as:
get_boat_status()
get_latest_location()
get_battery()
get_mission_status()
get_recent_alerts()
start_mission()
pause_mission()
return_home()
stop_boat()
generate_mission_report()
But write operations should pass through a safety validator.
AI Agent
│
▼
Tool call
│
▼
Safety Validator
│
├── permitted → ESP32
│
└── rejected → AI explanation
68. Suggested n8n workflow nodes
Workflow 1
Webhook
↓
Code - Validate Telemetry
↓
Google Sheets
↓
HTTP Request - ThingSpeak
↓
IF
↓
AI Agent
↓
Telegram
Workflow 2
Telegram Trigger
↓
IF Voice?
├── YES → Download Voice
│ ↓
│ Speech-to-text
│
└── NO
↓
AI Agent
↓
Command Validator
↓
HTTP Request
↓
Telegram Confirmation
Workflow 3
Schedule Trigger
↓
Get Latest Boat Data
↓
AI Agent
↓
Mission Health Check
↓
IF abnormal
↓
TTS
↓
Telegram Voice
69. ThingSpeak API example from n8n
An n8n HTTP Request node can POST:
URL:
https://api.thingspeak.com/update.json
Body:
{
"api_key": "YOUR_WRITE_API_KEY",
"field1": "={{$json.battery}}",
"field2": "={{$json.speed}}",
"field3": "={{$json.heading}}",
"field4": "={{$json.front_distance}}",
"field5": "={{$json.garbage_count}}",
"field6": "={{$json.lat}}",
"field7": "={{$json.lon}}",
"field8": "={{$json.mission_progress}}"
}
ThingSpeak documents both GET and POST methods for updating channel data. MathWorks
70. Google Sheets data model
I recommend three sheets.
Sheet 1 — Telemetry
timestamp
device
lat
lon
speed
heading
battery
obstacle
mode
mission
Sheet 2 — Missions
mission_id
start_time
end_time
zone
distance
battery_used
garbage_mass
status
Sheet 3 — Alerts
timestamp
severity
type
message
battery
location
resolved
This allows you to create historical performance reports.
71. Performance metrics
The project can calculate:
Cleaning efficiency
Cleaning efficiency =
Garbage collected / Mission duration
Energy efficiency
Energy efficiency =
Garbage collected / Battery energy consumed
Route efficiency
Route efficiency =
Useful cleaning distance / Total travelled distance
Obstacle avoidance rate
Successful avoidance /
Total obstacle detections
72. Advanced AI version
For a research-grade version, add a camera.
Camera
↓
Image
↓
AI vision model
↓
Floating object classification
│
┌─┴─────────────┐
▼ ▼
Garbage Non-garbage
│ │
▼ ▼
Collect Avoid
Classes could include:
plastic bottle
plastic bag
foam
can
wood
leaf
animal
person
boat
unknown
Do not use the camera classifier as the only obstacle safety mechanism. A person, animal, boat or floating object should be treated conservatively by the navigation system.
73. Advanced path planner
The next-generation version can use:
GPS
+
Compass
+
Obstacle map
+
Cleaning polygon
+
Garbage locations
+
Battery
to generate a cost map:
WATER MAP
┌───────────────────────────┐
│ X │
│ │
│ X G │
│ │
│ ███ │
│ G │
│ │
│ HOME │
└───────────────────────────┘
Where:
G = detected garbage
X = obstacle
██ = restricted area
Then:
Path planner
↓
Lowest-cost route
↓
Waypoint generator
↓
ESP32
A grid-based A* planner is a reasonable next step for a research prototype.
74. Recommended project phases
Phase 1 — Manual boat
ESP32
+
Motor driver
+
2 motors
Phase 2 — Sensorized boat
Add:
GPS
Ultrasonic
Battery sensing
Phase 3 — Autonomous navigation
Add:
Waypoint following
Heading control
Obstacle avoidance
Return home
Phase 4 — Garbage collection
Add:
Scoop
Conveyor
Basket
Garbage sensor
Phase 5 — IoT
Add:
n8n
ThingSpeak
Google Sheets
Web dashboard
Phase 6 — AI agent
Add:
Natural language commands
Mission planner
Fault analysis
Mission summaries
Phase 7 — Voice
Add:
Telegram
Speech-to-text
Text-to-speech
Voice alerts
Phase 8 — Computer vision
Add:
Camera
Object detection
Garbage classification
Garbage localization
75. Final complete architecture
┌──────────────────────┐
│ OPERATOR │
│ │
│ Web / Telegram │
│ Voice commands │
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ n8n │
│ │
│ Workflow Automation │
└──────────┬───────────┘
│
┌───────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌─────────────┐
│ AI Agent │ │ Google │ │ ThingSpeak │
│ │ │ Sheets │ │ │
└─────┬──────┘ └────────────┘ └─────────────┘
│
┌────┴─────┐
▼ ▼
TTS Commands
│ │
▼ ▼
Telegram ESP32
Voice │
│
┌─────────┼─────────┐
│ │ │
▼ ▼ ▼
GPS Sensors Camera
│ │ │
└─────────┼─────────┘
▼
┌───────────────┐
│ Navigation │
│ Engine │
└───────┬───────┘
│
┌────────┴────────┐
▼ ▼
Propulsion Collector
motors conveyor
│ │
▼ ▼
Autonomous Garbage
boat collection
76. Important distinction: what is actually "AI"?
The strongest version of the project has three intelligence layers:
Layer 1 — Embedded intelligence
ESP32:
Obstacle avoidance
Waypoint following
Battery protection
Emergency stop
Return home
Layer 2 — AI agent
n8n + LLM:
Natural-language commands
Mission interpretation
Fault reasoning
Route recommendations
Mission reports
Layer 3 — AI vision
Optional camera model:
Plastic detection
Garbage classification
Human/animal recognition
Floating-object detection
This gives the project a much stronger "Agentic IoT" architecture than simply putting an API call into an ESP32.
77. Official references
-
ESP32 Arduino Wi-Fi documentation — ESP32 station/AP networking and HTTP-server-related capabilities. Espressif Systems
-
n8n documentation — workflow automation and AI capabilities. n8n Documentation
-
n8n Telegram node — Telegram triggers/actions and audio operations. n8n Documentation
-
ThingSpeak REST API — ThingSpeak REST interface. MathWorks
-
ThingSpeak Write Data API — channel update format and fields. MathWorks
-
Google Sheets API — spreadsheet operations. Google Developers
-
Telegram Bot API — bot and voice-message API. Telegram
-
OpenAI Audio API — text-to-speech and speech-to-text API reference. OpenAI Platform
78. What the finished project demonstrates
This single project can demonstrate all of the following:
✓ Embedded systems
✓ ESP32
✓ Robotics
✓ Autonomous navigation
✓ GPS
✓ Sensors
✓ Motor control
✓ Obstacle avoidance
✓ IoT
✓ Web dashboard
✓ REST APIs
✓ n8n automation
✓ AI agents
✓ Natural-language control
✓ Google Sheets
✓ ThingSpeak
✓ Telegram bots
✓ Voice notifications
✓ Text-to-speech
✓ Data logging
✓ Cloud integration
✓ Safety engineering
✓ Environmental technology
It is therefore suitable as a final-year engineering project, IoT/AI project, robotics demonstration, research prototype, or startup proof-of-concept.
One important implementation note
The code above is intentionally a reference implementation rather than claiming to be a finished autonomous marine product. Before putting it on open water, the propulsion, waterproofing, electrical protection, battery system, GPS/heading accuracy, obstacle detection, failsafes, and radio link need to be tested independently and then together in a controlled area.
If you build it in the sequence manual boat → sensors → autonomous navigation → collector → n8n → AI → Telegram voice, debugging becomes dramatically easier than attempting the entire system at once.
Project Summary
AI-Powered Autonomous Garbage Collection Boat is an IoT and robotics system that automatically detects its position, navigates through a predefined water area, avoids obstacles, collects floating garbage, and reports its status to an operator.
Core architecture
┌──────────────┐
│ Operator │
│ Web/Telegram │
└──────┬───────┘
│
▼
┌──────────────┐
│ n8n │
│ Automation │
└──────┬───────┘
┌────┼─────┐
▼ ▼ ▼
AI Sheets ThingSpeak
│
▼
Telegram
Voice Alert
│
▼
┌───────┐
│ ESP32 │
└───┬───┘
┌─────┼──────────┐
▼ ▼ ▼
GPS Sensors Camera*
│ │ │
└─────┼──────────┘
▼
Navigation Engine
┌───┴────┐
▼ ▼
Motors Garbage
Collector
Main hardware
-
ESP32
-
GPS module
-
Compass/IMU
-
Waterproof ultrasonic/ToF obstacle sensors
-
Two propulsion motors
-
Motor driver
-
Conveyor/scoop mechanism
-
Garbage basket
-
Battery + buck converter
-
Battery-voltage sensor
-
Physical emergency stop
-
Optional camera, load cell and water-quality sensors
Autonomous functions
The ESP32 performs the safety-critical functions locally:
-
GPS waypoint navigation
-
Heading control
-
Obstacle detection
-
Obstacle avoidance
-
Motor control
-
Garbage collection
-
Battery monitoring
-
Return-to-home
-
Emergency stop
-
Communication watchdog
Important: the AI should never directly control motor PWM. The AI issues high-level commands such as START_MISSION, STOP, or RETURN_HOME; the ESP32 validates and executes them.
Cloud/AI functions
n8n acts as the automation layer:
ESP32
↓
n8n Webhook
↓
Validate telemetry
├── Google Sheets
├── ThingSpeak
└── AI Agent
↓
Telegram
↓
Voice Alert
The AI agent can:
-
understand Telegram text/voice commands
-
analyze boat telemetry
-
detect abnormal conditions
-
recommend return-to-home
-
generate mission reports
-
explain why the boat stopped
-
summarize garbage collected
IoT dashboard
The system can display:
-
Battery %
-
GPS location
-
Speed
-
Heading
-
Obstacle distance
-
Garbage collected
-
Mission progress
-
Operating mode
-
Alerts
Example operator command
"Start cleaning Zone A."
Flow:
Telegram Voice
↓
Speech-to-Text
↓
n8n
↓
AI Agent
↓
Safety Validator
↓
ESP32
↓
Autonomous Mission
Example emergency
Battery = 17%
↓
ESP32 detects low battery
↓
Stop garbage collection
↓
RETURN_HOME
↓
n8n
↓
AI-generated alert
↓
Telegram text + voice
Development stages
-
Build and manually control the boat.
-
Add ESP32 and motor control.
-
Add GPS, compass and obstacle sensors.
-
Implement waypoint navigation.
-
Implement obstacle avoidance and return-home.
-
Add garbage conveyor/basket.
-
Add ESP32 web dashboard.
-
Connect n8n.
-
Add Google Sheets and ThingSpeak.
-
Add Telegram notifications.
-
Add AI agent.
-
Add voice commands and voice alerts.
-
Optionally add computer vision for garbage detection.
Final concept
The project combines:
Robotics + ESP32 + Autonomous Navigation + AI Agent + IoT + n8n + Telegram + Voice AI + Google Sheets + ThingSpeak + Environmental Cleanup
The most important design principle is:
ESP32 provides real-time autonomy and safety; n8n/AI provides cloud intelligence, automation, communication and analytics.

No comments:
Post a Comment