Saturday, 22 August 2026

AI Powered Borewell Child Rescue Robot with ESP32CAM, Gas Detection & Robotic Gripper

AI-Powered Borewell Child Rescue Robot — Complete Project Documentation

This project can be designed as a tele-operated rescue robot with AI-assisted decision support, rather than a fully autonomous machine. That distinction is important: a real borewell rescue operation is safety-critical, so the robot should never automatically grab, lift, or make a rescue decision based only on an AI model. AI should assist the human operator by analyzing sensor/video data and generating alerts.

The architecture below combines:

  • ESP32-CAM live video
  • ESP32 sensor/controller
  • Gas detection
  • Temperature/humidity
  • Distance/depth sensing
  • Robotic gripper
  • DC geared motors
  • Motor driver
  • LED illumination
  • Buzzer
  • Wi-Fi
  • Local control webpage
  • n8n automation
  • AI agent
  • Telegram alerts
  • Telegram voice notifications
  • Google Sheets logging
  • ThingSpeak cloud dashboard

The Arduino-ESP32 documentation currently covers ESP32 Arduino Core 3.3.x and ESP-IDF 5.5, so the code below is structured around the current Arduino ESP32 environment.


1. Project Title

AI-Powered Borewell Child Rescue Robot Using ESP32-CAM, Gas Detection, Robotic Gripper, IoT, n8n Automation and AI Agent

Short title

AI-Borewell Rescue Robot

Main objective

To develop a remotely operated robotic system capable of entering a borewell or confined vertical shaft and providing:

  1. Live video monitoring.
  2. Gas/environment monitoring.
  3. Victim-location assistance.
  4. Two-way robotic movement.
  5. Controlled robotic gripper operation.
  6. Lighting.
  7. Sensor telemetry.
  8. Emergency alerts.
  9. Cloud data logging.
  10. AI-assisted situation analysis.
  11. Telegram notifications and voice alerts.
  12. Web-based remote monitoring.

2. Important Safety Principle

This should initially be treated as a prototype/research demonstrator, not as equipment certified for actual human rescue.

A real deployment requires professional rescue engineering, structural assessment, redundant communication, rated lifting equipment, oxygen monitoring, intrinsically safe equipment where required, emergency recovery mechanisms, and trained rescue personnel.

In particular:

  • Do not allow the gripper to autonomously close around a person.
  • Do not use an MQ-series gas sensor as the sole determination that a borewell is safe.
  • Do not suspend a person from an untested robot chassis or hobby servo.
  • Do not operate motors when the robot's tether/cable can become entangled.
  • Provide a mechanical recovery cable independent of software.
  • The operator should have a physical emergency stop.
  • AI should recommend, not make the final rescue decision.

3. Overall System Architecture

                         ┌───────────────────────┐
                         │       OPERATOR        │
                         │ Laptop / Mobile Phone │
                         └───────────┬───────────┘
                                     │
                         Wi-Fi / Internet
                                     │
                ┌────────────────────▼────────────────────┐
                │          n8n AUTOMATION SERVER          │
                │                                          │
                │ Webhook → AI Agent → Decision Logic     │
                │      │             │                    │
                │      │             ├── Telegram         │
                │      │             ├── Voice Alert      │
                │      │             ├── Google Sheets    │
                │      │             └── Cloud Dashboard   │
                └───────────────┬──────────────────────────┘
                                │
                ┌───────────────┼────────────────┐
                │               │                │
          Telegram          Google Sheets    ThingSpeak
                │                                │
                │                                │
                └───────────────┬────────────────┘
                                │
                         Internet / Wi-Fi
                                │
                 ┌──────────────▼──────────────┐
                 │          ESP32              │
                 │                             │
                 │ Sensors                     │
                 │ Gas                         │
                 │ Temperature/Humidity         │
                 │ Distance                     │
                 │ Battery                      │
                 │                             │
                 │ Motor Controller             │
                 │ Gripper                      │
                 │ Lights                       │
                 └──────────────┬──────────────┘
                                │
                         Local Control
                                │
                    ┌───────────▼───────────┐
                    │      ESP32-CAM        │
                    │                       │
                    │ Live Video            │
                    │ Camera                 │
                    │ Illumination           │
                    └───────────────────────┘

4. Recommended Hardware

Component Purpose
ESP32 DevKit Main controller
ESP32-CAM AI Thinker Video
OV2640 camera Image capture
L298N/TB6612FNG Motor control
2 × DC geared motors Robot movement
Servo motor Gripper
Robotic gripper Controlled gripping
MQ-2/MQ-4/MQ-135 Prototype gas sensing
DHT22/SHT31 Temperature/humidity
VL53L0X/ultrasonic sensor Distance
MPU6050 Tilt/orientation
High-brightness LED Borewell illumination
Buzzer Local alarm
Battery Robot power
Buck converter Regulated supply
Emergency stop Hardware safety
Tether/recovery cable Mechanical recovery
Limit switches Mechanical position protection
Waterproof enclosure Electronics protection
Wi-Fi router/hotspot Communication

For an actual confined-space rescue system, replace hobby-grade environmental sensors with appropriately rated professional gas/oxygen monitoring equipment.


5. Why Use Two ESP32 Boards?

An ESP32-CAM is excellent for video but has limited GPIO availability.

Therefore, a much cleaner design is:

ESP32-CAM
    │
    ├── Camera
    ├── Video stream
    └── Optional light

ESP32 MAIN CONTROLLER
    │
    ├── Motors
    ├── Gripper
    ├── Gas sensor
    ├── Temperature
    ├── Distance
    ├── IMU
    ├── Battery
    └── n8n communication

This also prevents camera processing from interfering with motor/safety control.

ESP32 supports Wi-Fi station mode for connecting to an access point, which is the appropriate mode when the robot needs Internet connectivity.


