Wednesday, 7 October 2026

AI Garbage Collecting Boat with Autonomous Path Planning

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:

  1. GPS position

  2. waypoint navigation

  3. heading estimation

  4. obstacle detection

  5. local avoidance

  6. 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:

  1. GPS waypoint navigation

  2. Heading control

  3. Obstacle detection

  4. Obstacle avoidance

  5. Motor control

  6. Garbage collection

  7. Battery monitoring

  8. Return-to-home

  9. Emergency stop

  10. 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

  1. Build and manually control the boat.

  2. Add ESP32 and motor control.

  3. Add GPS, compass and obstacle sensors.

  4. Implement waypoint navigation.

  5. Implement obstacle avoidance and return-home.

  6. Add garbage conveyor/basket.

  7. Add ESP32 web dashboard.

  8. Connect n8n.

  9. Add Google Sheets and ThingSpeak.

  10. Add Telegram notifications.

  11. Add AI agent.

  12. Add voice commands and voice alerts.

  13. 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.

 

Tuesday, 6 October 2026

AI Floating Solar Tracker with Sun Path Prediction

Absolutely. This can be designed as a complete AI-powered floating solar tracker + IoT + ESP32 + n8n + Telegram + Google Sheets + ThingSpeak system, with an AI agent supervising the system and sending voice alerts.

Below is a complete project architecture and documentation structure you can use for a final-year project, prototype, paper, GitHub repository, or product demonstration.

AI Floating Solar Tracker with Sun -Path Prediction

1. Project Title

AI-Powered Floating Solar Tracker with Sun-Path Prediction, ESP32 IoT, n8n Automation, Telegram Voice Alerts, Google Sheets Logging and ThingSpeak Cloud Dashboard

Short name

AI-FST-IoT

Core technologies

  • ESP32

  • Floating solar panel platform

  • Dual-axis solar tracking

  • GPS / RTC

  • LDR or solar irradiance sensors

  • INA219/INA226 voltage-current sensor

  • Servo motors / geared DC motors

  • Temperature and water-level sensors

  • Wi-Fi

  • MQTT/HTTP

  • n8n

  • AI Agent

  • Telegram Bot

  • Telegram voice notifications

  • Google Sheets

  • ThingSpeak

  • Web dashboard

  • Solar-position/sun-path algorithm

  • Optional weather API

  • Optional machine-learning prediction


2. Project Abstract

The proposed system is an AI-enabled floating photovoltaic tracking system designed to improve solar -energy collection from photovoltaic panels installed on a floating platform.

Unlike a conventional fixed solar panel, the proposed system continuously determines the position of the sun and automatically adjusts the orientation of the floating solar panel using an ESP32-based control system.

The system combines astronomical sun-position prediction, sensor feedback, IoT communication and AI-assisted decision-making.

The ESP32 collects parameters such as:

  • Solar panel voltage

  • Solar panel current

  • Power output

  • Panel temperature

  • Water temperature

  • Water level

  • GPS position

  • Panel orientation

  • Light intensity

  • Motor position

  • Battery voltage

  • System status

The ESP32 transmits the data through Wi-Fi to an automation platform based on n8n.

n8n acts as the central automation layer. It can receive sensor data, store historical information in Google Sheets, update ThingSpeak, evaluate abnormal conditions and communicate with an AI agent .

The AI agent analyzes the incoming information and determines whether the system requires:

  • Normal operation

  • Tracker adjustment

  • Maintenance

  • Low-power operation

  • Over-temperature warning

  • Low-water warning

  • Sensor-failure warning

  • Motor-failure warning

  • Weather-related protection

  • Emergency notification

When an important event occurs, n8n automatically sends a Telegram notification. For critical events, a text-to-speech service can generate a voice alert that is delivered through Telegram.

A web dashboard provides real-time monitoring of the floating solar plant.


3. Main Objective

The main objective is:

To develop an autonomous floating solar tracking system that predicts the sun's position, automatically tracks the sun, monitors photovoltaic performance through IoT, and uses AI-assisted n8n automation to analyze conditions and send intelligent alerts.


4. Specific Objectives

The project has several objectives.

Hardware objectives

  1. Build a floating solar-panel platform.

  2. Install a photovoltaic panel on a motorized tracking mechanism.

  3. Measure voltage and current.

  4. Calculate real-time power.

  5. Measure environmental parameters.

  6. Control the tracking motors using ESP32.

  7. Monitor battery/system voltage.

  8. Detect abnormal mechanical or electrical conditions.

Software objectives

  1. Calculate solar position.

  2. Predict sunrise, solar noon and sunset.

  3. Calculate solar azimuth and elevation.

  4. Control the tracker according to predicted solar position.

  5. Send sensor data to the cloud.

  6. Store historical measurements.

  7. Visualize data.

  8. Automate alerts.

  9. Use an AI agent for intelligent analysis.

  10. Provide Telegram notifications and voice alerts.


5. High-Level Architecture

                    ┌───────────────────────┐
                    │       SUN / SKY       │
                    └───────────┬───────────┘
                                │
                                ▼
                    ┌───────────────────────┐
                    │ Sun Position Algorithm│
                    │ Azimuth + Elevation   │
                    └───────────┬───────────┘
                                │
                                ▼
┌───────────────┐      ┌───────────────────────┐
│ Solar Panel   │─────▶│         ESP32         │
└───────────────┘      │                       │
                       │ Sensor Acquisition    │
┌───────────────┐      │ Tracker Control       │
│ LDR Sensors   │─────▶│ Power Measurement     │
└───────────────┘      │ Wi-Fi / MQTT / HTTP   │
                       └───────────┬───────────┘
                                   │
                                   │ Wi-Fi
                                   ▼
                         ┌──────────────────┐
                         │       n8n        │
                         │ Automation Layer │
                         └────────┬─────────┘
                                  │
             ┌────────────────────┼─────────────────────┐
             │                    │                     │
             ▼                    ▼                     ▼
       ┌───────────┐        ┌─────────────┐       ┌────────────┐
       │ AI Agent  │        │ Google      │       │ ThingSpeak │
       │           │        │ Sheets      │       │ Dashboard  │
       └─────┬─────┘        └─────────────┘       └────────────┘
             │
             ▼
       ┌─────────────┐
       │ Decision /  │
       │ Automation  │
       └──────┬──────┘
              │
              ▼
       ┌──────────────┐
       │   Telegram   │
       │ Text Alert   │
       │ Voice Alert  │
       └──────────────┘

6. Complete System Flow

START
  │
  ▼
ESP32 BOOT
  │
  ▼
Initialize Wi-Fi
  │
  ▼
Initialize sensors
  │
  ▼
Read GPS / RTC
  │
  ▼
Calculate solar position
  │
  ├───────────────┐
  │               │
  ▼               ▼
