This is a comprehensive, multi-layered IoT and AI project combining robotics, edge-computing, cloud data logging, and automated alert systems.
Below is the complete step-by-step documentation, architecture, and code required to build the AI Autonomous Fire Fighting Robot with Air Pollution Monitoring System.
1. Full Project Description
This system functions as an autonomous, self-navigating rover that simultaneously monitors environmental health and serves as an active fire suppression unit.
The core is an ESP32 Microcontroller. While navigating (using ultrasonic sensors to avoid obstacles), it constantly reads data from an MQ-135 Gas Sensor to track air pollution (CO2, Smoke, AQI) and an AMG8833 Thermal Camera to scan for anomalous heat signatures.
The AI & Agentic Workflow:
-
Edge AI / Logic: The ESP32 evaluates thermal arrays. If a cluster of pixels exceeds 60°C (140°F), it classifies the event as a fire, halts navigation, targets the heat source, and activates a water pump via a relay.
-
Data Logging: Telemetry (AQI, Temperature, Battery/Power consumption) is pushed continuously to a ThingSpeak Cloud Dashboard.
-
Agentic Automation (n8n): Upon detecting a fire or critical pollution levels, the ESP32 triggers a webhook on an n8n Automation Server.
-
Notifications & Logs: n8n acts as the agent. It logs the exact event timestamp and sensor readings into Google Sheets for historical tracking, and simultaneously pushes a Telegram Voice Notification (using a Text-to-Speech API integration) to alert human operators instantly.
2. Components List
Hardware Components
-
ESP32 WROOM-32 (Main Microcontroller with WiFi)
-
AMG8833 IR Thermal Camera Breakout (8x8 grid heat detection)
-
MQ-135 Air Quality Sensor (Detects NH3, NOx, Alcohol, Benzene, smoke, CO2)
-
L298N Motor Driver Module (Controls chassis movement)
-
4x DC Gear Motors & Smart Car Chassis
-
HC-SR04 Ultrasonic Sensor (Obstacle avoidance)
-
5V Relay Module & Mini Submersible Water Pump
-
2x 18650 Li-ion Batteries & Battery Holder (Power supply)
Software & Cloud Services
-
Arduino IDE (C++ programming)
-
n8n (Self-hosted or Cloud for workflow automation)
-
Telegram (BotFather for creating the bot)
-
Google Sheets API (via Google Cloud Console)
-
ThingSpeak (MathWorks IoT Analytics dashboard)
3. Circuit Schematic Connections
| Component | ESP32 Pin | Notes |
|---|---|---|
| AMG8833 Thermal | GPIO 21 (SDA), GPIO 22 (SCL) | I2C Communication. Needs 3.3V power. |
| MQ-135 Gas Sensor | GPIO 34 (Analog In) | Needs 5V power. Keep away from water pump. |
| HC-SR04 Ultrasonic | GPIO 5 (Trig), GPIO 18 (Echo) | Needs 5V. Use voltage divider for Echo to ESP32 (3.3V limit). |
| L298N Motor Driver | GPIO 12 (IN1), 14 (IN2), 27 (IN3), 26 (IN4) | Power L298N directly from batteries. |
| 5V Relay (Pump) | GPIO 33 | Active HIGH to trigger the water pump. |
4. System Flowchart
graph TD
A[Power On System] --> B[Initialize WiFi & Sensors]
B --> C[Read AMG8833 Thermal Array]
B --> D[Read MQ135 AQI Level]
D --> E[Push Data to ThingSpeak]
C --> F{Max Temp > 60°C?}
F -- YES (Fire Detected) --> G[Stop Motors]
G --> H[Activate Relay/Water Pump]
H --> I[Trigger n8n Webhook: FIRE ALERT]
I --> J[n8n: Log to Google Sheets]
I --> K[n8n: Generate TTS & Send Telegram Voice Alert]
F -- NO --> L[Read Ultrasonic Sensor]
L --> M{Obstacle < 15cm?}
M -- YES --> N[Turn Left/Right]
M -- NO --> O[Move Forward]
N --> C
O --> C
5. Software & Cloud Setup
A. Telegram Bot Setup
-
Open Telegram and search for @BotFather.
-
Send
/newbot, give it a name and username. -
Save the HTTP API Token.
-
Start a chat with your bot and send a test message. Get your Chat ID using
api.telegram.org/bot<TOKEN>/getUpdates.
B. ThingSpeak Dashboard
-
Create an account at thingspeak.com and click New Channel.
-
Name it "Robot Telemetry". Enable Field 1 (Max Temp) and Field 2 (Air Quality).
-
Go to the API Keys tab and copy your Write API Key.
C. n8n Automation & Google Sheets
-
Create a Google Sheet named "Robot Logs" with columns:
Timestamp,Event,Severity,Value. -
In n8n, create a new workflow.
-
Add a Webhook node (Method: POST, Respond: Immediately). Copy the Webhook URL.
-
Add a Google Sheets node connected to the Webhook to append a row with the incoming data.
-
Add an HTTP Request node to call a free TTS service (like VoiceRSS or ElevenLabs) to convert the text "Fire Detected" into an audio file.
-
Add a Telegram node (Action: Send Audio/Voice) to push the generated audio file to your Chat ID.
n8n Workflow JSON Snippet
You can import this foundational structure into your n8n instance:
{
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "robot-alert",
"options": {}
},
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"typeVersion": 1,
"position": [250, 300],
"webhookId": "your-webhook-uuid"
},
{
"parameters": {
"operation": "append",
"documentId": {
"__rl": true,
"value": "your-google-sheet-id",
"mode": "id"
},
"sheetName": {
"__rl": true,
"value": "Sheet1",
"mode": "list"
},
"columns": {
"mappingMode": "defineBelow",
"value": {
"Event": "={{$json.body.event}}",
"Value": "={{$json.body.value}}"
}
}
},
"name": "Google Sheets",
"type": "n8n-nodes-base.googleSheets",
"position": [500, 200]
},
{
"parameters": {
"chatId": "your-chat-id",
"text": "=ALERT! {{$json.body.event}}. Value: {{$json.body.value}}",
"additionalFields": {}
},
"name": "Telegram",
"type": "n8n-nodes-base.telegram",
"position": [500, 400]
}
],
"connections": {
"Webhook": {
"main": [
[
{ "node": "Google Sheets", "type": "main", "index": 0 },
{ "node": "Telegram", "type": "main", "index": 0 }
]
]
}
}
}
6. ESP32 Source Code
This sketch handles WiFi, I2C thermal scanning, analog air quality reading, and triggers the n8n webhook upon critical events.
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_AMG88xx.h>
// --- Configuration ---
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
String n8n_Webhook = "http://YOUR_N8N_URL/webhook/robot-alert";
String thingSpeak_URL = "http://api.thingspeak.com/update?api_key=YOUR_WRITE_KEY";
// --- Pins ---
#define MQ135_PIN 34
#define RELAY_PIN 33
#define IN1 12
#define IN2 14
#define IN3 27
#define IN4 26
Adafruit_AMG88xx amg;
float pixels[AMG88xx_PIXEL_ARRAY_SIZE];
unsigned long lastCloudUpdate = 0;
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
if (!amg.begin()) {
Serial.println("Could not find AMG8833 sensor!");
while (1) delay(10);
}
}
void loop() {
// 1. Read Air Quality
int aqiValue = analogRead(MQ135_PIN);
// 2. Read Thermal Camera
amg.readPixels(pixels);
float maxTemp = 0;
for(int i = 1; i <= AMG88xx_PIXEL_ARRAY_SIZE; i++){
if(pixels[i-1] > maxTemp) maxTemp = pixels[i-1];
}
// 3. AI / Logic Agent Evaluation
if(maxTemp > 60.0) {
stopRobot();
digitalWrite(RELAY_PIN, HIGH); // Turn on water pump
triggern8nAlert("FIRE_DETECTED", maxTemp);
delay(5000); // Pump water for 5 seconds
digitalWrite(RELAY_PIN, LOW);
} else if (aqiValue > 2000) {
triggern8nAlert("HIGH_POLLUTION", aqiValue);
delay(5000); // Prevent spamming
} else {
moveForward(); // Proceed with autonomous patrol
}
// 4. Update Cloud Dashboard (every 15 seconds)
if(millis() - lastCloudUpdate > 15000) {
updateThingSpeak(maxTemp, aqiValue);
lastCloudUpdate = millis();
}
delay(100);
}
// --- Movement Functions ---
void moveForward() {
digitalWrite(IN1, HIGH); digitalWrite(IN2, LOW);
digitalWrite(IN3, HIGH); digitalWrite(IN4, LOW);
}
void stopRobot() {
digitalWrite(IN1, LOW); digitalWrite(IN2, LOW);
digitalWrite(IN3, LOW); digitalWrite(IN4, LOW);
}
// --- Network Functions ---
void triggern8nAlert(String event, float value) {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
http.begin(n8n_Webhook);
http.addHeader("Content-Type", "application/json");
String payload = "{\"event\":\"" + event + "\", \"value\":\"" + String(value) + "\"}";
http.POST(payload);
http.end();
}
}
void updateThingSpeak(float temp, int aqi) {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
String url = thingSpeak_URL + "&field1=" + String(temp) + "&field2=" + String(aqi);
http.begin(url);
http.GET();
http.end();
}
}
7. AI Power Consumption Prediction Logic
To implement AI power consumption and predictive maintenance without overloading the ESP32, the system utilizes a Cloud-Edge hybrid approach:
-
Edge Telemetry: The ESP32 reads the battery voltage via a voltage divider connected to an ADC pin and sends the voltage drop rate along with motor active time to ThingSpeak.
-
n8n Agentic Processing: n8n pulls the ThingSpeak data via an HTTP Request node on a cron schedule (e.g., every hour).
-
Prediction: n8n sends this historical data to an OpenAI API node or a local Python ML script (Linear Regression). The AI calculates the slope of battery degradation against motor strain.
-
Action: If the AI predicts the battery will die before the robot completes its patrol route, n8n sends a proactive Telegram message: "Prediction Alert: Battery will deplete in 12 minutes. Return to base recommended."
8. Future Enhancements & Deployment Guide
Deployment Constraints:
-
Thermal Isolation: The AMG8833 must be mounted away from the ESP32's WiFi antenna, as the antenna generates heat that can skew thermal readings.
-
Waterproofing: The L298N and ESP32 must be housed in an IP65+ rated acrylic enclosure to prevent damage when the water pump activates.
Future Upgrades:
-
Computer Vision: Upgrading from the ESP32 to an ESP32-CAM or Raspberry Pi to use OpenCV for visual fire confirmation (checking for the color and shape of flames) alongside the thermal data to reduce false positives.
-
SLAM Navigation: Integrating a LIDAR module for precise indoor mapping, allowing the robot to transmit its exact coordinate coordinates via Telegram when a fire is found.