6. Functional Block Diagram

                  ┌───────────────┐
                  │ ESP32-CAM     │
                  │ OV2640        │
                  └───────┬───────┘
                          │
                    Live Video
                          │
                          ▼
                 ┌────────────────┐
                 │ Web Dashboard   │
                 └────────────────┘


┌──────────────┐
│ Gas Sensor   │
└──────┬───────┘
       │
┌──────▼───────┐
│              │
│     ESP32     │
│ Main Control  │
│              │
└──┬──┬──┬──┬──┘
   │  │  │  │
   │  │  │  └──────► Battery Monitor
   │  │  └─────────► Distance
   │  └────────────► Gripper
   └───────────────► Motor Driver
                          │
                     ┌────┴────┐
                     ▼         ▼
                   Motor L   Motor R

ESP32
  │
  ▼
Wi-Fi
  │
  ▼
n8n Webhook
  │
  ├──► AI Agent
  │
  ├──► Google Sheets
  │
  ├──► ThingSpeak
  │
  └──► Telegram
           │
           └──► Voice Alert

n8n's Webhook node can receive HTTP requests from external devices and trigger workflows; it supports separate test and production webhook URLs and authentication mechanisms.


7. Robot Mechanical Structure

A practical prototype can use a vertical crawler configuration.

                 BOREWELL WALL
              ║                 ║
              ║   ┌─────────┐   ║
              ║   │ CAMERA  │   ║
              ║   └────┬────┘   ║
              ║        │        ║
              ║   ┌────▼────┐   ║
              ║   │   LED   │   ║
              ║   └─────────┘   ║
              ║                 ║
              ║  ┌───────────┐  ║
              ║  │  GRIPPER  │  ║
              ║  └─────┬─────┘  ║
              ║        │        ║
              ║   ┌────▼────┐   ║
              ║   │ ROBOT   │   ║
              ║   │ FRAME   │   ║
              ║   └─────────┘   ║
              ║    O       O    ║
              ║   MOTOR   MOTOR  ║
              ║                 ║
              ║       │         ║
              ║       │         ║
              ║    SAFETY       ║
              ║     TETHER      ║
              ║       │         ║
              ╚═══════╧═════════╝

The tether should provide mechanical recovery, not merely electrical/communication wiring.


8. Suggested ESP32 Main Controller Pin Assignment

For a generic ESP32 DevKit:

Function GPIO
Motor A IN1 25
Motor A IN2 26
Motor B IN1 27
Motor B IN2 14
Motor PWM A 32
Motor PWM B 33
Gripper Servo 13
Gas analog 34
DHT22 4
Distance trigger 5
Distance echo 18
Buzzer 19
LED 23
Battery ADC 35

Important: GPIO availability depends on the exact ESP32 board. Never copy a pin map to an ESP32-CAM without checking its board schematic.


9. Electrical Schematic

A simplified power architecture:

                   BATTERY
                     │
            ┌────────┴─────────┐
            │                  │
       MOTOR POWER         DC-DC BUCK
            │                  │
            ▼                  ▼
       MOTOR DRIVER          5V
            │                  │
       ┌────┴────┐       ┌────┴─────────┐
       │         │       │              │
     Motor L   Motor R  ESP32        Servo/LED
                         │
                         │
                   ┌─────┴─────┐
                   │           │
                 Sensors    Communication

Grounding

All low-voltage modules should share the appropriate common ground:

Battery GND
     │
     ├── Motor Driver GND
     ├── ESP32 GND
     ├── Sensor GND
     ├── Servo GND
     └── ESP32-CAM GND

However, motor current should be kept away from sensitive sensor wiring as much as possible.


10. Motor Driver Connection

Example with an H-bridge:

ESP32 GPIO25 ───── IN1
ESP32 GPIO26 ───── IN2
ESP32 GPIO27 ───── IN3
ESP32 GPIO14 ───── IN4

ESP32 GND ──────── GND

Motor Driver OUT1 ─── Motor A
Motor Driver OUT2 ─── Motor A

Motor Driver OUT3 ─── Motor B
Motor Driver OUT4 ─── Motor B

The motor supply must be appropriate for the actual motors.

Do not power the motors from the ESP32's 5-V/3.3-V rail.


11. Robotic Gripper

A prototype servo-driven gripper can use:

ESP32 GPIO13 ───── Servo signal
5V supply ──────── Servo VCC
GND ────────────── Servo GND

Example commands:

GRIP_OPEN
GRIP_CLOSE
GRIP_STOP

For a real rescue mechanism, add:

  • mechanical limit switches
  • current/torque monitoring
  • mechanical clutch
  • force-limiting mechanism
  • manual override
  • independent emergency release

The gripper should not be programmed to identify a human and automatically close.


12. Gas Detection

For an educational prototype:

MQ Sensor
   │
   ├── VCC
   ├── GND
   └── AO ───── ESP32 ADC

Example:

Gas ADC = 850
Temperature = 31.2 °C
Humidity = 78 %

The software can classify the sensor reading as:

NORMAL
WARNING
CRITICAL

But this should be understood as a prototype threshold, not an actual atmospheric safety certification.

A proper rescue system should monitor oxygen and hazardous gases using certified confined-space equipment.


13. Sensor Data Model

Use a consistent JSON packet.

{
  "device_id": "BOREBOT-01",
  "timestamp": 0,
  "gas_raw": 742,
  "temperature": 30.4,
  "humidity": 72.1,
  "distance": 1.82,
  "battery": 11.7,
  "tilt": 4.2,
  "motor": "STOP",
  "gripper": "OPEN",
  "status": "WARNING"
}

This makes n8n processing much easier.


14. IoT Communication Architecture

ESP32
  │
  │ HTTP POST
  ▼