Azimuth         Elevation
  │               │
  └───────┬───────┘
          ▼
Calculate desired tracker position
          │
          ▼
Read actual tracker position
          │
          ▼
Calculate tracking error
          │
          ▼
Move motors
          │
          ▼
Read electrical parameters
          │
          ▼
Calculate power
          │
          ▼
Read environmental sensors
          │
          ▼
Create JSON packet
          │
          ▼
Send to n8n
          │
          ▼
       n8n Webhook
          │
          ├───────────────┐
          │               │
          ▼               ▼
    Google Sheets     ThingSpeak
          │
          ▼
     AI Agent
          │
          ▼
Analyze system condition
          │
          ├──── NORMAL ────────▶ Continue
          │
          ├──── WARNING ───────▶ Telegram
          │
          └──── CRITICAL ──────▶ Voice Alert
                                      │
                                      ▼
                                   Operator

7. Hardware Architecture

A practical prototype can use the following components.

Component Purpose
ESP32 DevKit Main controller
Solar panel Energy generation
Servo motors / geared motors Solar tracking
Motor driver Motor control
LDR × 4 Light-direction feedback
INA219/INA226 Voltage/current measurement
DS18B20 Temperature
Ultrasonic sensor Water/platform level
MPU6050 Platform tilt detection
GPS module Location/time
RTC DS3231 Accurate timekeeping
Battery Energy storage
Buck converter Regulated supply
Float/platform Floating structure
Limit switches Mechanical safety
Fuse Electrical protection
Waterproof enclosure Electronics protection

8. Floating Platform

The physical platform can be constructed using:

  • HDPE pipes

  • PVC pontoons

  • Foam floats

  • Marine-grade plastic

  • Aluminium frame

  • Stainless-steel brackets

A basic arrangement is:

             SOLAR PANEL
       ┌─────────────────────┐
       │                     │
       │       PV PANEL      │
       │                     │
       └─────────────────────┘
              │       │
              │ TILT  │
              ▼       ▼

        ┌───────────────────┐
        │   ROTATING FRAME  │
        └─────────┬─────────┘
                  │
             ROTATION AXIS
                  │
       ┌──────────┴──────────┐
       │                     │
   ┌───────┐             ┌───────┐
   │FLOAT 1│             │FLOAT 2│
   └───────┘             └───────┘

~~~~~~~~~~~~ WATER SURFACE ~~~~~~~~~~~~

For a prototype, the system can first be built on a small water tank rather than a pond.


9. Solar Tracking Mechanism

A dual-axis tracker is preferable for a demonstration project.

It provides:

  • Azimuth rotation

  • Elevation/tilt adjustment

                  SUN
                   ☀
                  /|
                 / |
                /  |
               /   |
              ▼    |
        ┌──────────────┐
        │  SOLAR PANEL │
        └──────────────┘
              ↕
          ELEVATION
             MOTOR

               │
               │
             ROTARY
              BASE
               ↻
            AZIMUTH

10. Four-LDR Tracking Sensor

Four LDRs can be placed around a small cross-shaped divider.

                 NORTH
                   ↑

              ┌───────┐
              │ LDR-N │
              └───┬───┘
                  │
       LDR-W ─────┼───── LDR-E
                  │
              ┌───┴───┐
              │ LDR-S │
              └───────┘

The ESP32 compares the readings.

For example:

Horizontal error:

Error_H = (LDR_E + LDR_NE + LDR_SE)
        - (LDR_W + LDR_NW + LDR_SW)

Vertical error:

Error_V = (LDR_N + LDR_NE + LDR_NW)
        - (LDR_S + LDR_SE + LDR_SW)

The motor moves until the error approaches zero.


11. Why Use Both AI and Sun-Path Prediction?

This is an important part of the project.

The system should not depend entirely on AI to control the motor.

The deterministic solar-position calculation should provide the primary tracking command.

AI should operate as a higher-level supervisory system.

Conventional control

Sun position
     ↓
Tracker position
     ↓
Motor

Proposed AI system

Sun prediction
       ↓
ESP32 tracker
       ↓
Sensor measurements
       ↓
AI Agent
       ↓
Performance analysis
       ↓
Decision / warning / optimization

This makes the system more reliable.


12. Sun-Path Prediction

The ESP32 can calculate the position of the sun using:

  • Latitude

  • Longitude

  • Date

  • Time

  • Time zone

The result is:

Solar azimuth

Direction of the sun measured around the horizon.

Solar elevation

Angle of the sun above the horizon.

Example:

                  SUN
                   ☀
                  /|
                 / |
                /  | elevation
               /   |
              / θ  |
-------------/-----|------------- horizon
            /
           /
        Azimuth

13. Sun Tracking Algorithm

Simplified logic:

if (sunElevation <= 0) {
    trackerToParkPosition();
}
else {
    targetAzimuth = calculateSolarAzimuth();
    targetElevation = calculateSolarElevation();

    moveAzimuth(targetAzimuth);
    moveElevation(targetElevation);
}

The tracker should also impose mechanical limits:

if (azimuth < AZ_MIN)
    azimuth = AZ_MIN;

if (azimuth > AZ_MAX)
    azimuth = AZ_MAX;

if (elevation < EL_MIN)
    elevation = EL_MIN;

if (elevation > EL_MAX)
    elevation = EL_MAX;

14. Hybrid Tracking Algorithm

A better implementation combines astronomical prediction and LDR feedback.

              Solar Position
                    │
                    ▼
             Target Position
                    │
                    ▼
             Motor Controller
                    │
                    ▼
             Physical Panel
                    │
                    ▼
                LDR Array
                    │
                    ▼
             Actual Position
                    │
                    ▼
              Error Correction
                    │
                    └─────────────┐
                                  │
                                  ▼
                             Motor Driver

The solar algorithm gives the expected location while the LDR array provides real-world correction.

This helps compensate for:

  • Small mounting errors

  • Mechanical backlash

  • Sensor inaccuracies

  • Incorrect initial orientation

  • Small clock errors

  • Structural movement


15. Electrical Measurement

The ESP32 measures:

Voltage = V
Current = I

Power = V × I

Energy can be estimated as:

Energy = ∫ Power dt

For sampled data:

Energy += Power × Δt

For example:

Voltage = 18.2 V
Current = 1.45 A

Power = 18.2 × 1.45
      = 26.39 W

16. ESP32 Data Packet

The ESP32 can send JSON to n8n.

Example:

{
  "device_id": "FLOAT_SOLAR_01",
  "timestamp": "2026-10-07T12:30:00",
  "latitude": 17.3850,
  "longitude": 78.4867,
  "solar_azimuth": 142.5,
  "solar_elevation": 54.2,
  "tracker_azimuth": 141.8,
  "tracker_elevation": 53.9,
  "voltage": 18.2,
  "current": 1.45,
  "power": 26.39,
  "panel_temperature": 42.5,
  "water_temperature": 28.4,
  "water_level": 74,
  "battery_voltage": 12.6,
  "tilt_x": 0.7,
  "tilt_y": -1.2,
  "motor_status": "OK",
  "tracking_status": "TRACKING"
}