n8n Webhook
  │
  ├───────────────┐
  ▼               ▼
AI Agent       Google Sheets
  │
  ├────────► Telegram
  │
  ├────────► Voice
  │
  └────────► Operator

n8n's Google Sheets integration supports operations including appending, updating, reading and deleting spreadsheet data.


15. n8n Workflow 1 — Telemetry

Create:

Webhook
   ↓
Validate JSON
   ↓
Normalize Data
   ↓
Google Sheets
   ↓
ThingSpeak
   ↓
AI Risk Analysis
   ↓
IF Critical?
   ├── NO → End
   └── YES
          ↓
       Telegram
          ↓
       Voice Alert

16. n8n Webhook Configuration

Create a Webhook node:

HTTP Method:
POST

Path:
borebot/telemetry

Response:
Immediately

Example endpoint:

https://YOUR-N8N-DOMAIN/webhook/borebot/telemetry

For development use the n8n test webhook. After testing, use the production webhook and publish/activate the workflow. n8n explicitly distinguishes its test and production webhook URLs.


17. ESP32 → n8n Code

Example:

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

const char* ssid = "YOUR_WIFI";
const char* password = "YOUR_PASSWORD";

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

void sendTelemetry(
    int gas,
    float temperature,
    float humidity,
    float distance,
    float battery,
    String motorState,
    String gripperState) {

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

  HTTPClient http;

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

  JsonDocument doc;

  doc["device_id"] = "BOREBOT-01";
  doc["gas_raw"] = gas;
  doc["temperature"] = temperature;
  doc["humidity"] = humidity;
  doc["distance"] = distance;
  doc["battery"] = battery;
  doc["motor"] = motorState;
  doc["gripper"] = gripperState;

  String payload;
  serializeJson(doc, payload);

  int responseCode = http.POST(payload);

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

  http.end();
}

18. Wi-Fi Connection Code

void connectWiFi() {

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  Serial.print("Connecting");

  unsigned long start = millis();

  while (WiFi.status() != WL_CONNECTED &&
         millis() - start < 20000) {

    delay(500);
    Serial.print(".");
  }

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

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

  } else {

    Serial.println();
    Serial.println("WiFi connection failed");
  }
}

19. Motor Control Software

A safer starting point is dead-man control.

The robot should stop if command communication disappears.

#define M1_IN1 25
#define M1_IN2 26
#define M2_IN1 27
#define M2_IN2 14

unsigned long lastCommand = 0;

const unsigned long COMMAND_TIMEOUT = 1500;

void stopRobot() {

  digitalWrite(M1_IN1, LOW);
  digitalWrite(M1_IN2, LOW);

  digitalWrite(M2_IN1, LOW);
  digitalWrite(M2_IN2, LOW);
}

void forward() {

  digitalWrite(M1_IN1, HIGH);
  digitalWrite(M1_IN2, LOW);

  digitalWrite(M2_IN1, HIGH);
  digitalWrite(M2_IN2, LOW);

  lastCommand = millis();
}

void reverseRobot() {

  digitalWrite(M1_IN1, LOW);
  digitalWrite(M1_IN2, HIGH);

  digitalWrite(M2_IN1, LOW);
  digitalWrite(M2_IN2, HIGH);

  lastCommand = millis();
}

void turnLeft() {

  digitalWrite(M1_IN1, LOW);
  digitalWrite(M1_IN2, HIGH);

  digitalWrite(M2_IN1, HIGH);
  digitalWrite(M2_IN2, LOW);

  lastCommand = millis();
}

void turnRight() {

  digitalWrite(M1_IN1, HIGH);
  digitalWrite(M1_IN2, LOW);

  digitalWrite(M2_IN1, LOW);
  digitalWrite(M2_IN2, HIGH);

  lastCommand = millis();
}

Then:

void safetyLoop() {

  if (millis() - lastCommand > COMMAND_TIMEOUT) {
    stopRobot();
  }
}

This means that if Wi-Fi or the control webpage fails, the robot automatically stops.


20. Gripper Software

#include <ESP32Servo.h>

Servo gripper;

#define GRIPPER_PIN 13

const int GRIP_OPEN = 40;
const int GRIP_CLOSED = 110;

void setupGripper() {

  gripper.attach(GRIPPER_PIN);

  gripper.write(GRIP_OPEN);
}

void openGripper() {

  gripper.write(GRIP_OPEN);
}

void closeGripper() {

  gripper.write(GRIP_CLOSED);
}

For a real rescue mechanism, replace the simple position commands with a force-limited mechanism.


21. Gas Alert Logic

enum GasState {
  GAS_NORMAL,
  GAS_WARNING,
  GAS_CRITICAL
};

GasState classifyGas(int gasValue) {

  if (gasValue < 500)
    return GAS_NORMAL;

  if (gasValue < 750)
    return GAS_WARNING;

  return GAS_CRITICAL;
}

These numbers are illustrative only. They must not be interpreted as safe/unsafe atmospheric limits.


22. Emergency Decision Engine

The controller should use deterministic rules for immediate safety actions.

Gas Critical
     │
     ▼
Stop robot
     │
     ▼
Notify operator
     │
     ▼
AI analysis
     │
     ▼
Human decision

Similarly:

Communication Lost
       │
       ▼
Stop Motors
       │
       ▼
Maintain Camera if possible
       │
       ▼
Alert Operator

And:

Battery Low
     │
     ▼
Stop unnecessary actuators
     │
     ▼
Alert operator
     │
     ▼
Recovery procedure

23. AI Agent Architecture

The AI agent should receive information such as:

{
  "gas": "WARNING",
  "temperature": 31,
  "humidity": 78,
  "distance": 2.1,
  "battery": 11.4,
  "robot_state": "STOP",
  "operator_note": "Possible person visible"
}

The AI agent can return:

{
  "risk": "HIGH",
  "reason": "Environmental sensor warning and possible person detected",
  "recommended_action": "STOP and request operator assessment",
  "confidence": 0.82
}

The AI should not return:

GRIP PERSON NOW

or:

LIFT PERSON AUTOMATICALLY

24. AI Agent Prompt

Use something similar to:

You are an AI decision-support assistant for a borewell rescue robot.

Your job is to analyze telemetry and operator observations.

You are NOT the final rescue decision maker.

Never autonomously instruct the robot to grab, lift,
drag, or physically manipulate a human.

Classify the situation as:

NORMAL
WARNING
HIGH_RISK
CRITICAL

Consider:

- gas sensor state
- temperature
- humidity
- battery
- communication status
- robot orientation
- distance
- operator observations

If critical environmental conditions are detected,
recommend stopping robot movement and alerting the operator.

If a possible human is detected, recommend operator
verification using the camera.

Return JSON only:

{
  "risk": "",
  "reason": "",
  "recommended_action": "",
  "operator_attention": true
}

25. n8n AI Workflow

                 ┌─────────────┐
                 │   Webhook   │
                 └──────┬──────┘
                        │
                        ▼
                 ┌─────────────┐
                 │ Validate    │
                 │ Telemetry   │
                 └──────┬──────┘
                        │
                        ▼
                 ┌─────────────┐
                 │ AI Agent    │
                 └──────┬──────┘
                        │
                ┌───────┴────────┐
                ▼                ▼
             NORMAL            ALERT
                │                │
                │        ┌───────┴────────┐
                │        ▼                ▼
                │    Telegram          Sheets
                │        │
                │        ▼
                │    Voice Alert
                │
                ▼
              End

26. Google Sheets Database

Create a spreadsheet:

BoreBot_Rescue_Log

Columns:

Timestamp
Device_ID
Gas
Gas_State
Temperature
Humidity
Distance
Battery
Motor
Gripper
Robot_State
AI_Risk
AI_Recommendation
Alert_Sent
Operator
Notes

Example:

Timestamp Gas Temp Distance Battery Risk
22:10:01 421 30.2 1.5 12.1 NORMAL
22:10:11 620 30.7 1.6 12.0 WARNING
22:10:21 810 31.1 1.6 11.9 CRITICAL

27. ThingSpeak Configuration

Create a ThingSpeak channel.

Suggested fields:

Field 1 = Gas
Field 2 = Temperature
Field 3 = Humidity
Field 4 = Distance
Field 5 = Battery
Field 6 = Robot State
Field 7 = AI Risk
Field 8 = Communication

ThingSpeak supports channel updates through REST HTTP GET/POST requests.

Example:

https://api.thingspeak.com/update.json

POST:

api_key=YOUR_WRITE_API_KEY
field1=742
field2=31.2
field3=77.4
field4=1.82
field5=11.7

ThingSpeak documents the channel Write API Key as the credential used to update channel data.


28. ESP32 ThingSpeak Code

#include <HTTPClient.h>

const char* TS_URL =
  "https://api.thingspeak.com/update";

const char* TS_KEY =
  "YOUR_THINGSPEAK_WRITE_KEY";

void sendThingSpeak(
    int gas,
    float temperature,
    float humidity,
    float distance,
    float battery) {

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

  HTTPClient http;

  http.begin(TS_URL);

  http.addHeader(
      "Content-Type",
      "application/x-www-form-urlencoded");

  String data =
      "api_key=" + String(TS_KEY) +
      "&field1=" + String(gas) +
      "&field2=" + String(temperature, 2) +
      "&field3=" + String(humidity, 2) +
      "&field4=" + String(distance, 2) +
      "&field5=" + String(battery, 2);

  int response = http.POST(data);

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

  http.end();
}

ThingSpeak's documentation specifies application/x-www-form-urlencoded for normal POST updates and documents update.json for JSON responses.


29. Telegram Alert System

n8n can use its built-in Telegram integration to send messages and other media.

Example normal alert:

🤖 BOREBOT STATUS

Device: BOREBOT-01
Depth: 4.2 m

Gas: NORMAL
Temperature: 30.4°C
Humidity: 74%
Battery: 11.8 V

Robot: STOP
Gripper: OPEN

AI Risk: NORMAL

Critical alert:

🚨 BOREBORE RESCUE ALERT

Device: BOREBOT-01

⚠️ Environmental warning detected.

Gas state: CRITICAL
Temperature: 31.4°C
Battery: 11.5 V

Robot has been commanded to STOP.

Operator assessment required.

30. Telegram Voice Alert

Telegram's current Bot API supports sendVoice; voice messages can use supported formats including OGG/Opus, MP3 or M4A.

The architecture is:

ESP32
  │
  ▼
n8n
  │
  ▼
AI Agent
  │
  ▼
Generate alert text
  │
  ▼
Text-to-Speech
  │
  ▼
Audio file
  │
  ▼
Telegram sendVoice
  │
  ▼
Operator's phone

Example spoken message:

"Emergency alert. BoreBot has detected a critical environmental sensor condition. The robot has stopped. Please assess the camera feed and rescue conditions."

The actual voice-generation provider can be selected separately; n8n handles the automation.


31. Telegram Command Interface

The operator could send:

/status

Response:

Robot: ONLINE
Battery: 11.9 V
Gas: NORMAL
Temperature: 30.1 C
Depth: 3.8 m
Gripper: OPEN
Motor: STOP

Commands:

/status
/stop
/light_on
/light_off
/grip_open
/grip_stop
/camera

Movement should preferably remain under a dedicated authenticated control interface rather than unrestricted Telegram text commands.


32. Web Control Page

The ESP32 can host a local control webpage.

Concept:

┌──────────────────────────────────────────────┐
│          BOREBOT RESCUE CONTROL              │
├──────────────────────────────────────────────┤
│                                              │
│              LIVE CAMERA                     │
│                                              │
│           ┌───────────────┐                  │
│           │               │                  │
│           │    CAMERA     │                  │
│           │               │                  │
│           └───────────────┘                  │
│                                              │
├──────────────────────────────────────────────┤
│ GAS       : NORMAL                           │
│ TEMP      : 30.5 °C                          │
│ HUMIDITY  : 74 %                             │
│ DISTANCE  : 2.43 m                           │
│ BATTERY   : 11.8 V                           │
├──────────────────────────────────────────────┤
│                                              │
│             [ FORWARD ]                      │
│                                              │
│ [ LEFT ] [ STOP ] [ RIGHT ]                  │
│                                              │
│             [ REVERSE ]                      │
│                                              │
│ [ GRIP OPEN ] [ GRIP STOP ] [ GRIP CLOSE ]  │
│                                              │
└──────────────────────────────────────────────┘

33. ESP32 Web Server Example

#include <WebServer.h>

WebServer server(80);

void handleRoot() {

  String html = R"rawliteral(

<!DOCTYPE html>
<html>

<head>
<title>BoreBot Control</title>

<style>

body {
  background:#111;
  color:white;
  font-family:Arial;
  text-align:center;
}

button {
  width:130px;
  height:55px;
  margin:8px;
  font-size:18px;
  border-radius:10px;
}

.stop {
  background:red;
  color:white;
}

</style>

</head>

<body>

<h1>🤖 BOREBOT</h1>

<h2>Rescue Robot Control</h2>

<div>
<img src="/stream"
     width="320">
</div>

<h3>Robot Movement</h3>

<button onclick="cmd('forward')">
FORWARD
</button>

<br>

<button onclick="cmd('left')">
LEFT
</button>

<button class="stop"
        onclick="cmd('stop')">
STOP
</button>

<button onclick="cmd('right')">
RIGHT
</button>

<br>

<button onclick="cmd('reverse')">
REVERSE
</button>

<h3>Gripper</h3>

<button onclick="cmd('open')">
OPEN
</button>

<button onclick="cmd('gripstop')">
STOP
</button>

<button onclick="cmd('close')">
CLOSE
</button>

<script>

function cmd(command) {

 fetch("/cmd?value=" + command);

}

</script>

</body>

</html>

)rawliteral";

  server.send(
      200,
      "text/html",
      html);
}

34. Command Handler

void handleCommand() {

  if (!server.hasArg("value")) {
    server.send(400, "text/plain", "Missing command");
    return;
  }

  String command = server.arg("value");

  if (command == "forward") {
    forward();
  }

  else if (command == "reverse") {
    reverseRobot();
  }

  else if (command == "left") {
    turnLeft();
  }

  else if (command == "right") {
    turnRight();
  }

  else if (command == "stop") {
    stopRobot();
  }

  else if (command == "open") {
    openGripper();
  }

  else if (command == "close") {
    closeGripper();
  }

  else if (command == "gripstop") {
    // For a production mechanism,
    // implement servo stop/hold logic.
  }

  server.send(
      200,
      "text/plain",
      "OK");
}

35. Main Setup

void setup() {

  Serial.begin(115200);

  pinMode(M1_IN1, OUTPUT);
  pinMode(M1_IN2, OUTPUT);
  pinMode(M2_IN1, OUTPUT);
  pinMode(M2_IN2, OUTPUT);

  stopRobot();

  setupGripper();

  connectWiFi();

  server.on("/", handleRoot);

  server.on("/cmd", handleCommand);

  server.begin();

  Serial.println("Web server started");
}

Loop:

void loop() {

  server.handleClient();

  safetyLoop();

  static unsigned long lastTelemetry = 0;

  if (millis() - lastTelemetry > 15000) {

    lastTelemetry = millis();

    int gas = analogRead(34);

    float temperature = 30.5;
    float humidity = 70.0;
    float distance = 2.0;
    float battery = 11.8;

    sendTelemetry(
        gas,
        temperature,
        humidity,
        distance,
        battery,
        "STOP",
        "OPEN");

    sendThingSpeak(
        gas,
        temperature,
        humidity,
        distance,
        battery);
  }
}

36. ESP32-CAM Video Architecture

The ESP32-CAM should be responsible primarily for:

Camera
  │
  ▼
Image acquisition
  │
  ▼
JPEG frames
  │
  ▼
HTTP stream
  │
  ▼
Operator webpage

The ESP32 Arduino ecosystem provides camera/web/network functionality, but exact camera pin definitions depend on the board/module variant. The current ESP32 documentation should therefore be used together with the exact ESP32-CAM board schematic.

For an AI-capable version, a better architecture is:

ESP32-CAM
      │
      │ JPEG
      ▼
n8n / AI Server
      │
      ▼
Computer Vision Model
      │
      ▼
"Possible human/person visible"
      │
      ▼
Human operator verification

Do not make the AI detection directly operate the gripper.


37. AI Computer Vision

The camera image can be analyzed by an external AI vision model.

Possible pipeline:

Camera
   │
   ▼
JPEG
   │
   ▼
AI Vision Model
   │
   ├── Person detected
   ├── No person detected
   ├── Low visibility
   └── Unknown
          │
          ▼
      n8n AI Agent
          │
          ▼
      Telegram

Example AI response:

{
  "person_visible": true,
  "confidence": 0.87,
  "visibility": "low",
  "recommended_action": "Operator verification required"
}

Again, the AI output should never directly trigger gripping.


38. Complete n8n Automation

A strong implementation can use several workflows.

Workflow A — Telemetry

ESP32
  ↓
Webhook
  ↓
Validate
  ↓
Google Sheets
  ↓
ThingSpeak

Workflow B — AI Analysis

Telemetry
  ↓
AI Agent
  ↓
Risk classification
  ↓
Decision

Workflow C — Emergency

AI Risk
   ↓
IF HIGH/CRITICAL
   ↓
Telegram Message
   ↓
Text-to-Speech
   ↓
Telegram Voice

Workflow D — Operator Commands

Telegram
   ↓
Command Parser
   ↓
Authorization
   ↓
n8n
   ↓
ESP32 Command Webhook
   ↓
ESP32

Workflow E — Logging

Every event
    ↓
Google Sheets

39. n8n Master Architecture

                           ┌───────────────┐
                           │ ESP32-CAM     │
                           │ Video         │
                           └───────┬───────┘
                                   │
                                   ▼
                              Operator UI
                                   │
                                   │
ESP32 Sensors ──────► n8n Webhook ◄──── Operator
                         │
                         ▼
                    Data Validation
                         │
              ┌──────────┼───────────┐
              ▼          ▼           ▼
          ThingSpeak  Sheets      AI Agent
                                      │
                         ┌────────────┴─────────┐
                         ▼                      ▼
                     NORMAL                  CRITICAL
                         │                      │
                         │                Telegram
                         │                      │
                         │                 Text-to-Speech
                         │                      │
                         │                Telegram Voice
                         │
                         ▼
                       LOG

40. AI Agent Decision Matrix

Condition AI classification Immediate robot action
Sensors normal NORMAL Continue operator control
Sensor warning WARNING Notify operator
Critical gas reading CRITICAL Stop movement
Communication lost CRITICAL Stop motors
Battery critically low HIGH Stop/recover
Possible person visible HIGH Operator verification
Camera obscured WARNING Operator assessment
Robot tilted excessively HIGH Stop movement
Gripper obstruction HIGH Stop gripper

41. Safety State Machine

The robot should have explicit states:

BOOT
  │
  ▼
SELF_TEST
  │
  ▼
READY
  │
  ▼
REMOTE_CONTROL
  │
  ├───────────────┐
  │               │
  ▼               ▼
WARNING         EMERGENCY
  │               │
  ▼               ▼
LIMITED         STOP
CONTROL           │
                  ▼
               RECOVERY

Software should not allow:

EMERGENCY → automatic movement

Instead:

EMERGENCY
    ↓
STOP
    ↓
Operator verification
    ↓
Manual reset
    ↓
READY

42. Emergency Stop Circuit

Do not rely exclusively on software.

A physical emergency-stop arrangement should be approximately:

BATTERY
  │
  ▼
FUSE
  │
  ▼
EMERGENCY STOP
  │
  ├────────► Motor power
  │
  └────────► Controller power

Depending on the design, the emergency stop can remove motor power while maintaining enough controller power for communication/telemetry.

A professional design should use an appropriately rated safety circuit rather than a hobby pushbutton directly carrying motor current.


43. Power Architecture

Example:

12V Battery
     │
     ├── Fuse
     │
     ├── Emergency Stop
     │
     ├────────► Motor Driver
     │
     └────────► Buck Converter
                    │
                    ├── 5V ESP32-CAM
                    ├── 5V Servo
                    └── 5V Sensors

Do not connect a random 12-V battery directly to an ESP32.


44. Battery Monitoring

Use a voltage divider:

Battery +
   │
  R1
   │
   ├──── ESP32 ADC
   │
  R2
   │
  GND

For example:

float readBatteryVoltage() {

  int adc = analogRead(35);

  float voltage =
      ((float)adc / 4095.0) * 3.3;

  // Replace with your actual divider ratio.
  voltage *= 4.0;

  return voltage;
}

The divider ratio must be calculated according to the actual resistors.


45. Data Flow

A complete telemetry cycle:

1. Sensor reads gas
       ↓
2. ESP32 reads temperature
       ↓
3. ESP32 reads distance
       ↓
4. ESP32 reads battery
       ↓
5. ESP32 creates JSON
       ↓
6. HTTP POST to n8n
       ↓
7. n8n validates
       ↓
8. Google Sheets logs
       ↓
9. ThingSpeak updates
       ↓
10. AI Agent analyzes
       ↓
11. Risk calculated
       ↓
12. If critical:
       ↓
13. Telegram alert
       ↓
14. TTS
       ↓
15. Telegram voice

46. Example Telemetry JSON

{
  "device_id": "BOREBOT-01",
  "gas_raw": 823,
  "gas_state": "CRITICAL",
  "temperature": 31.7,
  "humidity": 81.4,
  "distance": 4.27,
  "battery": 11.62,
  "tilt": 6.3,
  "motor": "STOP",
  "gripper": "OPEN",
  "camera": "ONLINE",
  "wifi": -61
}

47. AI Response

{
  "risk": "CRITICAL",
  "reason": "Environmental sensor indicates a potentially hazardous condition.",
  "recommended_action": "Keep motors stopped and request operator assessment.",
  "operator_attention": true
}

48. Google Sheets Event

2026-08-22 22:47:12
BOREBOT-01
823
CRITICAL
31.7
81.4
4.27
11.62
STOP
OPEN
CRITICAL
Keep motors stopped
YES

49. Telegram Notification

🚨 BOREBOT CRITICAL ALERT

Robot: BOREBOT-01

Gas: CRITICAL
Depth/Distance: 4.27 m
Temperature: 31.7°C
Humidity: 81.4%
Battery: 11.62 V

Robot status:
🛑 STOPPED

AI recommendation:
Keep motors stopped and request operator assessment.

⚠️ Human operator decision required.

50. Operator Dashboard

A complete dashboard should display:

┌───────────────────────────────────────────┐
│             BOREBOT AI RESCUE             │
├───────────────────────────────────────────┤
│ CAMERA                                    │
│                                           │
│          [ LIVE VIDEO ]                    │
│                                           │
├───────────────────────────────────────────┤
│ GAS             CRITICAL 🔴               │
│ TEMPERATURE     31.7 °C                   │
│ HUMIDITY        81.4 %                    │
│ DISTANCE        4.27 m                    │
│ BATTERY         11.62 V                   │
│ WIFI            -61 dBm                   │
├───────────────────────────────────────────┤
│ AI RISK        CRITICAL 🔴                │
│                                           │
│ Recommendation:                           │
│ KEEP ROBOT STOPPED                        │
├───────────────────────────────────────────┤
│       [FORWARD]                            │
│                                           │
│ [LEFT] [STOP] [RIGHT]                     │
│                                           │
│       [REVERSE]                            │
├───────────────────────────────────────────┤
│ GRIPPER                                    │
│ [OPEN] [STOP] [CLOSE]                     │
└───────────────────────────────────────────┘

51. Recommended Software Stack

Firmware
├── Arduino IDE
├── Arduino ESP32 Core
├── WiFi
├── HTTPClient
├── WebServer
├── ESP32Servo
└── ArduinoJson

Video
├── ESP32-CAM
└── OV2640

Automation
└── n8n

AI
└── n8n AI Agent + chosen AI model

Cloud
├── ThingSpeak
└── Google Sheets

Alerts
└── Telegram Bot

Voice
└── Text-to-Speech → Telegram

52. Arduino IDE Setup

Install the ESP32 board support using the Arduino IDE board-manager method described in Espressif's current installation documentation.

Then select the correct ESP32 board.

Install libraries:

ArduinoJson
ESP32Servo
DHT sensor library
Adafruit Unified Sensor
Adafruit VL53L0X
Adafruit MPU6050

The exact sensor libraries depend on the hardware you finally choose.


53. Testing Procedure

Do not start testing with a person in a borewell.

Use this progression:

Test 1 — Electronics

Power
 ↓
ESP32
 ↓
Sensors

Verify every voltage.

Test 2 — Motors

Raise the robot off the ground.

Test:

FORWARD
REVERSE
LEFT
RIGHT
STOP

Test 3 — Dead-Man Safety

Disconnect Wi-Fi.

Expected:

Wi-Fi lost
     ↓
Timeout
     ↓
Motors STOP

Test 4 — Gripper

Use an inert test object.

OPEN
 ↓
CLOSE
 ↓
STOP

Test 5 — Gas Sensor

Use controlled laboratory calibration procedures rather than unknown hazardous gases.

Test 6 — Webpage

Verify:

Camera
Sensors
Movement
Stop
Gripper

Test 7 — n8n

Send test JSON:

{
  "device_id": "TEST",
  "gas_raw": 100,
  "temperature": 25,
  "humidity": 50,
  "distance": 1,
  "battery": 12
}

Test 8 — Telegram

Confirm:

normal message
warning message
critical message
voice alert

Test 9 — Cloud

Confirm:

Google Sheets ✓
ThingSpeak ✓

Test 10 — Integrated Robot

Only after all individual systems have passed testing.


54. Fault Testing

Intentionally test:

Wi-Fi failure
n8n failure
ThingSpeak failure
Telegram failure
camera failure
gas sensor failure
distance sensor failure
low battery
motor driver failure
servo failure
ESP32 reset

The most important behavior is:

UNKNOWN CONDITION
       ↓
SAFE STATE
       ↓
STOP
       ↓
ALERT

55. Security

Never hard-code credentials into publicly uploaded source code.

Avoid:

const char* password = "MyPassword123";

in a public GitHub repository.

Use:

Wi-Fi credentials
n8n authentication
Telegram Bot Token
ThingSpeak Write API Key
AI API Key

as secrets.

The n8n Webhook node supports authentication options such as Basic Auth, Header Auth and JWT, so an authenticated webhook is preferable to an unrestricted public endpoint.


56. Recommended n8n Security

Use:

ESP32
  │
  │ HTTPS
  ▼
n8n Webhook
  │
  │ Header authentication
  ▼
Validate device token
  │
  ▼
Process

For example:

X-DEVICE-TOKEN:
YOUR_SECRET_DEVICE_TOKEN

Then n8n checks:

IF token valid
    ↓
process
ELSE
    ↓
reject

57. AI Agentic Behavior

The word agentic should mean that the AI can coordinate information and workflows, not that it has unrestricted physical control.

A safe agentic architecture is:

              ┌───────────────┐
              │ Sensor Data   │
              └───────┬───────┘
                      │
                      ▼
                ┌───────────┐
                │ AI Agent  │
                └─────┬─────┘
                      │
             ┌────────┼────────┐
             ▼        ▼        ▼
          Analyze    Log     Alert
             │        │        │
             └────────┼────────┘
                      ▼
                Human Operator
                      │
                 Authorizes
                      │
                      ▼
                    Robot

This is substantially safer than:

AI
 ↓
AUTONOMOUS GRIP
 ↓
PERSON

58. Complete Project Flow

                    START
                      │
                      ▼
                Power ON Robot
                      │
                      ▼
                  Self Test
                      │
             ┌────────┴────────┐
             │                 │
          PASS               FAIL
             │                 │
             ▼                 ▼
           READY              STOP
             │
             ▼
        Connect Wi-Fi
             │
             ▼
       Connect n8n
             │
             ▼
       Start Camera
             │
             ▼
       Read Sensors
             │
             ▼
      Send Telemetry
             │
             ▼
        AI Analysis
             │
       ┌─────┴─────┐
       │           │
     SAFE        RISK
       │           │
       ▼           ▼
 Operator       Alert
 Control          │
       │           ▼
       │       Robot STOP
       │           │
       └─────┬─────┘
             ▼
          Recovery