17. ESP32 Software Architecture

The ESP32 program should be divided into modules.

ESP32 Firmware
│
├── WiFi Manager
│
├── Sensor Manager
│   ├── LDR
│   ├── INA219
│   ├── DS18B20
│   ├── MPU6050
│   └── Water sensor
│
├── GPS/RTC Manager
│
├── Solar Position Calculator
│
├── Tracker Controller
│
├── Safety Manager
│
├── Energy Calculator
│
├── JSON Generator
│
└── Cloud Communication

18. ESP32 Example Code

Below is a starting firmware architecture.

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

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

const char* N8N_URL =
    "https://YOUR-N8N-SERVER/webhook/solar";

#define LDR_N 34
#define LDR_S 35
#define LDR_E 32
#define LDR_W 33

float panelVoltage = 0;
float panelCurrent = 0;
float panelPower = 0;

float solarAzimuth = 0;
float solarElevation = 0;

float trackerAzimuth = 90;
float trackerElevation = 30;

void setup() {

  Serial.begin(115200);

  pinMode(LDR_N, INPUT);
  pinMode(LDR_S, INPUT);
  pinMode(LDR_E, INPUT);
  pinMode(LDR_W, INPUT);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting to WiFi");

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

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

void loop() {

  readSensors();

  calculateSolarPosition();

  trackingControl();

  sendDataToN8N();

  delay(10000);
}

19. Sensor Function

void readSensors() {

  int north = analogRead(LDR_N);
  int south = analogRead(LDR_S);
  int east  = analogRead(LDR_E);
  int west  = analogRead(LDR_W);

  Serial.println("LDR readings:");

  Serial.println(north);
  Serial.println(south);
  Serial.println(east);
  Serial.println(west);

  // Replace these with INA219/INA226 readings
  panelVoltage = 18.2;
  panelCurrent = 1.45;

  panelPower = panelVoltage * panelCurrent;
}

20. LDR Tracking Control

void trackingControl() {

  int north = analogRead(LDR_N);
  int south = analogRead(LDR_S);
  int east  = analogRead(LDR_E);
  int west  = analogRead(LDR_W);

  int horizontalError = east - west;
  int verticalError = north - south;

  const int deadBand = 100;

  if (horizontalError > deadBand) {

    trackerAzimuth += 1;

  } else if (horizontalError < -deadBand) {

    trackerAzimuth -= 1;
  }

  if (verticalError > deadBand) {

    trackerElevation += 1;

  } else if (verticalError < -deadBand) {

    trackerElevation -= 1;
  }

  trackerAzimuth = constrain(
      trackerAzimuth,
      0,
      180
  );

  trackerElevation = constrain(
      trackerElevation,
      0,
      90
  );
}

In the real system, this function should drive actual servos/motors rather than simply changing variables.


21. Sending Data to n8n

void sendDataToN8N() {

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

  HTTPClient http;

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

  StaticJsonDocument<1024> doc;

  doc["device_id"] = "FLOAT_SOLAR_01";

  doc["solar_azimuth"] = solarAzimuth;
  doc["solar_elevation"] = solarElevation;

  doc["tracker_azimuth"] = trackerAzimuth;
  doc["tracker_elevation"] = trackerElevation;

  doc["voltage"] = panelVoltage;
  doc["current"] = panelCurrent;
  doc["power"] = panelPower;

  String json;

  serializeJson(doc, json);

  int responseCode = http.POST(json);

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

  http.end();
}

22. n8n Architecture

n8n becomes the automation brain around the ESP32.

Recommended workflow:

                    ESP32
                      │
                      ▼
              ┌─────────────┐
              │ n8n Webhook │
              └──────┬──────┘
                     │
                     ▼
              Validate Data
                     │
                     ▼
              Normalize Data
                     │
             ┌───────┴────────┐
             │                │
             ▼                ▼
        Google Sheets    ThingSpeak
             │
             └───────┬────────┘
                     ▼
                 AI Agent
                     │
                     ▼
               Decision Node
               /     |      \
              /      |       \
          NORMAL   WARNING   CRITICAL
             │        │          │
             ▼        ▼          ▼
           Log     Telegram   Voice Alert

23. n8n Workflow Nodes

A complete workflow could contain:

1. Webhook
2. Set / Edit Fields
3. JSON Validation
4. Function / Code
5. IF – Sensor Valid?
6. Google Sheets
7. HTTP Request – ThingSpeak
8. AI Agent
9. Structured Output Parser
10. IF – Alert Required?
11. Telegram
12. Text-to-Speech
13. Telegram Voice
14. Logging

24. n8n Webhook

The ESP32 sends:

POST /webhook/solar

with:

{
  "device_id": "FLOAT_SOLAR_01",
  "power": 26.39,
  "temperature": 42.5,
  "water_level": 74,
  "battery_voltage": 12.6,
  "tracking_status": "TRACKING"
}

The n8n webhook receives the information.


25. Data Validation

The workflow should check:

Is voltage valid?
       │
       ├── NO ──> Sensor Error
       │
       └── YES
            │
            ▼
Is current valid?
            │
            ├── NO ──> Sensor Error
            │
            └── YES
                 │
                 ▼
Continue

This prevents the AI agent from making decisions based on corrupt data.


26. Google Sheets Database

Create columns such as:

Timestamp Device Voltage Current Power Temp Water Level Azimuth Elevation Battery

Example:

2026-10-07 12:30
FLOAT_SOLAR_01
18.2
1.45
26.39
42.5
74
142.5
54.2
12.6

Google Sheets is useful for:

  • Historical data

  • Reports

  • Excel-compatible analysis

  • Maintenance records

  • Daily energy summaries


27. ThingSpeak Dashboard

ThingSpeak can be used for real-time visualization.

Possible fields:

Field 1 = Voltage
Field 2 = Current
Field 3 = Power
Field 4 = Panel Temperature
Field 5 = Water Temperature
Field 6 = Battery Voltage
Field 7 = Solar Azimuth
Field 8 = Solar Elevation

Dashboard:

┌─────────────────────────────────────┐
│       FLOATING SOLAR MONITOR        │
├─────────────────────────────────────┤
│ Voltage       18.2 V                │
│ Current        1.45 A               │
│ Power         26.39 W               │
│ Panel Temp    42.5 °C               │
│ Battery       12.6 V                │
├─────────────────────────────────────┤
│ Solar Azimuth       142.5°          │
│ Solar Elevation      54.2°          │
├─────────────────────────────────────┤
│ Status: TRACKING                    │
└─────────────────────────────────────┘

28. AI Agent

The AI agent should not directly control dangerous hardware without constraints.

Instead, it should act as a supervisory intelligence layer.

It receives:

{
  "power": 26.39,
  "panel_temperature": 42.5,
  "water_level": 74,
  "battery_voltage": 12.6,
  "tracking_error": 1.4,
  "motor_status": "OK"
}

The AI evaluates the condition.


29. Example AI Prompt

A useful system instruction for the AI agent is:

You are the supervisory AI agent for a floating solar
photovoltaic tracking system.

Analyze the sensor data provided by the ESP32.

Your responsibilities are:

1. Detect abnormal operating conditions.
2. Identify possible sensor failures.
3. Identify excessive panel temperature.
4. Identify low battery voltage.
5. Identify abnormal water level.
6. Identify excessive tracking error.
7. Identify unusual power reduction.
8. Recommend maintenance when appropriate.
9. Determine alert severity.

Severity levels:

NORMAL
WARNING
CRITICAL

Never invent sensor values.

Never claim that hardware has moved unless movement
confirmation is available.

Do not issue unrestricted motor commands.

Return structured JSON.

30. AI Output

Example:

{
  "status": "WARNING",
  "reason": "Panel temperature is elevated",
  "severity": 2,
  "recommended_action": "Increase monitoring frequency",
  "telegram_alert": true,
  "voice_alert": false
}

For a critical event:

{
  "status": "CRITICAL",
  "reason": "Battery voltage is below safe operating threshold",
  "severity": 3,
  "recommended_action": "Enter low-power mode",
  "telegram_alert": true,
  "voice_alert": true
}

31. Agentic IoT Concept

The project becomes agentic IoT when the system can observe, reason, decide and initiate actions.

OBSERVE
   │
   ▼
ESP32 Sensors
   │
   ▼
UNDERSTAND
   │
   ▼
n8n + AI Agent
   │
   ▼
REASON
   │
   ▼
Determine condition
   │
   ▼
DECIDE
   │
   ▼
Choose action
   │
   ▼
ACT
   │
   ├── Telegram
   ├── Voice Alert
   ├── Database
   ├── Dashboard
   └── ESP32 command

32. Telegram Alert

Example normal warning:

☀️ FLOATING SOLAR ALERT

Device: FLOAT_SOLAR_01

Status: WARNING

Panel Power: 26.4 W
Panel Temperature: 42.5 °C
Battery: 12.6 V

Reason:
Panel temperature is above the preferred operating range.

Recommendation:
Continue monitoring.

33. Telegram Critical Voice Alert

Example:

🚨 CRITICAL FLOATING SOLAR ALERT

Device FLOAT_SOLAR_01 has detected critically low
battery voltage.

Current battery voltage: 10.8 volts.

The system recommends entering low-power mode
and inspecting the battery and charging circuit.

n8n can:

AI Agent
   ↓
Generate alert text
   ↓
Text-to-Speech service
   ↓
MP3/OGG audio
   ↓
Telegram Bot
   ↓
Operator's phone

34. Telegram Conversation / Chat Architecture

The system can also become interactive.

                 USER
                  │
                  ▼
              Telegram
                  │
                  ▼
             n8n Webhook
                  │
                  ▼
              AI Agent
                  │
       ┌──────────┼──────────┐
       │          │          │
       ▼          ▼          ▼
   Current     History    Commands
    Data       Data       /status
       │          │          │
       └──────────┼──────────┘
                  ▼
              AI Response
                  │
                  ▼
              Telegram

35. Example Telegram Chat

User

/status

AI Agent

☀️ Solar System Status

Power: 26.4 W
Voltage: 18.2 V
Current: 1.45 A

Panel temperature: 42.5 °C
Battery: 12.6 V

Solar azimuth: 142.5°
Solar elevation: 54.2°

Tracker: NORMAL
Water level: NORMAL

Overall condition: GOOD

36. Natural-Language Commands

The Telegram AI agent could support:

What is the current power?
How much energy did we generate today?
Is the tracker working correctly?
Why is the power lower than yesterday?
Show today's maximum power.
Is the battery healthy?
Give me a daily report.

37. AI Daily Report

n8n can run automatically at a selected time.

Example:

☀️ DAILY SOLAR REPORT

Device:
FLOAT_SOLAR_01

Energy generated:
1.82 kWh

Peak power:
143 W

Average power:
76 W

Maximum temperature:
47.2 °C

Tracking performance:
96.4%

Tracker errors:
3

Critical alerts:
0

Warnings:
2

System health:
GOOD

38. Web Dashboard

The project should have a webpage.

Recommended dashboard:

┌──────────────────────────────────────────────────┐
│             AI FLOATING SOLAR SYSTEM             │
├──────────────────────────────────────────────────┤
│                                                  │
│   POWER             ENERGY TODAY                │
│   126 W             1.82 kWh                    │
│                                                  │
├──────────────────────────────────────────────────┤
│ Voltage     Current     Temperature   Battery   │
│ 18.4 V       6.8 A        42 °C        12.7 V   │
├──────────────────────────────────────────────────┤
│                                                  │
│             ☀ SUN POSITION                       │
│                                                  │
│       Azimuth: 142°                             │
│       Elevation: 54°                            │
│                                                  │
├──────────────────────────────────────────────────┤
│             TRACKER POSITION                     │
│                                                  │
│       Azimuth: 141°                             │
│       Elevation: 53°                            │
│                                                  │
├──────────────────────────────────────────────────┤
│ AI STATUS:       ● NORMAL                        │
│ MOTOR:           ● OK                            │
│ INTERNET:        ● CONNECTED                    │
│ BATTERY:         ● GOOD                         │
└──────────────────────────────────────────────────┘

39. Webpage Technology Options

You can build the dashboard using:

Simple

HTML
CSS
JavaScript

More advanced

React
+
Chart.js
+
REST API
+
n8n

Example architecture

ESP32
  │
  ▼
n8n
  │
  ├── Google Sheets
  ├── ThingSpeak
  └── Dashboard API
          │
          ▼
      Web Browser

40. Example HTML Dashboard

<!DOCTYPE html>
<html>
<head>
    <title>AI Floating Solar Tracker</title>

    <style>
        body {
            font-family: Arial;
            background: #081b29;
            color: white;
            margin: 0;
        }

        header {
            background: #0d6efd;
            padding: 20px;
            text-align: center;
        }

        .dashboard {
            display: grid;
            grid-template-columns:
                repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            padding: 20px;
        }

        .card {
            background: #102d42;
            padding: 25px;
            border-radius: 15px;
            text-align: center;
        }

        .value {
            font-size: 32px;
            color: #00ff99;
        }
    </style>
</head>

<body>

<header>
    <h1>☀️ AI Floating Solar Tracker</h1>
</header>

<div class="dashboard">

    <div class="card">
        <h3>Voltage</h3>
        <div class="value" id="voltage">-- V</div>
    </div>

    <div class="card">
        <h3>Current</h3>
        <div class="value" id="current">-- A</div>
    </div>

    <div class="card">
        <h3>Power</h3>
        <div class="value" id="power">-- W</div>
    </div>

    <div class="card">
        <h3>Temperature</h3>
        <div class="value" id="temperature">-- °C</div>
    </div>

    <div class="card">
        <h3>Battery</h3>
        <div class="value" id="battery">-- V</div>
    </div>

    <div class="card">
        <h3>Tracker</h3>
        <div class="value" id="tracker">--</div>
    </div>

</div>

<script>

async function updateDashboard() {

    const response =
        await fetch("/api/status");

    const data =
        await response.json();

    document.getElementById("voltage")
        .innerText = data.voltage + " V";

    document.getElementById("current")
        .innerText = data.current + " A";

    document.getElementById("power")
        .innerText = data.power + " W";

    document.getElementById("temperature")
        .innerText = data.temperature + " °C";

    document.getElementById("battery")
        .innerText = data.battery + " V";

    document.getElementById("tracker")
        .innerText = data.tracker;
}

setInterval(updateDashboard, 5000);

updateDashboard();

</script>

</body>
</html>

41. Recommended API Response

The dashboard API can return:

{
  "voltage": 18.2,
  "current": 1.45,
  "power": 26.39,
  "temperature": 42.5,
  "battery": 12.6,
  "tracker": "TRACKING",
  "azimuth": 142.5,
  "elevation": 54.2,
  "waterLevel": 74,
  "status": "NORMAL"
}

42. Complete n8n Workflow

A production-oriented workflow can look like this:

                     ┌───────────────┐
                     │     ESP32     │
                     └───────┬───────┘
                             │
                             ▼
                     ┌───────────────┐
                     │    WEBHOOK    │
                     └───────┬───────┘
                             │
                             ▼
                     ┌───────────────┐
                     │ VALIDATE JSON │
                     └───────┬───────┘
                             │
                             ▼
                     ┌───────────────┐
                     │ NORMALIZATION │
                     └───────┬───────┘
                             │
              ┌──────────────┼───────────────┐
              │              │               │
              ▼              ▼               ▼
        Google Sheets    ThingSpeak      Database
              │              │
              └──────────────┼───────────────┘
                             ▼
                       ┌───────────┐
                       │ AI AGENT  │
                       └─────┬─────┘
                             │
                             ▼
                    ┌────────────────┐
                    │ Decision Logic │
                    └───────┬────────┘
                            │
          ┌─────────────────┼────────────────┐
          │                 │                │
          ▼                 ▼                ▼
       NORMAL            WARNING          CRITICAL
          │                 │                │
          ▼                 ▼                ▼
         LOG             Telegram      Telegram Text
                                             │
                                             ▼
                                       Text-to-Speech
                                             │
                                             ▼
                                       Telegram Voice

43. Safety Layer

This is extremely important.

The AI agent should not be allowed to bypass hardware safety limits.

Implement:

                 AI COMMAND
                     │
                     ▼
              SAFETY VALIDATOR
                     │
        ┌────────────┼────────────┐
        │            │            │
    Position      Current       Voltage
      limit         limit         limit
        │            │            │
        └────────────┼────────────┘
                     ▼
               COMMAND SAFE?
                 /       \
               NO         YES
               │           │
               ▼           ▼
             REJECT       ESP32

The ESP32 itself must enforce limits even if n8n or the AI sends an invalid command.


44. Watchdog System

The ESP32 should have a watchdog.

ESP32
 │
 ├── Sensor task
 ├── Tracker task
 ├── Wi-Fi task
 └── Communication task
       │
       ▼
    Watchdog
       │
       ├── System healthy
       │
       └── System frozen
                │
                ▼
              RESET

45. Offline Mode

A robust system should continue working if Wi-Fi disappears.

             Wi-Fi?
             /    \
           YES     NO
            │       │
            ▼       ▼
         Cloud    Local
         Mode     Mode
            │       │
            └──┬────┘
               ▼
          ESP32 Tracker

During Wi-Fi failure:

  • Sun tracking continues.

  • Safety functions continue.

  • Local sensor control continues.

  • Data can be buffered.

  • Data can be uploaded after connection returns.


46. Data Buffering

For example:

if (WiFi.status() != WL_CONNECTED) {

    saveDataLocally();

} else {

    uploadBufferedData();

}

For a more robust design, use:

  • LittleFS

  • SPIFFS

  • SD card

  • external flash


47. AI Fault Detection

The AI agent can detect patterns such as:

Case 1 — High temperature

Temperature ↑
Power ↓
Solar radiation high
       │
       ▼
AI suspects thermal derating

Case 2 — Motor failure

Target position ≠ actual position

Motor command = ON
Position change = 0

       ↓

AI:
Possible motor/gear obstruction

Case 3 — Dirty panel

Solar radiation = high
Tracking = normal
Power = unusually low

       ↓

Possible:
- Dust
- Shading
- Panel degradation
- Electrical fault

48. Predictive Maintenance

The project can become more advanced by storing historical data.

Example:

Date       Power     Temp     Motor Error
------------------------------------------
Day 1      145 W     37°C       1
Day 2      142 W     38°C       1
Day 3      139 W     39°C       2
Day 4      132 W     41°C       3
Day 5      126 W     43°C       5

AI can identify:

Power trend ↓
Motor error ↑
Temperature ↑

and generate:

MAINTENANCE RECOMMENDATION

The tracker has shown increasing positioning error
over the last five days.

Recommended inspection:
- Azimuth motor
- Mechanical bearings
- Gear mechanism
- Mounting structure

49. Energy Optimization

The AI system can compare:

Fixed panel output
        VS
Tracked panel output

Calculate:

Tracking gain (%) =
((Tracked Energy - Fixed Energy)
 / Fixed Energy) × 100

For example:

Fixed = 1.20 kWh/day
Tracked = 1.48 kWh/day

Gain =
(1.48 - 1.20) / 1.20 × 100

= 23.3%

The actual improvement must be measured experimentally rather than assumed.


50. Floating-Solar-Specific Monitoring

Because the project is floating, add sensors that a conventional solar tracker doesn't need.

Water level

Normal
  │
  ├── Low → inspect flotation
  │
  └── High → possible flooding/wave condition

Tilt

Tilt X
Tilt Y
   │
   ▼
Platform stability

Water temperature

Useful for environmental monitoring and research.

Wind

A future version can include an anemometer.

Wind speed > safety limit
             │
             ▼
         Park panel

51. Emergency Logic

Example:

IF wind_speed > MAX_WIND
       ↓
Park tracker

IF battery_voltage < MIN_BATTERY
       ↓
Low-power mode

IF panel_temperature > MAX_TEMP
       ↓
Send warning

IF water_level abnormal
       ↓
Critical alert

IF platform_tilt > MAX_TILT
       ↓
Stop motors + alert

IF motor_current > MAX_MOTOR_CURRENT
       ↓
Stop motor + alert

These rules should be implemented locally on the ESP32, not solely through the AI/cloud layer.


52. Complete Communication Architecture

                 ┌────────────────────┐
                 │ Floating PV System  │
                 └──────────┬─────────┘
                            │
                            ▼
                       ┌─────────┐
                       │  ESP32  │
                       └────┬────┘
                            │
                    Wi-Fi / HTTP
                            │
                            ▼
                     ┌───────────┐
                     │    n8n    │
                     └─────┬─────┘
                           │
       ┌───────────────────┼─────────────────────┐
       │                   │                     │
       ▼                   ▼                     ▼
 Google Sheets         ThingSpeak            AI Agent
       │                                         │
       │                                         ▼
       │                                  Decision Engine
       │                                         │
       │                          ┌──────────────┼───────────┐
       │                          │              │           │
       ▼                          ▼              ▼           ▼
 Historical Data             Telegram       Voice Alert   ESP32
                                     

53. Complete Hardware Wiring Concept

                         ESP32
                  ┌─────────────────┐
                  │                 │
 LDR North ───────┤ GPIO 34         │
 LDR South ───────┤ GPIO 35         │
 LDR East ────────┤ GPIO 32         │
 LDR West ────────┤ GPIO 33         │
                  │                 │
 INA219 SDA ──────┤ GPIO 21         │
 INA219 SCL ──────┤ GPIO 22         │
                  │                 │
 DS18B20 ─────────┤ GPIO 4          │
                  │                 │
 MPU6050 SDA ─────┤ GPIO 21         │
 MPU6050 SCL ─────┤ GPIO 22         │
                  │                 │
 Servo AZ ────────┤ GPIO 18         │
 Servo EL ────────┤ GPIO 19         │
                  │                 │
 GPS RX/TX ───────┤ Serial          │
                  │                 │
 Wi-Fi ───────────┤ ESP32 Radio     │
                  └─────────────────┘

Important: motor/servo power should normally come from a suitable separate power supply, with a common ground and appropriate protection. Do not power high-current motors directly from ESP32 GPIO pins.


54. Suggested Pin Assignment

Device ESP32 Pin
LDR North GPIO 34
LDR South GPIO 35
LDR East GPIO 32
LDR West GPIO 33
I²C SDA GPIO 21
I²C SCL GPIO 22
DS18B20 GPIO 4
Azimuth servo GPIO 18
Elevation servo GPIO 19
GPS RX/TX Hardware UART
Motor driver Dedicated GPIOs
Limit switch 1 GPIO 25
Limit switch 2 GPIO 26

The exact pins should be adapted to the particular ESP32 board and peripherals.


55. Project State Machine

A professional implementation should use states.

             ┌───────────┐
             │   START   │
             └─────┬─────┘
                   ▼
             ┌───────────┐
             │  INIT     │
             └─────┬─────┘
                   ▼
             ┌───────────┐
             │   IDLE    │
             └─────┬─────┘
                   ▼
             ┌───────────┐
             │ TRACKING  │
             └─────┬─────┘
                   │
        ┌──────────┼──────────┐
        ▼          ▼          ▼
      NORMAL     WARNING    CRITICAL
        │          │          │
        │          ▼          ▼
        │       ALERT       PARK
        │          │          │
        └──────────┴──────────┘
                   │
                   ▼
              NIGHT MODE
                   │
                   ▼
             PARK POSITION

56. Night Mode

At sunset:

Solar elevation < 0°
        │
        ▼
Stop tracking
        │
        ▼
Move to safe park position
        │
        ▼
Enter low-power mode

At sunrise:

Solar elevation > threshold
        │
        ▼
Wake tracker
        │
        ▼
Move to predicted sunrise position
        │
        ▼
Begin tracking

57. AI + n8n Advanced Workflow

A more advanced system can have several specialized agents.

                    n8n
                     │
       ┌─────────────┼─────────────┐
       │             │             │
       ▼             ▼             ▼
 Energy Agent   Maintenance     Safety Agent
                   Agent
       │             │             │
       └─────────────┼─────────────┘
                     ▼
               Supervisor AI
                     │
                     ▼
              Final Decision

Energy Agent

Analyzes:

  • Power

  • Energy

  • Irradiance

  • Temperature

  • Tracking efficiency

Maintenance Agent

Analyzes:

  • Motor errors

  • Sensor errors

  • Long-term degradation

  • Mechanical anomalies

Safety Agent

Analyzes:

  • Battery

  • Wind

  • tilt

  • water level

  • temperature


58. Example Agentic Scenario

Suppose:

Power = 62 W
Expected power = 120 W
Sun elevation = 55°
Tracker error = 1°
Temperature = 38°C

AI concludes:

Tracking appears correct.

Power output is substantially below expected
performance.

Possible causes:
1. Panel shading
2. Dirt
3. Electrical connection problem
4. PV degradation

Then n8n can:

Create maintenance event
        ↓
Store in Google Sheets
        ↓
Send Telegram notification

59. Telegram Voice Workflow

Sensor
  │
  ▼
ESP32
  │
  ▼
n8n
  │
  ▼
AI Agent
  │
  ▼
CRITICAL?
  │
 YES
  │
  ▼
Generate message
  │
  ▼
Text-to-Speech
  │
  ▼
Audio file
  │
  ▼
Telegram Bot
  │
  ▼
Operator

60. Example Voice Alert Logic

if (severity === "CRITICAL") {

    message =
      "Critical alert. Floating solar system "
      + device
      + " has detected "
      + reason
      + ".";

}

Then n8n passes the message to a TTS service.


61. AI Chat Interface

A web page can also include:

┌─────────────────────────────────────────┐
│        AI SOLAR ASSISTANT               │
├─────────────────────────────────────────┤
│                                         │
│ User:                                   │
│ Why is power lower today?               │
│                                         │
│ AI:                                     │
│ Power is approximately 18% below the    │
│ recent average. Tracking error is low,  │
│ so panel alignment appears normal.     │
│                                         │
│ The most likely factors are temperature │
│ and reduced irradiance.                 │
│                                         │
├─────────────────────────────────────────┤
│ Ask AI...                        [Send]  │
└─────────────────────────────────────────┘

62. Project Folder Structure

A clean GitHub project could use:

AI-Floating-Solar-Tracker/
│
├── README.md
│
├── documentation/
│   ├── architecture.md
│   ├── hardware.md
│   ├── software.md
│   ├── n8n-workflow.md
│   ├── ai-agent.md
│   ├── telegram.md
│   └── testing.md
│
├── hardware/
│   ├── schematic/
│   ├── pcb/
│   ├── wiring/
│   └── bom.csv
│
├── firmware/
│   ├── main/
│   ├── sensors/
│   ├── tracker/
│   ├── solar/
│   └── communication/
│
├── n8n/
│   ├── workflows/
│   └── prompts/
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── ai/
│   ├── prompts/
│   └── schemas/
│
├── telegram/
│   └── commands.md
│
└── tests/
    ├── sensor-tests/
    ├── motor-tests/
    └── integration-tests/

63. Bill of Materials

A prototype BOM could include:

Component Qty
ESP32 DevKit 1
Small solar panel 1
Servo/geared motors 2
Motor driver 1–2
LDR 4
INA219/INA226 1
DS18B20 1–2
MPU6050 1
GPS module 1
RTC DS3231 1
Water-level sensor 1
Battery 1
Buck converter 1
Limit switches 2–4
Waterproof enclosure 1
Floating structure 1
Wires/connectors As required
Fuse/protection As required

64. Software Stack

Hardware
   ↓
ESP32 / Arduino C++
   ↓
Wi-Fi
   ↓
HTTP / MQTT
   ↓
n8n
   ↓
AI Agent
   ↓
Google Sheets
ThingSpeak
Telegram
Web Dashboard

Potential software:

  • Arduino IDE / PlatformIO

  • C/C++

  • JavaScript

  • HTML/CSS

  • n8n

  • Telegram Bot API

  • Google Sheets API

  • ThingSpeak API

  • AI API

  • Text-to-Speech API


65. Testing Plan

The project should be tested in stages.

Test 1 — ESP32

Verify:

ESP32 boots
      ↓
Wi-Fi connects
      ↓
Sensors work

Test 2 — LDR

Use a flashlight.

Light left
   ↓
Tracker moves left

Light right
   ↓
Tracker moves right

Test 3 — Motor

Check:

0°
45°
90°
135°
180°

and verify mechanical limits.

Test 4 — Power measurement

Compare INA219/INA226 readings against a calibrated meter.

Test 5 — n8n

Send a simulated JSON packet.

Test 6 — Google Sheets

Verify one row is inserted per valid measurement.

Test 7 — ThingSpeak

Verify all fields update correctly.

Test 8 — Telegram

Trigger a warning manually.

Test 9 — AI

Feed simulated abnormal data.

Test 10 — End-to-end

ESP32
 ↓
n8n
 ↓
AI
 ↓
Telegram

66. Failure-Test Scenarios

Test at least these conditions:

Condition Expected action
Wi-Fi disconnected Local operation
Battery low Low-power mode
High temperature Warning
Excessive tilt Stop tracker
Motor overcurrent Stop motor
Water abnormal Alert
Sensor disconnected Sensor-failure alert
Night Park
High wind Park
AI unavailable Local control continues

67. Key Design Principle

The most important architecture principle is:

                AI / CLOUD
                    │
            Advisory / supervisory
                    │
                    ▼
                 ESP32
                    │
              Deterministic
               safety logic
                    │
                    ▼
                 Motors

Never make the cloud or AI the only safety mechanism.

If n8n goes offline, the tracker should still be safe.

If the AI service fails, the tracker should still operate.

If Wi-Fi fails, the tracker should still protect itself.


68. Final System Flow Diagram

                         ☀ SUN
                          │
                          ▼
                ┌──────────────────┐
                │ Sun-Path Model   │
                │ Azimuth/Elevation│
                └────────┬─────────┘
                         │
                         ▼
                  ┌──────────────┐
                  │    ESP32     │
                  │              │
                  │ Solar Track  │
                  │ Sensors      │
                  │ Safety       │
                  └──────┬───────┘
                         │
             ┌───────────┴───────────┐
             │                       │
             ▼                       ▼
       Motor Control             Sensor Data
             │                       │
             ▼                       ▼
        Floating PV              Wi-Fi
             │                       │
             └──────────┬────────────┘
                        ▼
                 ┌─────────────┐
                 │     n8n     │
                 └──────┬──────┘
                        │
          ┌─────────────┼──────────────┐
          │             │              │
          ▼             ▼              ▼
     Google Sheets  ThingSpeak      AI Agent
                                      │
                                      ▼
                                Decision Engine
                                      │
                           ┌──────────┼──────────┐
                           │          │          │
                           ▼          ▼          ▼
                         Normal    Warning    Critical
                                      │          │
                                      │          ▼
                                      │     Text-to-Speech
                                      │          │
                                      └────┬─────┘
                                           ▼
                                       Telegram
                                           │
                                           ▼
                                      Mobile User

69. Expected Project Output

At the end of the project, the prototype should demonstrate:

                    AI FLOATING SOLAR
                         SYSTEM
                           │
        ┌──────────────────┼──────────────────┐
        │                  │                  │
        ▼                  ▼                  ▼
   SUN TRACKING        IoT MONITORING       AI AGENT
        │                  │                  │
        ▼                  ▼                  ▼
     ESP32              n8n Cloud         Intelligent
        │                  │               Analysis
        │                  │                  │
        └──────────────────┼──────────────────┘
                           │
             ┌─────────────┼──────────────┐
             ▼             ▼              ▼
        Google Sheets  ThingSpeak      Telegram
                                          │
                                          ▼
                                     Voice Alerts

70. Recommended Project Phases

Phase 1 — Hardware

Build:

ESP32
+
PV panel
+
LDR
+
Motor
+
INA219/INA226

Phase 2 — Tracking

Implement:

LDR tracking
+
solar-position calculation

Phase 3 — IoT

Implement:

ESP32 → n8n

Phase 4 — Cloud

Implement:

n8n → Google Sheets
n8n → ThingSpeak

Phase 5 — AI

Implement:

n8n → AI Agent → Decision

Phase 6 — Telegram

Implement:

AI → Telegram text
AI → TTS → Telegram voice

Phase 7 — Dashboard

Implement:

ESP32/n8n
     ↓
Web API
     ↓
Dashboard

Phase 8 — Floating Platform

Move the completed electronics and tracker onto the water platform.

Phase 9 — Testing

Perform:

Indoor test
↓
Outdoor land test
↓
Water-tank test
↓
Real floating test

Phase 10 — Optimization

Compare:

Fixed PV
   VS
Single-axis
   VS
Dual-axis
   VS
AI-assisted optimized tracking

This comparison will make the project much stronger academically.


71. Suggested Final-Year Project Chapters

For a formal report, use:

  1. Introduction

  2. Problem Statement

  3. Existing System

  4. Proposed System

  5. Objectives

  6. System Architecture

  7. Hardware Design

  8. Floating Platform Design

  9. Solar Tracking Mechanism

  10. Sun-Path Prediction

  11. ESP32 Firmware

  12. IoT Communication

  13. n8n Automation

  14. AI Agent Design

  15. Telegram Notification System

  16. Google Sheets Integration

  17. ThingSpeak Integration

  18. Web Dashboard

  19. Safety and Fault Detection

  20. Experimental Methodology

  21. Results

  22. Performance Comparison

  23. Cost Analysis

  24. Limitations

  25. Future Scope

  26. Conclusion

  27. References

  28. Appendix – Source Code


72. Future Scope

The system can eventually be expanded with:

  • Weather forecasting

  • Cloud prediction

  • Machine-learning power prediction

  • Computer vision for cloud detection

  • Camera-based panel inspection

  • Automatic panel-cleanliness detection

  • Wind-speed prediction

  • Wave-motion prediction

  • Digital twin

  • Multi-panel floating solar farm

  • Edge AI

  • LoRaWAN for remote locations

  • Solar irradiance sensor

  • MPPT monitoring

  • Automatic fault classification

  • Predictive motor maintenance

  • AI-generated daily reports

  • Voice-based Telegram commands

  • Multi-agent AI architecture

A particularly interesting extension is:

Weather Forecast
       +
Historical Solar Data
       +
Sun Position
       +
Panel Temperature
       +
Cloud Prediction
       ↓
AI Energy Forecast
       ↓
Expected Solar Generation

That turns the project from a simple solar tracker into an AI-powered predictive floating solar management system.


73. Recommended Final Architecture

For the strongest version of the project, I recommend this exact hierarchy:

                    ┌─────────────────────────┐
                    │        SOLAR FARM       │
                    │ Floating PV + Tracker   │
                    └────────────┬────────────┘
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │          ESP32          │
                    │                         │
                    │ Sensors                 │
                    │ Solar Position          │
                    │ Tracker                 │
                    │ Local Safety            │
                    │ Offline Operation       │
                    └────────────┬────────────┘
                                 │
                              HTTPS
                                 │
                                 ▼
                    ┌─────────────────────────┐
                    │          n8n            │
                    │ Automation Orchestrator  │
                    └────────────┬────────────┘
                                 │
            ┌────────────────────┼─────────────────────┐
            │                    │                     │
            ▼                    ▼                     ▼
     ┌─────────────┐     ┌──────────────┐      ┌─────────────┐
     │Google Sheets│     │  ThingSpeak  │      │  AI Agent   │
     └─────────────┘     └──────────────┘      └──────┬──────┘
                                                       │
                                              ┌────────┼────────┐
                                              │        │        │
                                              ▼        ▼        ▼
                                           Energy  Safety  Maintenance
                                            Agent   Agent     Agent
                                              │        │        │
                                              └────────┼────────┘
                                                       ▼
                                              ┌────────────────┐
                                              │ Decision Layer │
                                              └───────┬────────┘
                                                      │
                                     ┌────────────────┼──────────────┐
                                     │                │              │
                                     ▼                ▼              ▼
                                  Dashboard       Telegram       Voice Alert

This architecture gives you a project that combines embedded systems + renewable energy + solar tracking + IoT + cloud automation + AI agents + data analytics + messaging automation, rather than simply being an ESP32 solar tracker.

If you build it in this order—ESP32 hardware → sun tracking → sensor monitoring → n8n → cloud logging → AI agent → Telegram/voice → dashboard → floating platform → predictive maintenance—you can test each subsystem independently before integrating the entire system.

 

Project Summary

AI-Powered Floating Solar Tracker with Sun-Path Prediction and Agentic IoT

The project is an ESP32-based floating solar photovoltaic system that automatically tracks the sun, monitors solar-panel and environmental parameters, sends data to the cloud, and uses n8n + an AI agent for automated analysis and alerts.

Core System

☀️ Sun
  ↓
Sun-Path Prediction
  ↓
ESP32
  ├── LDR Sensors
  ├── Voltage/Current Sensor
  ├── Temperature Sensor
  ├── Water-Level Sensor
  ├── Tilt Sensor
  ├── GPS/RTC
  └── Motor Control
  ↓
Floating Solar Panel
  ↓
Wi-Fi
  ↓
n8n Automation
  ├── Google Sheets
  ├── ThingSpeak
  ├── AI Agent
  └── Web Dashboard
       ↓
  Telegram
  ├── Text Alerts
  └── Voice Alerts

Main Features

  • Dual-axis solar tracking

  • Sun azimuth/elevation prediction

  • LDR-based tracking correction

  • ESP32-based control

  • Solar voltage, current and power measurement

  • Panel and water temperature monitoring

  • Battery monitoring

  • Platform tilt and water-level monitoring

  • Local safety and offline operation

  • n8n automation

  • AI-based fault analysis

  • Google Sheets historical logging

  • ThingSpeak visualization

  • Real-time web dashboard

  • Telegram notifications

  • Telegram voice alerts

  • AI daily reports

  • Predictive maintenance

AI Agent Role

The AI is primarily a supervisory intelligence layer, not the primary safety controller.

Sensors
   ↓
ESP32
   ↓
n8n
   ↓
AI Agent
   ↓
Analyze
   ↓
NORMAL / WARNING / CRITICAL
   ↓
Telegram / Voice / Dashboard

The ESP32 retains local safety controls so the system can continue operating safely even if Wi-Fi, n8n, or the AI service fails.

Major Hardware

  • ESP32 DevKit

  • Solar panel

  • Two motors/servos

  • Motor drivers

  • 4 LDRs

  • INA219/INA226

  • DS18B20

  • MPU6050

  • GPS

  • DS3231 RTC

  • Water-level sensor

  • Battery

  • Buck converter

  • Limit switches

  • Floating platform

Software Stack

ESP32 / Arduino C++
        ↓
HTTP / MQTT
        ↓
n8n
        ↓
AI Agent
 ┌──────┼─────────┐
 ↓      ↓         ↓
Sheets ThingSpeak Telegram
                  ↓
             Voice Alerts

Final Project Goal

The finished prototype demonstrates an autonomous floating solar-energy management system capable of:

  1. Predicting the sun's position.

  2. Tracking the sun automatically.

  3. Measuring solar-energy production.

  4. Monitoring floating-platform conditions.

  5. Sending IoT data to the cloud.

  6. Using AI to identify abnormal conditions.

  7. Automatically recording historical data.

  8. Sending Telegram text and voice alerts.

  9. Providing a real-time web dashboard.

  10. Supporting predictive maintenance and future solar-generation forecasting.

One-Line Description

An ESP32-based AI-agentic floating solar tracker that combines sun-path prediction, IoT sensing, n8n automation, cloud dashboards, Google Sheets, ThingSpeak, and Telegram voice alerts for autonomous solar-energy monitoring and management.