59. Complete Project Folder Structure

BoreBot/
│
├── firmware/
│   ├── borebot_main.ino
│   ├── config.h
│   ├── sensors.cpp
│   ├── sensors.h
│   ├── motors.cpp
│   ├── motors.h
│   ├── gripper.cpp
│   ├── gripper.h
│   ├── telemetry.cpp
│   ├── telemetry.h
│   └── safety.cpp
│
├── esp32cam/
│   └── camera_server.ino
│
├── n8n/
│   ├── telemetry-workflow.json
│   ├── alert-workflow.json
│   └── command-workflow.json
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── script.js
│
├── docs/
│   ├── block-diagram.png
│   ├── circuit-diagram.png
│   ├── flowchart.png
│   └── project-report.md
│
└── README.md

60. Suggested Project Report Chapters

For an academic/project submission, structure the documentation as:

Chapter 1  Introduction
Chapter 2  Problem Statement
Chapter 3  Existing System
Chapter 4  Proposed System
Chapter 5  Objectives
Chapter 6  System Architecture
Chapter 7  Hardware Requirements
Chapter 8  Software Requirements
Chapter 9  Circuit Design
Chapter 10 Mechanical Design
Chapter 11 ESP32 Firmware
Chapter 12 ESP32-CAM
Chapter 13 IoT Architecture
Chapter 14 n8n Automation
Chapter 15 AI Agent
Chapter 16 Telegram Integration
Chapter 17 Google Sheets
Chapter 18 ThingSpeak
Chapter 19 Web Dashboard
Chapter 20 Safety System
Chapter 21 Testing
Chapter 22 Results
Chapter 23 Advantages
Chapter 24 Limitations
Chapter 25 Future Scope
Chapter 26 Conclusion

61. Advantages

  • Remote operation.
  • Live camera monitoring.
  • Environmental monitoring.
  • Cloud telemetry.
  • Automated logging.
  • Instant Telegram notifications.
  • Voice alerts.
  • AI-assisted risk assessment.
  • Web-based control.
  • Modular architecture.
  • Low-cost prototype platform.
  • n8n makes the automation workflow easy to modify.

62. Limitations

  • ESP32-CAM image quality is limited compared with professional inspection cameras.
  • Wi-Fi may not work reliably deep underground.
  • Gas sensor readings require calibration.
  • Hobby motors are not rescue-rated.
  • Servo grippers are not suitable for lifting humans.
  • AI vision can produce false positives/negatives.
  • Borewell geometry varies significantly.
  • Radio communication can be blocked by soil/concrete.
  • A prototype cannot replace professional rescue equipment.

63. Future Enhancements

The next-generation version could include:

ESP32-CAM
     +
Thermal camera
     +
Professional gas detector
     +
Oxygen sensor
     +
Depth encoder
     +
IMU
     +
Load cell
     +
Motor encoders
     +
Tether communication
     +
Edge AI
     +
Computer vision
     +
Cloud dashboard
     +
AI agent

Additional improvements:

  • ROS 2 integration.
  • Raspberry Pi/Jetson companion computer.
  • Thermal imaging.
  • Computer-vision victim detection.
  • SLAM where feasible.
  • Motor current monitoring.
  • Force-limited gripper.
  • Redundant communications.
  • Industrial emergency-stop circuitry.
  • Professional tether system.

64. Key External Documentation

For implementation, the most useful current references are:

  • — current ESP32 Arduino documentation.
  • — webhook configuration, authentication and production/test behavior.
  • — Telegram automation operations.
  • — spreadsheet logging/automation.
  • — channel data REST API.
  • — bot messaging and voice-message API.

65. Final System in One Diagram

                         ┌─────────────────────┐
                         │      OPERATOR       │
                         │ Mobile / PC         │
                         └──────────┬──────────┘
                                    │
                           Web + Telegram
                                    │
                  ┌─────────────────▼─────────────────┐
                  │                n8n                 │
                  │                                    │
                  │ Webhook                            │
                  │    │                               │
                  │    ▼                               │
                  │ Data Validation                    │
                  │    │                               │
                  │    ├────► Google Sheets            │
                  │    │                               │
                  │    ├────► ThingSpeak               │
                  │    │                               │
                  │    ▼                               │
                  │ AI Agent                            │
                  │    │                               │
                  │    ├────► Risk Analysis            │
                  │    ├────► Telegram                 │
                  │    └────► Voice Alert              │
                  └───────────────┬────────────────────┘
                                  │
                                HTTPS
                                  │
                 ┌────────────────▼────────────────┐
                 │          ESP32 MAIN             │
                 │                                 │
                 │ Gas ────────────────┐           │
                 │ Temperature ────────┤           │
                 │ Humidity ────────────┤           │
                 │ Distance ────────────┤           │
                 │ Battery ─────────────┤           │
                 │ IMU ─────────────────┤           │
                 │                      ▼           │
                 │                  CONTROLLER      │
                 │                      │           │
                 │              ┌───────┼───────┐   │
                 │              ▼       ▼       ▼   │
                 │           Motors  Gripper   LED  │
                 └──────────────────────────────────┘
                                  │
                                  │
                 ┌────────────────▼────────────────┐
                 │          ESP32-CAM              │
                 │                                 │
                 │ OV2640 Camera                   │
                 │ Live JPEG Stream                │
                 │ Illumination                    │
                 └─────────────────────────────────┘

The most important design decision is to keep the architecture “AI-assisted + human-authorized,” with deterministic hardware safety controls. The AI/n8n layer can analyze, log, prioritize and alert; the ESP32 safety layer controls stop conditions; and the human operator remains responsible for physical rescue decisions.

For ThingSpeak, REST is appropriate for ordinary channel updates, while ThingSpeak also provides MQTT for publish/subscribe scenarios.