Friday, 9 October 2026

AI Real-Time Air Quality Monitoring & Forecasting System

AI Real-Time Air Quality Monitoring & Forecasting System using ESP32, IoT, n8n and Agentic AI

Complete project documentation • Hardware design • Circuit schematic • ESP32 firmware • AI forecasting • n8n workflows • Telegram voice alerts • Google Sheets • ThingSpeak dashboard

This project is an end-to-end smart environmental monitoring system that measures air pollution in real time, sends sensor data to the cloud, predicts possible air-quality deterioration, and automatically alerts users through Telegram—including voice notifications—using an ESP32, n8n automation, and an AI agent.

Air Quality Monitoring System (AQMS) - Hackster.io
Sniffer Air Quality (AQI) Monitor using ESP32 + PMSA003 + BME680 - Bootloader Blog
IoT-Based Environmental Monitoring System | project

1. Project overview

The system combines five major functions:

  • Sensing: Collect air-quality, temperature, and humidity measurements from connected sensors.

  • IoT monitoring: Transmit readings from the ESP32 to ThingSpeak and Google Sheets.

  • AI forecasting: Analyze recent measurements and estimate whether air quality may deteriorate.

  • Agentic automation: Use n8n to evaluate conditions, coordinate AI analysis, and trigger appropriate actions.

  • Intelligent alerts: Send Telegram text and voice alerts when dangerous or abnormal conditions are detected.

The intended result is a live air-quality monitoring webpage and a connected automation system that works with minimal manual intervention.

Project capabilities

Real-time monitoring

Sensor readings and historical trends

AI forecasting

Predicted trends and risk assessment

n8n automation

Rules, decisions and scheduled workflows

Telegram voice alerts

Automated audio notifications and text

2. System architecture

The overall data flow is:

Air and environmental conditions

Particulate matter, gases, temperature, humidity

Sensor layer

PM2.5/PM10 sensor + optional gas sensor + temperature/humidity sensor

ESP32 microcontroller

Read, validate, timestamp and transmit measurements

Wi-Fi and HTTP / HTTPS

Secure data transmission to cloud services

n8n automation engine

Receive data, evaluate rules, call AI, log results and dispatch alerts

ThingSpeak

Live charts and trends

Google Sheets

Historical records

AI forecasting

Future risk estimate

Telegram

Text and audio alerts

The live webpage can read a backend API or ThingSpeak data; it need not connect directly to the ESP32.

End-to-end operating sequence

  1. Sensors sample the air.

  2. The ESP32 reads the measurements and checks that the values are valid.

  3. The ESP32 transmits the data to the cloud at a configured interval.

  4. n8n receives the data and checks for threshold violations, missing readings, and sensor faults.

  5. An AI model evaluates trends and forecasts future air-quality risk.

  6. n8n stores measurements and analysis results in Google Sheets and, where configured, ThingSpeak.

  7. If an alert condition is met, n8n sends a Telegram message and optionally generates and delivers a voice message.

  8. The dashboard displays current conditions, historical measurements, and forecast results.

The system should use deterministic safety rules for urgent alerts. The AI agent provides additional interpretation and forecasting rather than being the sole authority on whether a critical alert is sent.

3. Hardware components required

Use a particulate-matter sensor as the primary air-pollution measurement device. A gas sensor alone is not sufficient to measure PM2.5 or PM10.

GitHub - TronixLab/DOIT_ESP32_DevKit-v1_30P · GitHub

1. ESP32 DevKit V1

Required

The controller reads sensors, connects to Wi-Fi, and uploads readings to cloud services.

Czujnik pyłu/czystości powietrza PM1.0 / PM2.5 / PM10 - PMS5003 - 5V UART Sklep Botland

2. PMS5003 particulate-matter sensor

Recommended

Measures PM1.0, PM2.5 and PM10 estimates. Communicates through UART serial.

Buy DHT 22 Module Online In India. Hyderabad

3. DHT22 temperature/humidity sensor

Provides environmental context for the air-quality readings and forecasting model.

MQ-135 Air Quality Gas Sensor Module | eBay

4. MQ-135 gas sensor (optional)

Provides a gas-sensitive analog signal. Requires warm-up and calibration; do not interpret raw ADC values as accurate ppm measurements.

KEYESTUDIO Starter Kit with 3.3V 5V Breadboard Power Module, 830 points Breadboard kit, 65pcs Jumper Wire for Arduino MEGA2560 R3 - BigaMart

5. Supporting components

Breadboard or PCB, jumper wires, suitable regulated power supply, and level shifting or voltage-divider components where needed.

Estimated project budget

These are indicative planning estimates in Indian rupees, not live quotations.

Component

Estimated cost

ESP32 development board

₹400–900

PMS5003 particulate sensor

₹1,200–2,500

DHT22 sensor

₹150–350

Optional MQ-135 module

₹100–250

Wiring, PCB and power components

₹300–800

Estimated total

₹2,150–4,800

Cloud hosting, an AI API, and voice-generation services may add costs depending on usage. A free or self-hosted n8n setup may reduce some expenses.

4. Circuit schematic and wiring

The following schematic uses the ESP32, PMS5003 and DHT22. The MQ-135 is optional.

【ESP32】PMS5003で空気中の粒子状物質を測定してみた #IoT - Qiita

Pin connection table

Example pin assignment for a classic ESP32 DevKit V1. Confirm the pinout and voltage requirements of your exact sensor modules before powering them.

Sensor pin

ESP32 connection

Purpose

PMS5003 VCC

Suitable regulated supply, typically 5 V

Sensor power

PMS5003 GND

GND

Common ground

PMS5003 TX

GPIO 16 (RX2)

ESP32 receives sensor data

PMS5003 RX

GPIO 17 (TX2), optional

ESP32 sends sensor commands

DHT22 VCC

3.3 V for a compatible module

Sensor power

DHT22 GND

GND

Common ground

DHT22 DATA

GPIO 4

Digital readings

MQ-135 AO, optional

GPIO 34 through a suitable voltage divider

Analog reading

Important electrical precautions

  • Check the PMS5003 model's supply requirements and ensure its UART signal voltage is safe for the ESP32.

  • The ESP32 GPIO inputs are not 5 V tolerant. Never connect a 5 V analog output directly to GPIO 34.

  • A bare DHT22 generally needs a pull-up resistor on its data line; many breakout modules already include one.

  • MQ-135 modules can have analog outputs approaching their supply voltage. Use a properly designed divider and check the maximum voltage under all conditions.

  • Use a stable supply and common ground. Do not power a sensor heater or other high-current load from an ESP32 GPIO.

5. Software and cloud services

Install or create these components before programming the device.

Software/service

Purpose

Arduino IDE

ESP32 firmware development

ESP32 Arduino core

Board support and Wi-Fi

Adafruit DHT sensor library

Temperature/humidity readings

ThingSpeak

Time-series charts and data storage

n8n

Workflow automation and AI orchestration

Google Sheets

Historical log and reports

Telegram Bot API

Text and audio notifications

AI model/API

Forecast explanation and risk assessment

Web dashboard

Live readings, trends, alerts and predictions

References: ESP32 Wi-Fi documentation , ThingSpeak write API , n8n documentation , n8n Telegram integration , and n8n Google Sheets integration .

— Arduino ESP32 latest documentation
+4

 

6. ESP32 firmware — complete starter implementation

This firmware is designed to:

  • Connect to Wi-Fi.

  • Read PM1.0, PM2.5 and PM10 from the PMS5003.

  • Read temperature and humidity from the DHT22.

  • Upload data to ThingSpeak.

  • Send a JSON payload to an n8n webhook.

  • Retry network connections and report basic errors through the serial monitor.

Step 1: Configure the Arduino IDE

  1. Install the ESP32 board package using Boards Manager.

  2. Select the correct ESP32 board and serial port.

  3. Install the DHT sensor library by Adafruit and its Adafruit Unified Sensor dependency.

  4. Connect the PMS5003 TX to ESP32 GPIO 16.

  5. Set the serial monitor to 115200 baud.

Step 2: Create a ThingSpeak channel

Create a channel with the following numeric fields:

  • Field 1: PM1.0 in µg/m³

  • Field 2: PM2.5 in µg/m³

  • Field 3: PM10 in µg/m³

  • Field 4: Temperature in °C

  • Field 5: Relative humidity in %

  • Field 6: Estimated AQI category code, if you implement a defined AQI calculation

Copy the channel's Write API Key. Keep it private.

Step 3: Create an n8n webhook

In n8n, create a workflow with a Webhook node configured as follows:

  • HTTP method: POST

  • Path: air-quality

  • Response mode: respond immediately or use a Respond to Webhook node

  • Expected body: JSON

Activate the workflow and copy its production webhook URL. For a deployed system, use an HTTPS URL.

Step 4: Upload this firmware

Replace the placeholder Wi-Fi credentials, ThingSpeak key and webhook URL before uploading.

cpp

#include <WiFi.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <DHT.h>

// ---------- USER CONFIGURATION ----------
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

const char* THINGSPEAK_WRITE_KEY = "YOUR_WRITE_API_KEY";

// Use your real HTTPS n8n production webhook URL.
const char* N8N_WEBHOOK_URL =
  "https://YOUR_N8N_HOST/webhook/air-quality";

// ---------- HARDWARE ----------
#define PMS_RX 16
#define PMS_TX 17
#define DHT_PIN 4
#define DHT_TYPE DHT22

HardwareSerial pmsSerial(2);
DHT dht(DHT_PIN, DHT_TYPE);

// ---------- DATA STRUCTURE ----------
struct PMData {
  uint16_t pm1;
  uint16_t pm25;
  uint16_t pm10;
};

unsigned long lastSample = 0;
const unsigned long SAMPLE_INTERVAL = 20000;

// Read one valid 32-byte PMS5003 frame.
// The atmospheric/environmental PM values are used.
bool readPMS(PMData &out) {
  static uint8_t frame[32];
  static size_t pos = 0;

  while (pmsSerial.available()) {
    uint8_t b = pmsSerial.read();

    if (pos == 0 && b != 0x42) continue;

    if (pos == 1 && b != 0x4D) {
      pos = (b == 0x42) ? 1 : 0;
      continue;
    }

    frame[pos++] = b;

    if (pos == 32) {
      pos = 0;

      uint16_t length =
        (uint16_t(frame[2]) << 8) | frame[3];

      uint16_t sum = 0;
      for (int i = 0; i < 30; i++) {
        sum += frame[i];
      }

      uint16_t received =
        (uint16_t(frame[30]) << 8) | frame[31];

      if (length != 28 || sum != received) {
        return false;
      }

      out.pm1 =
        (uint16_t(frame[10]) << 8) | frame[11];
      out.pm25 =
        (uint16_t(frame[12]) << 8) | frame[13];
      out.pm10 =
        (uint16_t(frame[14]) << 8) | frame[15];

      return true;
    }
  }

  return false;
}

bool ensureWiFi() {
  if (WiFi.status() == WL_CONNECTED) return true;

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  unsigned long start = millis();
  while (WiFi.status() != WL_CONNECTED &&
         millis() - start < 15000) {
    delay(250);
  }

  return WiFi.status() == WL_CONNECTED;
}

// Prototype helper: HTTPS with certificate verification disabled.
// Replace with CA certificate validation for deployment.
int httpsPostJson(const char* url, const String& body) {
  WiFiClientSecure client;
  client.setInsecure();  // Prototype only; not production-secure

  HTTPClient http;
  if (!http.begin(client, url)) return -1;

  http.setTimeout(10000);
  http.addHeader("Content-Type", "application/json");

  int code = http.POST(body);
  http.end();
  return code;
}

bool uploadThingSpeak(
  const PMData &pm, float temp, float humidity
) {
  if (!ensureWiFi()) return false;

  String url = "https://api.thingspeak.com/update?api_key=";
  url += THINGSPEAK_WRITE_KEY;
  url += "&field1=" + String(pm.pm1);
  url += "&field2=" + String(pm.pm25);
  url += "&field3=" + String(pm.pm10);
  url += "&field4=" + String(temp, 1);
  url += "&field5=" + String(humidity, 1);

  WiFiClientSecure client;
  client.setInsecure(); // Prototype only

  HTTPClient http;
  if (!http.begin(client, url)) return false;

  http.setTimeout(10000);
  int code = http.GET();
  String response = http.getString();
  http.end();

  // ThingSpeak normally returns a nonzero entry ID.
  response.trim();
  return code == HTTP_CODE_OK &&
         response.length() > 0 &&
         response != "0";
}

void sendToN8N(
  const PMData &pm, float temp, float humidity
) {
  String json = "{";
  json += "\"device_id\":\"esp32-air-01\",";
  json += "\"pm1\":" + String(pm.pm1) + ",";
  json += "\"pm25\":" + String(pm.pm25) + ",";
  json += "\"pm10\":" + String(pm.pm10) + ",";
  json += "\"temperature_c\":" + String(temp, 1) + ",";
  json += "\"humidity_pct\":" + String(humidity, 1);
  json += "}";

  int code = httpsPostJson(N8N_WEBHOOK_URL, json);

  Serial.print("n8n HTTP status: ");
  Serial.println(code);
}

void setup() {
  Serial.begin(115200);

  pmsSerial.begin(
    9600, SERIAL_8N1, PMS_RX, PMS_TX
  );

  dht.begin();

  WiFi.mode(WIFI_STA);
  ensureWiFi();

  Serial.println("Air quality monitor started.");
}

void loop() {
  if (millis() - lastSample < SAMPLE_INTERVAL) {
    delay(50);
    return;
  }

  lastSample = millis();

  PMData pm;
  if (!readPMS(pm)) {
    Serial.println(
      "No valid PMS5003 frame. Check wiring and sensor."
    );
    return;
  }

  float temp = dht.readTemperature();
  float humidity = dht.readHumidity();

  if (isnan(temp) || isnan(humidity)) {
    Serial.println("DHT22 read failed; skipping upload.");
    return;
  }

  Serial.printf(
    "PM1=%u, PM2.5=%u, PM10=%u, "
    "Temp=%.1f C, RH=%.1f%%\n",
    pm.pm1, pm.pm25, pm.pm10, temp, humidity
  );

  if (!ensureWiFi()) {
    Serial.println("Wi-Fi unavailable.");
    return;
  }

  bool tsOK = uploadThingSpeak(pm, temp, humidity);
  Serial.println(tsOK ?
    "ThingSpeak upload OK" :
    "ThingSpeak upload failed");

  sendToN8N(pm, temp, humidity);
}

Firmware notes

  • The firmware sends data every 20 seconds. Check your ThingSpeak account's write-rate restrictions and increase the interval if necessary.

  • The PMS5003 must have time to initialize and sample the air. In a production version, maintain a rolling sample buffer and use timeouts rather than depending on a fresh complete sensor frame arriving at the exact polling instant.

  • The setInsecure() calls disable TLS certificate verification. They are shown only to simplify a bench prototype. Use certificate validation before deployment.

  • The example intentionally does not publish a fabricated AQI number. Add a jurisdiction-specific AQI calculation before showing an AQI value.

  • If Wi-Fi fails, this basic implementation does not maintain a persistent offline queue. That can be added using flash storage or an SD card.

7. n8n automation workflow

n8n is the automation layer. It receives the sensor readings, stores them, checks thresholds, calls the AI model, and routes the correct alert to Telegram.

Workflow A — real-time sensor processing

mermaid

flowchart TD
    A[ESP32 POST sensor JSON] --> B[Webhook Trigger]
    B --> C[Validate required fields]
    C --> D{Valid payload?}
    D -- No --> E[Log invalid reading]
    D -- Yes --> F[Normalize units and timestamp]
    F --> G[Google Sheets: Append Row]
    F --> H[Evaluate PM thresholds]
    H --> I{Alert condition?}
    I -- No --> J[Store normal status]
    I -- Yes --> K[Create alert event]
    K --> L[Telegram text notification]
    K --> M[Voice message workflow]
    F --> N[Collect recent history]
    N --> O[AI forecast and explanation]
    O --> P[Store forecast result]
    P --> Q[Update dashboard data]

Step-by-step node configuration

Node 1 — Webhook

Set method to POST and path to air-quality. The input JSON should contain device_id, pm1, pm25, pm10, temperature_c and humidity_pct.

Use the production URL only after activating the workflow. The ESP32 firmware above sends this payload.

Node 2 — Validate and normalize

Use an Edit Fields (Set) node or Code node to validate numeric values, attach a timestamp, and reject malformed payloads. Do not silently replace missing sensor values with zero.

Node 3 — Google Sheets

Use the Google Sheets node with the Append Row operation. Map each field to the corresponding spreadsheet column.

Node 4 — IF / Switch

Compare the current PM2.5 reading against configured thresholds, or compare the reading against an applicable local AQI standard. Route normal and alert conditions separately.

Node 5 — AI forecast

Retrieve recent historical measurements, send the structured time series to a forecasting service or AI model, validate its output, and save the result. Use a Code node for mathematical forecasting if you want a reproducible baseline.

Node 6 — Telegram

Configure a Telegram bot credential and use Send Message for text alerts. Use Send Audio or Send Voice for audio delivery, depending on the generated file format and the operation supported by your n8n version.

Example data-validation Code node

Add a Code node after the Webhook node. This example expects the webhook body to be in $json.body and stops processing if any required measurement is invalid.

javascript

const input = $json.body ?? $json;

const fields = [
  "pm1",
  "pm25",
  "pm10",
  "temperature_c",
  "humidity_pct"
];

for (const field of fields) {
  if (
    input[field] === undefined ||
    input[field] === null ||
    !Number.isFinite(Number(input[field]))
  ) {
    throw new Error(`Invalid or missing field: ${field}`);
  }
}

const pm1 = Number(input.pm1);
const pm25 = Number(input.pm25);
const pm10 = Number(input.pm10);
const temp = Number(input.temperature_c);
const humidity = Number(input.humidity_pct);

if (
  pm1 < 0 || pm25 < 0 || pm10 < 0 ||
  humidity < 0 || humidity > 100 ||
  temp < -40 || temp > 85
) {
  throw new Error("Measurement outside configured limits");
}

return [{
  json: {
    device_id: String(input.device_id ?? "unknown"),
    timestamp: new Date().toISOString(),
    pm1,
    pm25,
    pm10,
    temperature_c: temp,
    humidity_pct: humidity
  }
}];

The limits above are data-validation limits, not health thresholds. Real deployments should also reject stale data, impossible sensor combinations, duplicate events, and persistent sensor faults.

8. AI agent and air-quality forecasting

A major project requirement is forecasting, not merely displaying current measurements. To achieve that, maintain a history of readings and use a forecasting method that has been evaluated against actual future measurements.

Three forecasting levels

Level 1 — Trend-based baseline

Compare the latest readings with recent rolling averages, calculate the rate of change, and flag rising pollution. This can run in an n8n Code node without an external AI API.

Level 2 — AI-assisted interpretation

Supply the latest measurements and historical summary to an AI model. Ask it to explain the trend, identify uncertainty, and produce a structured risk assessment. An LLM explanation alone is not a validated numerical forecast.

Level 3 — Trained predictive model

Train a regression or time-series model using historical PM2.5, PM10, temperature, humidity, time of day, and—if available—wind, rainfall and external weather observations. Predict future concentrations and measure error on held-out data.

Forecasting flowchart

mermaid

flowchart TD
    A[Historical sensor data] --> B[Remove invalid readings]
    B --> C[Resample into fixed time intervals]
    C --> D[Build time-series features]
    D --> E[Forecast PM2.5 and PM10]
    E --> F[Calculate prediction uncertainty]
    F --> G[Compare with configured thresholds]
    G --> H[AI generates plain-language explanation]
    H --> I[Store prediction and model version]
    I --> J[Dashboard and Telegram notification]
    J --> K[Compare forecast with later observation]
    K --> L[Calculate model error and improve model]

Example trend-based forecasting code

This is a baseline forecast, not a trained AI model. It predicts PM2.5 using the average change between successive readings. It should be replaced or benchmarked against a proper time-series model before making operational claims.

javascript

function forecastPM25(values, horizonSteps = 3) {
  if (
    values.length < 4 ||
    !values.every(v => Number.isFinite(v) && v >= 0)
  ) {
    throw new Error("At least four valid PM2.5 values required");
  }

  const last = values[values.length - 1];
  const recent = values.slice(-6);

  const differences = [];
  for (let i = 1; i < recent.length; i++) {
    differences.push(recent[i] - recent[i - 1]);
  }

  const meanChange =
    differences.reduce((a, b) => a + b, 0) /
    differences.length;

  const predicted = [];
  let current = last;

  for (let i = 0; i < horizonSteps; i++) {
    current = Math.max(0, current + meanChange);
    predicted.push(Number(current.toFixed(2)));
  }

  return {
    latest_pm25: last,
    mean_change_per_step: Number(meanChange.toFixed(2)),
    horizon_steps: horizonSteps,
    forecast_pm25: predicted,
    method: "recent_mean_difference_baseline"
  };
}

// Example only: replace with actual historical data.
const history = [18, 20, 21, 24, 27, 29];
return [{ json: forecastPM25(history, 3) }];

If readings are sampled every 20 seconds, three steps correspond to only one minute. For a meaningful 30-minute or 1-hour forecast, aggregate measurements into suitable time intervals and collect sufficient historical data.

Agentic AI decision logic

The agent should have defined responsibilities rather than unrestricted control.

AI agent tools

  1. Get latest readings: retrieve the current sensor measurements.

  2. Get history: retrieve the latest 30–100 valid time-series samples.

  3. Forecast pollution: invoke the baseline or trained forecasting service.

  4. Assess risk: compare the forecast against configured policy thresholds.

  5. Generate alert text: produce a concise explanation with values and uncertainty.

  6. Record the decision: save the model version, forecast horizon and action taken.

Example system instruction for the AI node:

text

You are an air-quality monitoring assistant.

Use only the sensor measurements, historical data,
and forecasts provided to you.

1. Summarize current PM2.5 and PM10 measurements.
2. Identify whether recent readings are rising, stable,
   or falling.
3. Explain the forecast horizon and uncertainty.
4. Never invent missing measurements or claim a forecast
   is a confirmed observation.
5. Do not calculate or invent a regulatory AQI category.
6. Return structured JSON with:
   status, trend, forecast_summary, uncertainty,
   recommended_precautions, and reason.
7. Safety-critical alerts are controlled by deterministic
   workflow rules, not by free-form AI decisions.

For an n8n AI Agent node, connect a chat-model node and the appropriate tools supported by your n8n version. If the forecasting tool returns numeric results, pass those results to the agent rather than asking the language model to guess the numbers.

9. AQI calculation and alert thresholds

PM2.5 concentration is not itself an AQI number. AQI depends on the relevant country's calculation method, pollutant breakpoints, averaging period, and rounding rules.

For an India-focused project, select and implement the applicable CPCB National Air Quality Index methodology. Do not label arbitrary PM2.5 thresholds as official Indian AQI categories.

Use two independent paths:

  • Measured-condition alerts: triggered from actual sensor measurements and the applicable rules.

  • Forecast alerts: triggered from predicted future conditions, clearly labeled as predictions.

For a prototype, you can use configurable engineering thresholds to test the automation. Mark them as test thresholds until you have implemented and verified the correct local standard.

A useful notification policy includes a persistence window, hysteresis, cooldown period, and sensor-fault detection. For example, require multiple consecutive valid samples before sending a non-emergency alert, but do not delay a required urgent alert because the AI service is unavailable.

10. Telegram text and voice notification system

This feature makes the project more interactive: when pollution rises or a forecast indicates elevated risk, the system can send a text message and a spoken audio alert.

Telegram setup

  1. Open Telegram and search for @BotFather.

  2. Send /newbot and follow the instructions.

  3. Save the bot token securely.

  4. Open your new bot and send it a message.

  5. Obtain the chat ID using the Telegram Bot API or an n8n Telegram Trigger node.

  6. In n8n, create Telegram credentials and configure the Send Message operation.

Never expose the bot token in frontend JavaScript, a public repository, or a shared spreadsheet.

Voice-alert workflow

mermaid

flowchart TD
    A[Alert event from n8n] --> B[Build alert text]
    B --> C[Text-to-Speech service]
    C --> D[Generate audio file]
    D --> E{Audio generated?}
    E -- Yes --> F[Telegram Send Voice or Audio]
    E -- No --> G[Send text-only fallback]
    F --> H[Log notification result]
    G --> H

The text-to-speech service can be a hosted provider or a self-hosted TTS engine. Configure its output format to match the Telegram operation. A voice message typically uses an appropriate OGG/Opus format; an audio file can use other supported formats.

Example alert message

Air Quality Monitor Bot

AIR QUALITY WARNING

PM2.5: 86 µg/m³

PM10: 124 µg/m³

Temperature: 32.1 °C

Humidity: 61%

Trend: Increasing over recent samples.

Forecast: Possible continued deterioration. Forecast confidence must be assessed using the deployed model.

Illustrative sample values, not live measurements.

Example spoken message:

Air quality warning. The latest PM2.5 reading is 86 micrograms per cubic meter. Recent measurements show an increasing trend. Please check the local air-quality advisory and consider appropriate precautions.

The voice message should distinguish measured readings from predicted values. If the TTS service fails, n8n must still send the text alert.

11. Google Sheets integration

Create a spreadsheet called Air_Quality_Monitoring.

Use the following column structure:

Column

Field

A

Timestamp

B

Device ID

C

PM1.0

D

PM2.5

E

PM10

F

Temperature °C

G

Humidity %

H

Measured AQI, if properly calculated

I

Forecast PM2.5

J

Forecast horizon

K

Alert status

L

Alert action

M

Model version

In n8n:

  1. Add a Google Sheets node after data validation.

  2. Authenticate using Google OAuth2 credentials.

  3. Select the spreadsheet and worksheet.

  4. Choose Append Row.

  5. Map the incoming values to the matching columns.

  6. Add another Append Row operation after forecasting to record the prediction and model metadata.

  7. Optionally create a separate Alert_Log worksheet to track notifications and delivery failures.

Avoid writing an entire row repeatedly for the same device and timestamp. Add a unique event identifier if you need reliable deduplication.

12. ThingSpeak IoT cloud dashboard

ThingSpeak provides time-series storage and charts. The ESP32 firmware sends PM1.0, PM2.5, PM10, temperature and humidity to the channel.

Measuring air quality with Raspberry Pi #4 - First measurements - element14 Community
pro2_plus_receiver - WeatherDuino WiKi
IoT Data Explorer for ThingSpeak and MATLAB - MATLAB & Simulink

Setup instructions

  1. Create a ThingSpeak account and channel.

  2. Enable the required fields.

  3. Copy the channel ID and Write API Key.

  4. Configure the firmware with the Write API Key.

  5. Upload the code and confirm that new entries appear.

  6. Create charts for PM2.5, PM10, temperature and humidity.

  7. Keep the channel private unless public access is intentional.

  8. Use a separate read key or controlled backend for any private dashboard integration.

Documentation: ThingSpeak channel data and charts .

Dashboard design

The web application should display:

Current PM2.5

Live value

µg/m³

PM10 trend

Time series

Historical readings

AI forecast

Future estimate

Show horizon and uncertainty

Alert status

Normal / Warning

Last notification event

13. Live IoT webpage implementation

A simple first version can use HTML, CSS and JavaScript. The following page is a frontend prototype with simulated readings. It does not connect to a real sensor until you replace the demo data source with a backend endpoint or ThingSpeak's read API.

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>AI Air Quality Monitor</title>
  <style>
    body {
      font-family: system-ui, sans-serif;
      max-width: 950px;
      margin: 30px auto;
      padding: 0 16px;
      background: #f4f7fb;
      color: #182230;
    }
    h1 { color: #155e75; }
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
      gap: 14px;
    }
    .card {
      background: white;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 2px 10px #0000000c;
    }
    .value { font-size: 30px; font-weight: 700; }
    .muted { color: #64748b; }
  </style>
</head>
<body>
  <h1>AI Air Quality Monitoring</h1>
  <p class="muted" id="updated">Demo mode — not live sensor data</p>

  <div class="grid">
    <div class="card">
      <div>PM2.5 (µg/m³)</div>
      <div class="value" id="pm25">--</div>
    </div>
    <div class="card">
      <div>PM10 (µg/m³)</div>
      <div class="value" id="pm10">--</div>
    </div>
    <div class="card">
      <div>Temperature (°C)</div>
      <div class="value" id="temp">--</div>
    </div>
    <div class="card">
      <div>Humidity (%)</div>
      <div class="value" id="humidity">--</div>
    </div>
  </div>

  <section class="card" style="margin-top:16px">
    <h2>System status</h2>
    <p id="status">Waiting for data</p>
    <p id="forecast">Forecast unavailable</p>
  </section>

  <script>
    // DEMO ONLY. Replace with a real backend request.
    const demo = {
      pm25: 24,
      pm10: 41,
      temp: 30.5,
      humidity: 58
    };

    function render(data) {
      document.getElementById("pm25").textContent = data.pm25;
      document.getElementById("pm10").textContent = data.pm10;
      document.getElementById("temp").textContent = data.temp;
      document.getElementById("humidity").textContent =
        data.humidity;

      document.getElementById("status").textContent =
        "Demo data — AQI category not calculated";

      document.getElementById("updated").textContent =
        "Updated: " + new Date().toLocaleString();

      document.getElementById("forecast").textContent =
        "No trained forecast model connected";
    }

    render(demo);

    // Production pattern:
    // fetch("/api/latest")
    //   .then(r => {
    //     if (!r.ok) throw new Error("API request failed");
    //     return r.json();
    //   })
    //   .then(render)
    //   .catch(() => {
    //     document.getElementById("status").textContent =
    //       "Unable to retrieve live sensor data";
    //   });
  </script>
</body>
</html>

Connecting the webpage to real data

For a production implementation, create a backend endpoint such as /api/latest that reads the most recent sensor record from ThingSpeak or a database. The webpage calls that endpoint periodically.

Recommended production architecture:

  • ESP32 → ThingSpeak and/or n8n webhook.

  • n8n → historical database and Google Sheets.

  • Forecast service → prediction results.

  • Web backend → latest readings, forecasts and alerts.

  • Web frontend → charts, status cards and historical trends.

Do not place private API keys in the webpage's JavaScript. If the ThingSpeak channel is private, use a backend to read it and protect the credentials.

14. Complete workflow map

This is the final combined project architecture.

mermaid

flowchart TB
    subgraph DEVICE["Hardware layer"]
        A[PMS5003]
        B[DHT22]
        C[ESP32]
        A --> C
        B --> C
    end

    subgraph CLOUD["Cloud and automation"]
        D[HTTPS telemetry]
        E[n8n Webhook]
        F[Validation and rules]
        G[Google Sheets]
        H[ThingSpeak]
        I[Forecast model]
        J[AI interpretation]
        K[Telegram text]
        L[Text to speech]
        M[Telegram voice]
    end

    subgraph UI["User interface"]
        N[Live webpage]
        O[Historical charts]
        P[Forecast and alert panel]
    end

    C --> D
    D --> E
    C --> H
    E --> F
    F --> G
    F --> I
    I --> J
    F --> K
    F --> L
    L --> M
    H --> N
    G --> O
    I --> P
    J --> P
    K --> P

15. Testing and validation plan

Do not consider the project complete until each part has been tested independently.

Project test checklist

0 of 12

Reset checklist

Forecast evaluation

Use chronological train/test separation rather than randomly mixing time-series records. Record at least these metrics:

  • MAE: mean absolute error of PM2.5 predictions.

  • RMSE: root mean squared error.

  • Forecast bias: whether the model systematically overpredicts or underpredicts pollution.

  • Alert performance: false alarms, missed events, and time between an event and its notification.

A low-cost sensor is useful for educational and indicative monitoring, but it should not automatically be treated as a regulatory-grade instrument. Compare it with a suitable reference monitor and follow the sensor manufacturer's operating requirements. The US EPA explains the importance of evaluating low-cost air sensors against reference measurements.

US EPA
+1

 

16. Security, reliability and limitations

For a deployment beyond a classroom prototype:

  • Use HTTPS with certificate verification.

  • Protect API keys and bot credentials using environment variables or a secrets manager.

  • Authenticate the n8n webhook, and validate the device identity.

  • Add a persistent offline queue and retry mechanism.

  • Store a timestamp and device ID with every observation.

  • Detect sensor disconnection and stale readings.

  • Add alert cooldowns and event deduplication.

  • Keep urgent threshold-based alerts independent of the AI API.

  • Back up n8n workflows and historical data.

  • Show a visible sensor-data timestamp and forecast uncertainty on the webpage.

Also remember that temperature, humidity and particulate concentration alone may not be sufficient to forecast outdoor air quality accurately. Weather, local emissions, traffic, seasonal effects and nearby sources can matter considerably.

17. Final project deliverables

The finished project should contain these deliverables:

Deliverable

Contents

Hardware prototype

ESP32, PMS5003, DHT22 and optional gas sensor

Circuit documentation

Pin map, wiring diagram and electrical precautions

Firmware

Wi-Fi, sensor parsing, cloud uploads and error handling

n8n workflows

Ingestion, validation, logging, forecasting and alerts

AI forecasting

Baseline model, trained model if available, and evaluation results

Telegram bot

Text alerts and voice notifications

Cloud storage

ThingSpeak channel and Google Sheets log

Web application

Live values, historical charts and forecast panel

Final report

Architecture, implementation, testing and limitations

Suggested report title

“AI-Powered Real-Time Air Quality Monitoring and Forecasting System Using ESP32, Agentic AI, n8n Automation, ThingSpeak, Google Sheets and Telegram Voice Notifications.”

This is a practical design for an academic or prototype project. The firmware and dashboard snippets provide a starting implementation; the full production system still requires configured credentials, a working n8n instance, a text-to-speech service, and a tested forecasting pipeline.

 

## Project Summary

AI-Powered Real-Time Air Quality Monitoring and Forecasting System Using ESP32, IoT, Agentic AI, n8n Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak

This project develops an intelligent IoT system that monitors air quality in real time, forecasts potential pollution trends, and automatically notifies users when air quality deteriorates.

The ESP32 microcontroller collects environmental measurements using a PMS5003 particulate-matter sensor and a DHT22 temperature and humidity sensor. It transmits the data through Wi-Fi to ThingSpeak for cloud monitoring and to n8n for automated processing.

The n8n workflow validates sensor readings, stores historical data in Google Sheets, evaluates alert conditions, and connects to an AI model for forecasting and natural-language explanations. When configured thresholds are exceeded, the system sends Telegram text notifications and voice alerts using a text-to-speech service.

A web dashboard displays current sensor readings, historical trends, forecasts, and alert status.

### Main components

- Hardware: ESP32, PMS5003, DHT22, optional MQ-135 gas sensor.
- IoT cloud: ThingSpeak for sensor data visualization.
- Automation: n8n workflows for data processing and notifications.
- Artificial intelligence: Trend analysis, pollution forecasting and risk explanations.
- Communication: Telegram text and voice alerts.
- Data storage: Google Sheets for historical records.
- Web application: Real-time monitoring dashboard.

### System workflow

mermaid
```

flowchart TD
A[Air Quality Sensors] --> B[ESP32]
B --> C[Wi-Fi and Cloud Upload]
C --> D[ThingSpeak Dashboard]
C --> E[n8n Automation]
E --> F[Google Sheets]
E --> G[AI Forecasting]
G --> H[Risk Assessment]
H --> I[Telegram Text Alerts]
H --> J[Text-to-Speech]
J --> K[Telegram Voice Alerts]
D --> L[IoT Web Dashboard]
G --> L
```

### Expected outcomes

- Continuous air-quality data collection.
- Remote monitoring through a cloud dashboard.
- Early warnings of potentially deteriorating air quality.
- Automated text and voice notifications.
- Historical data analysis and forecast evaluation.
- Reduced need for manual monitoring.

Conclusion: The project integrates IoT hardware, cloud services, AI forecasting, and workflow automation into a unified environmental monitoring solution. It is suitable for an academic project, smart-city prototype, or environmental monitoring demonstration. Accurate forecasting and regulatory AQI reporting require validated models, appropriate sensor calibration, and the applicable official calculation methodology.

Thursday, 8 October 2026

IoT-Based Smart Greenhouse Monitoring and Automatic Control System Using ESP32

AI-Enabled IoT Greenhouse Using ESP32, n8n, Telegram, Google Sheets and ThingSpeak

1. Recommended project title

AI-Powered Agentic IoT Greenhouse Monitoring and Control System Using ESP32, n8n Automation, Telegram Voice Alerts, Google Sheets, and ThingSpeak

A shorter title for the cover page is:

Agentic IoT Greenhouse Automation Using ESP32 and n8n

2. Project abstract

This project presents an AI-powered greenhouse monitoring and control system based on an ESP32 microcontroller, IoT cloud services, n8n workflow automation, and Telegram voice notifications. The ESP32 collects real-time environmental data from temperature, humidity, soil-moisture, light, water-level, pH, and air-quality sensors. It controls a water pump, solenoid valve, ventilation fan, grow light, and warning buzzer according to configurable crop-management rules.

Sensor data is transmitted to an n8n webhook through Wi-Fi. n8n acts as the automation and orchestration layer: it validates and processes incoming data, stores records in Google Sheets, updates a ThingSpeak channel, evaluates abnormal conditions, and sends Telegram notifications. An AI agent can interpret sensor readings, summarize greenhouse conditions, recommend actions, and process authorized user commands. Text-to-speech can convert critical alerts into Telegram voice messages.

The architecture combines edge control on the ESP32 with cloud automation in n8n. Essential safety actions, such as stopping the pump when the water tank is empty, remain locally enforced on the ESP32 even if the internet or n8n service is unavailable.

n8n provides webhook triggers for receiving application events, Google Sheets integration for automated spreadsheet operations, and Telegram nodes for bot communication. ThingSpeak provides REST and MQTT interfaces for sending and visualizing live IoT data.[docs.n8n][docs.n8n][docs.n8n][se.mathworks]

3. System objectives

The project aims to:

  • Monitor greenhouse temperature and humidity.
  • Measure soil moisture and automate irrigation.
  • Measure light intensity and control supplementary grow lighting.
  • Detect low water level before dry-running the pump.
  • Monitor irrigation-water pH.
  • Detect air-quality changes using the MQ-135.
  • Display readings locally on an OLED.
  • Upload data to ThingSpeak.
  • Store historical readings in Google Sheets.
  • Send Telegram text alerts and voice alerts.
  • Provide an AI assistant for summaries and authorized control commands.
  • Maintain essential local safety control even during internet failure.

4. Overall architecture

┌───────────────────────────────────────────────────────────────┐
│                        GREENHOUSE                             │
│                                                               │
│ DHT22 │ Soil Sensor │ BH1750 │ Water Level │ pH │ MQ-135     │
│                                                               │
│                 ┌─────────────────────┐                       │
│                 │       ESP32         │                       │
│                 │ Local sensing       │                       │
│                 │ Safety decisions    │                       │
│                 │ Relay control       │                       │
│                 │ OLED display        │                       │
│                 └───────┬─────────────┘                       │
│                         │                                      │
│        ┌────────────────┼────────────────┐                     │
│        ▼                ▼                ▼                     │
│  4-Channel Relay     OLED             Buzzer                 │
│        │                                                      │
│        ▼                                                      │
│ Pump │ Valve │ Fan │ Grow Light                              │
└────────┬──────────────────────────────────────────────────────┘
         │ Wi-Fi / HTTPS
         ▼
┌──────────────────────────────┐
│        n8n AUTOMATION         │
│                              │
│ Webhook → Validate → Route   │
│      │        │        │     │
│      │        │        └─────┼──► Telegram text alert
│      │        │              └──► TTS → Telegram voice alert
│      │        └─────────────► AI Agent
│      ├──────────────────────► Google Sheets
│      └──────────────────────► ThingSpeak
└──────────────┬───────────────┘
               │
    ┌──────────┼───────────┐
    ▼          ▼           ▼
Google       ThingSpeak   Telegram
Sheets       Dashboard    Bot / AI Assistant

5. Functional layers

5.1 Edge layer

The ESP32 performs the time-critical operations:

  • Reads all connected sensors.
  • Converts raw ADC readings into engineering values.
  • Applies temperature, soil-moisture, light, and water-level thresholds.
  • Controls relays.
  • Displays local readings.
  • Activates the buzzer.
  • Sends JSON data to n8n.
  • Stops irrigation locally when the water tank is empty.

5.2 Automation layer

n8n receives the ESP32 JSON payload through an HTTPS webhook. A Webhook node can start an n8n workflow when data is received.[docs.n8n]

The workflow then:

  • Validates the API key and sensor payload.
  • Adds a timestamp.
  • Stores the reading in Google Sheets.
  • Sends sensor data to ThingSpeak.
  • Checks alert rules.
  • Calls an AI agent for interpretation when required.
  • Sends Telegram text or voice notifications.
  • Optionally sends an approved control command back to the ESP32.

5.3 Application layer

The user can access:

  • ThingSpeak charts for sensor history.
  • Google Sheets for records and analysis.
  • Telegram for alerts and commands.
  • An AI assistant for natural-language explanations.
  • The local OLED for operation without cloud access.

6. Hardware components

Component Function
ESP32 DevKit V1 Main controller and Wi-Fi communication
DHT22 Temperature and humidity measurement
Capacitive soil-moisture sensor Soil moisture measurement
BH1750 Digital light measurement in lux
Water-level sensor Tank-level detection
pH sensor module Irrigation-water pH monitoring
MQ-135 Indicative air-quality measurement
0.96-inch OLED Local display
4-channel relay module Switching pump, valve, fan, and light
12 V water pump Irrigation
12 V solenoid valve Water-flow control
12 V DC fan Ventilation
12 V LED grow light Supplemental lighting
Active buzzer Local warning
12 V, 5 A SMPS Main power source
LM2596 buck converter 12 V to regulated low voltage
Fuse and holder Power-circuit protection
Waterproof enclosure Protection from moisture

7. ESP32 pin configuration

Device ESP32 pin Interface
DHT22 data GPIO 4 Digital
Soil-moisture analog output GPIO 34 ADC
Water-level analog output GPIO 35 ADC
pH analog output GPIO 32 ADC
MQ-135 analog output GPIO 33 ADC
BH1750 SDA GPIO 21 I²C
OLED SDA GPIO 21 I²C
BH1750 SCL GPIO 22 I²C
OLED SCL GPIO 22 I²C
Relay fan GPIO 16 Digital
Relay pump GPIO 17 Digital
Relay valve GPIO 18 Digital
Relay grow light GPIO 19 Digital
Buzzer GPIO 23 Digital

The OLED and BH1750 can share the I²C bus because they normally use different addresses. Confirm the actual addresses with an I²C scanner.

8. Electrical schematic

                         AC MAINS
                            │
                      ┌─────▼─────┐
                      │ 12 V SMPS │
                      │ 5 A DC    │
                      └─────┬─────┘
                            │ +12 V
                         ┌──▼──┐
                         │Fuse │
                         └──┬──┘
                            │
              ┌─────────────┼──────────────────────────┐
              │             │                          │
              ▼             ▼                          ▼
        Water pump    Solenoid valve              12 V fan
              │             │                          │
              └─────────────┼──────────────────────────┘
                            │
                         Relay COM/NO
                            │
                 4-CHANNEL RELAY MODULE
                 ┌──────────┼──────────┐
                 │          │          │
              CH1 Fan     CH2 Pump   CH3 Valve
                 │
              CH4 Grow light

12 V SMPS ───────────────► LM2596 buck converter
                              │
                         Regulated 5 V
                              │
                   ┌──────────┼──────────┐
                   ▼          ▼          ▼
                 ESP32       OLED      Sensors

ESP32 GND ───────────────── Common GND

Electrical precautions

  • Never apply 12 V directly to an ESP32 power pin.
  • Ensure every analog sensor output remains within the ESP32 ADC input range.
  • Use a voltage divider or signal-conditioning circuit where necessary.
  • Use a common ground between the ESP32, sensors, buck converter, and relay control side.
  • Keep pump and actuator wiring separate from analog sensor wiring.
  • Use flyback protection where a discrete MOSFET driver is used.
  • Use an appropriately rated fuse close to the SMPS output.
  • Do not place exposed electronics in a wet greenhouse environment.
  • Avoid routing dangerous mains voltage onto a student-project PCB.

9. Data flow

1. Sensors measure environmental values.
2. ESP32 reads and filters the values.
3. ESP32 applies local control rules.
4. Relays switch the actuators.
5. ESP32 displays readings on the OLED.
6. ESP32 creates a JSON payload.
7. ESP32 sends the payload to n8n over HTTPS.
8. n8n validates and timestamps the payload.
9. n8n writes a row to Google Sheets.
10. n8n updates the ThingSpeak channel.
11. n8n checks alarm conditions.
12. n8n sends Telegram text or voice alerts.
13. AI agent summarizes data or handles authorized commands.

10. ESP32 control flowchart

┌──────────────┐
│    START     │
└──────┬───────┘
       ▼
┌─────────────────────────┐
│ Initialize ESP32, pins, │
│ sensors, OLED and Wi-Fi │
└──────────┬──────────────┘
           ▼
┌─────────────────────────┐
│ Read all sensors        │
└──────────┬──────────────┘
           ▼
┌─────────────────────────┐
│ Water level low?        │
└───────┬─────────┬───────┘
        │Yes      │No
        ▼         ▼
┌─────────────┐  ┌──────────────────────┐
│ Pump OFF    │  │ Soil moisture low?   │
│ Valve OFF   │  └──────┬───────────────┘
│ Alert ON    │         │Yes
└──────┬──────┘         ▼
       │         ┌─────────────┐
       │         │ Pump ON     │
       │         │ Valve ON    │
       │         └──────┬──────┘
       └───────────────┬┘
                       ▼
             ┌─────────────────────┐
             │ Temperature high?   │
             └──────┬──────────────┘
                    │Yes
                    ▼
             ┌─────────────┐
             │ Fan ON      │
             └──────┬──────┘
                    ▼
             ┌─────────────────────┐
             │ Light too low?      │
             └──────┬──────────────┘
                    │Yes
                    ▼
             ┌─────────────┐
             │ Light ON    │
             └──────┬──────┘
                    ▼
             ┌─────────────────────┐
             │ Check pH and MQ-135 │
             └──────┬──────────────┘
                    ▼
             ┌─────────────────────┐
             │ Update OLED and     │
             │ send JSON to n8n    │
             └──────┬──────────────┘
                    ▼
             ┌─────────────────────┐
             │ Repeat continuously │
             └─────────────────────┘

11. n8n workflow design

Workflow A: ESP32 telemetry and alert workflow

Webhook
   │
   ▼
API Key Validation
   │
   ▼
Set / Code: Normalize JSON
   │
   ├──────────────► Google Sheets: Append Row
   │
   ├──────────────► HTTP Request: ThingSpeak Update
   │
   ▼
Alert Evaluation
   │
   ├── No alert ─────► Webhook Response
   │
   └── Alert ────────► Build alert message
                            │
                 ┌──────────┴──────────┐
                 ▼                     ▼
           Telegram text          Text-to-Speech
                                       │
                                       ▼
                                Telegram voice message

Workflow B: Telegram AI assistant

Telegram Trigger
       │
       ▼
Message Type Router
       │
   ┌───┴────────┐
   ▼            ▼
Text         Voice
   │            │
   │       Download audio
   │            │
   │       Speech-to-text
   └──────┬─────┘
          ▼
      AI Agent
          │
   ┌──────┼─────────┐
   ▼      ▼         ▼
Read data  Explain  Request control
          │         │
          │    Authorization check
          │         │
          │    ESP32 command webhook
          ▼
Telegram response

n8n examples commonly use a Telegram trigger, a router that distinguishes text and voice, audio download, speech-to-text, and an AI response path.[n8n][n8n]

12. n8n node-by-node setup

Node 1: Webhook

Configure:

  • Method: POST
  • Path: greenhouse/telemetry
  • Response mode: respond immediately or through a Webhook Response node.
  • Authentication: preferably header authentication or a secret API key.
  • Production URL: use the active workflow URL.

Example endpoint:

https://YOUR_N8N_DOMAIN/webhook/greenhouse/telemetry

The n8n instance must be publicly reachable over HTTPS for external webhook services such as Telegram. Telegram supports only one webhook per bot, so avoid configuring the same bot in multiple competing workflows.[docs.n8n][docs.n8n]

Node 2: Code node for validation

Use this code in an n8n Code node:

const body = $json.body ?? $json;

const expectedKey = 'CHANGE_THIS_SECRET';
const receivedKey =
  body.api_key ??
  body.apiKey ??
  '';

if (receivedKey !== expectedKey) {
  throw new Error('Unauthorized greenhouse device');
}

const required = [
  'device_id',
  'temperature',
  'humidity',
  'soil_moisture',
  'light_lux',
  'water_level',
  'ph',
  'mq135'
];

for (const field of required) {
  if (body[field] === undefined || body[field] === null) {
    throw new Error(`Missing field: ${field}`);
  }
}

return [{
  json: {
    timestamp: new Date().toISOString(),
    device_id: String(body.device_id),
    temperature: Number(body.temperature),
    humidity: Number(body.humidity),
    soil_moisture: Number(body.soil_moisture),
    light_lux: Number(body.light_lux),
    water_level: Number(body.water_level),
    ph: Number(body.ph),
    mq135: Number(body.mq135),
    fan: Boolean(body.fan),
    pump: Boolean(body.pump),
    valve: Boolean(body.valve),
    grow_light: Boolean(body.grow_light),
    low_water: Boolean(body.low_water),
    ph_alert: Boolean(body.ph_alert),
    air_quality_alert: Boolean(body.air_quality_alert)
  }
}];

Node 3: Google Sheets

Create a spreadsheet with these columns:

timestamp
device_id
temperature
humidity
soil_moisture
light_lux
water_level
ph
mq135
fan
pump
valve
grow_light
low_water
ph_alert
air_quality_alert

Configure the Google Sheets node to:

  • Operation: Append Row.
  • Select the target spreadsheet and worksheet.
  • Map each incoming field to its matching column.

The Google Sheets node is intended for integrating n8n workflows with spreadsheet data and automated spreadsheet operations.[docs.n8n]

Node 4: ThingSpeak HTTP Request

ThingSpeak accepts REST API updates using GET or POST. A write API key and one or more field values are required.[mathworks][mathworks]

Configure an n8n HTTP Request node:

  • Method: GET or POST.
  • URL:
https://api.thingspeak.com/update.json
  • Query or body parameters:
api_key    = YOUR_THINGSPEAK_WRITE_API_KEY
field1     = {{$json.temperature}}
field2     = {{$json.humidity}}
field3     = {{$json.soil_moisture}}
field4     = {{$json.light_lux}}
field5     = {{$json.water_level}}
field6     = {{$json.ph}}
field7     = {{$json.mq135}}
field8     = {{$json.pump}}

Suggested ThingSpeak field mapping:

ThingSpeak field Value
Field 1 Temperature
Field 2 Humidity
Field 3 Soil moisture
Field 4 Light intensity
Field 5 Water level
Field 6 pH
Field 7 MQ-135
Field 8 Pump status

ThingSpeak is useful for live IoT visualization and historical channel data; its REST and MQTT interfaces support sending data from connected devices.[se.mathworks]

Node 5: Alert evaluation

Use an n8n IF or Code node:

const d = $json;

const alerts = [];

if (d.low_water || d.water_level < 500) {
  alerts.push('Water tank level is low. Irrigation has been stopped.');
}

if (d.ph < 5.5 || d.ph > 7.5) {
  alerts.push(`Water pH is outside the safe range: ${d.ph.toFixed(2)}.`);
}

if (d.temperature > 32) {
  alerts.push(`High temperature detected: ${d.temperature.toFixed(1)} °C.`);
}

if (d.mq135 > 2500) {
  alerts.push(`Air-quality threshold exceeded. MQ-135 value: ${d.mq135}.`);
}

return [{
  json: {
    ...d,
    alert: alerts.length > 0,
    alert_text: alerts.join('\n')
  }
}];

Node 6: Telegram text alert

Configure a Telegram node:

  • Resource: Message.
  • Operation: Send Message.
  • Chat ID: your Telegram chat ID.
  • Text:
🚨 Greenhouse Alert

Device: {{$json.device_id}}
Time: {{$json.timestamp}}

{{$json.alert_text}}

Temperature: {{$json.temperature}} °C
Humidity: {{$json.humidity}} %
Soil moisture: {{$json.soil_moisture}} %
pH: {{$json.ph}}
Pump: {{$json.pump ? 'ON' : 'OFF'}}

n8n’s Telegram integration supports Telegram bot operations, while Telegram bots require valid bot credentials and a correctly configured webhook when using trigger-based communication.[docs.n8n][docs.n8n]

Node 7: Telegram voice alert

A generic voice-alert path is:

Alert text
   │
   ▼
Text-to-Speech service
   │
   ▼
Binary audio file
   │
   ▼
Telegram Send Audio / Send Voice

The TTS service may be:

  • OpenAI text-to-speech.
  • Google Cloud Text-to-Speech.
  • Microsoft Azure Speech.
  • ElevenLabs.
  • Another compatible HTTP-based speech provider.

Use a short message for reliable voice alerts:

Greenhouse warning. The water tank level is low. Irrigation has been stopped.

The precise n8n node depends on the TTS provider. The project should not hard-code an API key into the workflow; store it in n8n credentials.

13. AI agent design

The AI agent should not directly control safety-critical hardware without restrictions. Its responsibilities should be:

  • Explain current greenhouse conditions.
  • Summarize daily or weekly sensor trends.
  • Identify abnormal readings.
  • Answer user questions.
  • Recommend actions.
  • Convert authorized commands into structured requests.
  • Avoid bypassing local ESP32 safety rules.

Recommended AI tools

  • get_latest_reading: reads the latest row from Google Sheets or a database.
  • get_history: reads recent values for trend analysis.
  • get_thingspeak_data: retrieves ThingSpeak data.
  • request_actuator_command: sends a command to an n8n command workflow.
  • send_alert: sends a Telegram alert.

AI system prompt

You are the Greenhouse Operations Agent.

Your responsibilities:
1. Explain greenhouse sensor readings in simple language.
2. Identify high temperature, low soil moisture, low tank level,
   abnormal pH, and air-quality warnings.
3. Use metric units.
4. Never invent sensor values.
5. Clearly distinguish measured values from recommendations.
6. Do not directly bypass ESP32 safety rules.
7. Never turn on the pump if the water tank is low.
8. Never override an emergency shutdown.
9. For actuator commands, request confirmation when appropriate.
10. Return control requests only as structured JSON.

Allowed structured command format:
{
  "action": "pump|fan|valve|grow_light",
  "state": "on|off",
  "reason": "short explanation"
}

Example Telegram conversations

User:
What is the current greenhouse condition?

AI:
Current readings:
Temperature: 31.4 °C
Humidity: 68 %
Soil moisture: 43 %
Light: 7,200 lux
pH: 6.4
Water tank: Normal

The temperature is approaching the fan threshold, but irrigation is not
currently required.
User:
Why did I receive an alert?

AI:
The alert was generated because the water tank level fell below the
configured safety threshold. The ESP32 stopped the pump and solenoid valve
to prevent dry running.
User:
Turn on the pump.

AI:
The pump command requires a safety check. Current water level is normal.
Do you confirm turning on the pump?

14. ESP32 software

The following code is a complete edge-controller example. It:

  • Reads all sensors.
  • Controls the four relays.
  • Uses hysteresis.
  • Displays values on the OLED.
  • Sends telemetry to n8n.
  • Keeps pump protection local.
  • Uses HTTPS for the n8n request.

Arduino libraries

Install:

  • DHT sensor library.
  • Adafruit Unified Sensor.
  • BH1750.
  • Adafruit GFX.
  • Adafruit SSD1306.

ESP32 code

/*
  AI-Enabled IoT Greenhouse Controller

  ESP32:
  - DHT22
  - Capacitive soil moisture
  - BH1750
  - Water-level sensor
  - pH sensor
  - MQ-135
  - OLED
  - Four relays
  - Buzzer
  - n8n HTTPS telemetry
*/

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <DHT.h>
#include <BH1750.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

/* ---------------- Wi-Fi and n8n ---------------- */

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

const char* N8N_WEBHOOK_URL =
  "https://YOUR_N8N_DOMAIN/webhook/greenhouse/telemetry";

const char* DEVICE_API_KEY = "CHANGE_THIS_SECRET";
const char* DEVICE_ID = "greenhouse-esp32-01";

/* ---------------- Sensor pins ---------------- */

#define DHT_PIN             4
#define DHT_TYPE            DHT22
#define SOIL_PIN            34
#define WATER_LEVEL_PIN     35
#define PH_PIN              32
#define MQ135_PIN           33

/* ---------------- I2C ---------------- */

#define SDA_PIN             21
#define SCL_PIN             22

/* ---------------- Relay and buzzer pins ---------------- */

#define RELAY_FAN_PIN       16
#define RELAY_PUMP_PIN      17
#define RELAY_VALVE_PIN     18
#define RELAY_LIGHT_PIN     19
#define BUZZER_PIN          23

/* Most relay boards are active LOW */
#define RELAY_ON            LOW
#define RELAY_OFF           HIGH

/* ---------------- OLED ---------------- */

#define OLED_WIDTH          128
#define OLED_HEIGHT         64
#define OLED_RESET          -1
#define OLED_ADDRESS        0x3C

/* ---------------- Thresholds ---------------- */

const float FAN_ON_TEMP       = 32.0;
const float FAN_OFF_TEMP      = 29.0;

const int PUMP_ON_SOIL        = 40;
const int PUMP_OFF_SOIL       = 60;

const float LIGHT_ON_LUX      = 8000.0;
const float LIGHT_OFF_LUX     = 12000.0;

const int LOW_WATER_ADC       = 500;

const float PH_MINIMUM        = 5.5;
const float PH_MAXIMUM        = 7.5;

const int MQ135_LIMIT         = 2500;

/* ---------------- Calibration ---------------- */

const int DRY_SOIL_ADC        = 3200;
const int WET_SOIL_ADC        = 1300;

const float PH_SLOPE          = 3.5;
const float PH_OFFSET         = 0.5;

/* ---------------- Timing ---------------- */

const unsigned long READ_INTERVAL = 2000;
const unsigned long SEND_INTERVAL = 10000;

unsigned long lastRead = 0;
unsigned long lastSend = 0;

/* ---------------- Objects ---------------- */

DHT dht(DHT_PIN, DHT_TYPE);
BH1750 bh1750;

Adafruit_SSD1306 display(
  OLED_WIDTH,
  OLED_HEIGHT,
  &Wire,
  OLED_RESET
);

/* ---------------- Readings ---------------- */

float temperature = 0.0;
float humidity = 0.0;
float lightLux = 0.0;
float phValue = 0.0;

int soilMoisture = 0;
int waterLevel = 0;
int mq135 = 0;

/* ---------------- States ---------------- */

bool fanOn = false;
bool pumpOn = false;
bool valveOn = false;
bool growLightOn = false;

bool lowWater = false;
bool phAlert = false;
bool airQualityAlert = false;

/* ========================================================= */

void setRelay(uint8_t pin, bool state) {
  digitalWrite(pin, state ? RELAY_ON : RELAY_OFF);
}

void setFan(bool state) {
  fanOn = state;
  setRelay(RELAY_FAN_PIN, state);
}

void setPump(bool state) {
  pumpOn = state;
  setRelay(RELAY_PUMP_PIN, state);
}

void setValve(bool state) {
  valveOn = state;
  setRelay(RELAY_VALVE_PIN, state);
}

void setGrowLight(bool state) {
  growLightOn = state;
  setRelay(RELAY_LIGHT_PIN, state);
}

void setBuzzer(bool state) {
  digitalWrite(BUZZER_PIN, state ? HIGH : LOW);
}

/* ========================================================= */

int soilPercentFromADC(int value) {
  value = constrain(value, WET_SOIL_ADC, DRY_SOIL_ADC);

  int percent = map(
    value,
    DRY_SOIL_ADC,
    WET_SOIL_ADC,
    0,
    100
  );

  return constrain(percent, 0, 100);
}

/* ========================================================= */

float phFromADC(int value) {
  float voltage = (value * 3.3) / 4095.0;
  return (PH_SLOPE * voltage) + PH_OFFSET;
}

/* ========================================================= */

void readSensors() {
  float t = dht.readTemperature();
  float h = dht.readHumidity();

  if (!isnan(t)) {
    temperature = t;
  }

  if (!isnan(h)) {
    humidity = h;
  }

  int soilADC = analogRead(SOIL_PIN);
  soilMoisture = soilPercentFromADC(soilADC);

  lightLux = bh1750.readLightLevel();

  waterLevel = analogRead(WATER_LEVEL_PIN);

  int phADC = analogRead(PH_PIN);
  phValue = phFromADC(phADC);

  mq135 = analogRead(MQ135_PIN);
}

/* ========================================================= */

void applyAutomation() {
  /*
    Low-water protection has priority over every irrigation request.
  */
  lowWater = waterLevel < LOW_WATER_ADC;

  if (lowWater) {
    setPump(false);
    setValve(false);
  }
  else {
    if (soilMoisture < PUMP_ON_SOIL) {
      setPump(true);
      setValve(true);
    }
    else if (soilMoisture >= PUMP_OFF_SOIL) {
      setPump(false);
      setValve(false);
    }
  }

  /*
    Fan hysteresis.
  */
  if (temperature >= FAN_ON_TEMP) {
    setFan(true);
  }
  else if (temperature <= FAN_OFF_TEMP) {
    setFan(false);
  }

  /*
    Grow-light hysteresis.
  */
  if (lightLux < LIGHT_ON_LUX) {
    setGrowLight(true);
  }
  else if (lightLux >= LIGHT_OFF_LUX) {
    setGrowLight(false);
  }

  phAlert =
    phValue < PH_MINIMUM ||
    phValue > PH_MAXIMUM;

  airQualityAlert =
    mq135 > MQ135_LIMIT;

  setBuzzer(
    lowWater ||
    phAlert ||
    airQualityAlert
  );
}

/* ========================================================= */

void updateOLED() {
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);

  display.setCursor(0, 0);
  display.println("AI GREENHOUSE");

  display.print("T:");
  display.print(temperature, 1);
  display.print("C H:");
  display.print(humidity, 0);
  display.println("%");

  display.print("Soil:");
  display.print(soilMoisture);
  display.println("%");

  display.print("Lux:");
  display.println(lightLux, 0);

  display.print("pH:");
  display.print(phValue, 2);
  display.print(" W:");
  display.println(lowWater ? "LOW" : "OK");

  display.print("F:");
  display.print(fanOn ? "ON " : "OFF");

  display.print(" P:");
  display.print(pumpOn ? "ON " : "OFF");

  display.print(" L:");
  display.print(growLightOn ? "ON" : "OFF");

  display.display();
}

/* ========================================================= */

String jsonBool(bool value) {
  return value ? "true" : "false";
}

/* ========================================================= */

String buildTelemetryJson() {
  String json = "{";

  json += "\"api_key\":\"";
  json += DEVICE_API_KEY;
  json += "\",";

  json += "\"device_id\":\"";
  json += DEVICE_ID;
  json += "\",";

  json += "\"temperature\":";
  json += String(temperature, 2);
  json += ",";

  json += "\"humidity\":";
  json += String(humidity, 2);
  json += ",";

  json += "\"soil_moisture\":";
  json += String(soilMoisture);
  json += ",";

  json += "\"light_lux\":";
  json += String(lightLux, 2);
  json += ",";

  json += "\"water_level\":";
  json += String(waterLevel);
  json += ",";

  json += "\"ph\":";
  json += String(phValue, 2);
  json += ",";

  json += "\"mq135\":";
  json += String(mq135);
  json += ",";

  json += "\"fan\":";
  json += jsonBool(fanOn);
  json += ",";

  json += "\"pump\":";
  json += jsonBool(pumpOn);
  json += ",";

  json += "\"valve\":";
  json += jsonBool(valveOn);
  json += ",";

  json += "\"grow_light\":";
  json += jsonBool(growLightOn);
  json += ",";

  json += "\"low_water\":";
  json += jsonBool(lowWater);
  json += ",";

  json += "\"ph_alert\":";
  json += jsonBool(phAlert);
  json += ",";

  json += "\"air_quality_alert\":";
  json += jsonBool(airQualityAlert);

  json += "}";

  return json;
}

/* ========================================================= */

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

  WiFiClientSecure client;

  /*
    For testing only. In production, use a validated
    root certificate instead of disabling certificate checks.
  */
  client.setInsecure();

  HTTPClient http;

  if (!http.begin(client, N8N_WEBHOOK_URL)) {
    Serial.println("Could not connect to n8n webhook.");
    return;
  }

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

  String payload = buildTelemetryJson();

  int responseCode = http.POST(payload);

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

  http.end();
}

/* ========================================================= */

void connectWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  Serial.print("Connecting to Wi-Fi");

  unsigned long startTime = millis();

  while (
    WiFi.status() != WL_CONNECTED &&
    millis() - startTime < 20000
  ) {
    delay(500);
    Serial.print(".");
  }

  Serial.println();

  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Wi-Fi connected. IP: ");
    Serial.println(WiFi.localIP());
  }
  else {
    Serial.println("Wi-Fi unavailable. Local control continues.");
  }
}

/* ========================================================= */

void setup() {
  Serial.begin(115200);

  pinMode(RELAY_FAN_PIN, OUTPUT);
  pinMode(RELAY_PUMP_PIN, OUTPUT);
  pinMode(RELAY_VALVE_PIN, OUTPUT);
  pinMode(RELAY_LIGHT_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  setFan(false);
  setPump(false);
  setValve(false);
  setGrowLight(false);
  setBuzzer(false);

  analogReadResolution(12);

  analogSetPinAttenuation(SOIL_PIN, ADC_11db);
  analogSetPinAttenuation(WATER_LEVEL_PIN, ADC_11db);
  analogSetPinAttenuation(PH_PIN, ADC_11db);
  analogSetPinAttenuation(MQ135_PIN, ADC_11db);

  Wire.begin(SDA_PIN, SCL_PIN);

  dht.begin();
  bh1750.begin();

  if (!display.begin(
        SSD1306_SWITCHCAPVCC,
        OLED_ADDRESS
      )) {
    Serial.println("OLED initialization failed.");
  }

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println("AI Greenhouse");
  display.println("Starting...");
  display.display();

  connectWiFi();

  Serial.println("System ready.");
}

/* ========================================================= */

void loop() {
  unsigned long now = millis();

  if (
    now - lastRead >= READ_INTERVAL
  ) {
    lastRead = now;

    readSensors();
    applyAutomation();
    updateOLED();

    Serial.println(buildTelemetryJson());
  }

  if (
    now - lastSend >= SEND_INTERVAL
  ) {
    lastSend = now;

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

    sendTelemetryToN8N();
  }
}

15. Optional command path from n8n to ESP32

The safest method is for n8n to send a command to an ESP32 endpoint only after authorization. The ESP32 should validate the command and still enforce local protections.

Example command JSON

{
  "api_key": "CHANGE_THIS_SECRET",
  "command": "pump_off",
  "request_id": "telegram-12345"
}

Recommended command rules

pump_on:
  allowed only when water level is normal
  allowed only when manual control is enabled
  must be logged

pump_off:
  always allowed

fan_on/fan_off:
  allowed, but automatic temperature protection remains active

grow_light_on/grow_light_off:
  allowed within configured operating hours

valve_on:
  allowed only when pump and water level are safe

The ESP32 should not accept arbitrary relay pin numbers or unvalidated text commands. Use a small whitelist of commands.

16. Telegram voice-alert workflow

ESP32 telemetry
      │
      ▼
n8n Webhook
      │
      ▼
Alert condition?
      │
      ├── No → Log data only
      │
      └── Yes
            │
            ▼
       Create alert text
            │
            ▼
       Text-to-Speech API
            │
            ▼
     Receive MP3/OGG audio
            │
            ▼
       Telegram Send Voice

Example voice message:

Greenhouse warning. The water tank level is low.
The irrigation pump has been stopped to protect the system.

Telegram voice-message workflows generally require a Telegram bot token, an audio file, and a correctly configured Telegram node. n8n workflow examples also demonstrate voice-message transcription in the reverse direction.[n8n][n8n]

17. Google Sheets documentation format

Create a worksheet named Telemetry.

Header row

Timestamp | Device ID | Temperature | Humidity | Soil Moisture |
Light Lux | Water Level | pH | MQ-135 | Fan | Pump | Valve |
Grow Light | Low Water | pH Alert | Air Quality Alert

Example row

2026-10-09T07:30:00Z | greenhouse-esp32-01 | 31.4 | 68 |
43 | 7200 | 1800 | 6.4 | 1150 | FALSE | FALSE |
FALSE | TRUE | FALSE | FALSE | FALSE

Recommended spreadsheet improvements

  • Add conditional formatting for high temperature.
  • Highlight soil moisture below the irrigation threshold.
  • Highlight low-water rows in red.
  • Add daily average formulas.
  • Add a separate Alerts worksheet.
  • Add a Maintenance worksheet for sensor calibration records.

18. ThingSpeak dashboard design

Configure one ThingSpeak channel with eight fields:

Field 1: Temperature
Field 2: Humidity
Field 3: Soil moisture
Field 4: Light intensity
Field 5: Water level
Field 6: pH
Field 7: MQ-135
Field 8: Pump status

ThingSpeak supports channel charts and REST API updates. The API update request should use the channel’s write API key, and field values can be passed using field1, field2, and similar parameters.[mathworks][mathworks]

19. Security design

Use these protections:

  • Store Wi-Fi passwords and service keys outside public code repositories.
  • Use HTTPS for ESP32-to-n8n communication.
  • Validate a device API key in n8n.
  • Use a unique device ID.
  • Restrict Telegram commands to approved chat IDs.
  • Require confirmation for actuator commands.
  • Log every remote control action.
  • Rate-limit webhook requests.
  • Reject malformed JSON.
  • Keep emergency safety logic local on the ESP32.
  • Use TLS certificate validation in production instead of setInsecure().
  • Apply least-privilege credentials to Google Sheets and other services.

20. Testing procedure

Hardware testing

  1. Test the ESP32 without relay loads.
  2. Confirm each sensor reading in the Serial Monitor.
  3. Test the OLED separately.
  4. Test each relay with a low-risk load.
  5. Confirm relay ON/OFF polarity.
  6. Test the buzzer.
  7. Test pump and valve with water disconnected from plants.
  8. Verify the fuse and supply voltage.
  9. Confirm that low water disables the pump.

Software testing

  1. Upload the ESP32 code.
  2. Verify Wi-Fi connection.
  3. Confirm the n8n webhook receives JSON.
  4. Test invalid API-key rejection.
  5. Confirm Google Sheets receives one row per telemetry event.
  6. Confirm ThingSpeak fields update correctly.
  7. Trigger a low-water condition.
  8. Trigger a high-temperature condition.
  9. Verify Telegram text delivery.
  10. Verify Telegram voice delivery.
  11. Test Telegram voice-to-text if enabled.
  12. Test an AI summary.
  13. Test a denied unauthorized command.
  14. Disconnect Wi-Fi and verify local automation continues.

21. Troubleshooting

Problem Likely cause Solution
OLED blank Wrong I²C address or wiring Scan I²C addresses; check SDA/SCL
Relay operates inversely Active-HIGH/active-LOW mismatch Swap RELAY_ON and RELAY_OFF
ESP32 resets when pump starts Supply drop or electrical noise Separate power paths, add protection, use adequate SMPS
pH value is incorrect No calibration Calibrate with standard buffer solutions
MQ-135 fluctuates Sensor warm-up and environmental sensitivity Allow warm-up and use calibrated thresholds
n8n receives no data Wrong production URL or inactive workflow Activate workflow and verify HTTPS URL
Telegram trigger fails Bot webhook conflict or inaccessible n8n Use one workflow per bot and public HTTPS
Google Sheets fails Incorrect OAuth credential or sheet permissions Reconnect Google account and verify access
ThingSpeak rejects data Incorrect write API key or field mapping Verify channel key and field parameters
Voice alert does not send TTS output format or missing binary mapping Confirm audio file and Telegram binary property
AI gives unsafe instruction Poor prompt or unrestricted tool Add authorization and hard safety rules

22. Advantages

  • Local automatic control continues during cloud failure.
  • n8n provides visual, modular workflow automation.
  • Telegram supports rapid text and voice notifications.
  • Google Sheets provides a simple historical database.
  • ThingSpeak provides IoT charts and cloud visualization.
  • The AI agent provides natural-language analysis.
  • The architecture is expandable to cameras, CO₂ sensors, weather APIs, and solar power.
  • The project demonstrates embedded systems, IoT, cloud automation, APIs, AI, and smart agriculture in one platform.

23. Limitations

  • Internet-dependent functions stop when Wi-Fi or n8n is unavailable.
  • Low-cost pH sensors require frequent calibration.
  • MQ-135 provides an indicative reading, not a laboratory-grade gas analysis.
  • AI recommendations must not replace local safety logic.
  • Telegram and cloud services may have rate limits or service interruptions.
  • TTS services may require separate paid API credentials.
  • Sensor placement and greenhouse conditions significantly affect accuracy.
  • Relay modules are not a substitute for proper motor drivers in high-current systems.

24. Future scope

  • Camera-based plant growth monitoring.
  • AI disease and pest detection.
  • CO₂ sensor integration.
  • Automatic nutrient dosing.
  • Weather-based irrigation.
  • Solar power and battery backup.
  • LoRaWAN communication for remote farms.
  • Predictive irrigation using historical data.
  • Crop-specific AI agents.
  • Voice commands in multiple languages.
  • Mobile application integration.
  • Digital twin of the greenhouse.
  • MQTT-based scalable deployment.
  • Automatic report generation from Google Sheets.

25. Final conclusion

The proposed system combines ESP32 edge computing with n8n automation, AI assistance, Telegram notifications, Google Sheets logging, and ThingSpeak visualization. The ESP32 performs immediate sensing and actuator control, while n8n connects the greenhouse to cloud services and communication channels. Telegram provides practical text and voice alerts, Google Sheets offers accessible historical records, and ThingSpeak supplies live IoT visualization.

The most important design principle is to keep safety-critical functions local. The ESP32 must stop the pump during low-water conditions even if n8n, Telegram, the AI agent, or the internet is unavailable. The AI agent should interpret, summarize, and request authorized actions, but it should never bypass the embedded safety system.

Project Summary

The project is an AI-powered IoT greenhouse monitoring and control system using ESP32, n8n automation, Telegram alerts, Google Sheets, and ThingSpeak.

The ESP32 collects readings from temperature, humidity, soil-moisture, light, water-level, pH, and air-quality sensors. It locally controls the water pump, solenoid valve, ventilation fan, grow light, OLED display, and buzzer according to predefined thresholds.

Sensor data is sent through Wi-Fi to an n8n webhook. n8n processes the data, stores it in Google Sheets, updates ThingSpeak charts, evaluates abnormal conditions, and sends Telegram notifications. Critical alerts can be converted into Telegram voice messages using a text-to-speech service.

An AI agent can communicate through Telegram to:

  • Explain current greenhouse conditions.
  • Summarize sensor readings.
  • Identify abnormal values.
  • Recommend corrective actions.
  • Process authorized control requests.
  • Respond to text or voice messages.

System architecture

Sensors
   │
   ▼
ESP32 Controller
   │
   ├── OLED display
   ├── Buzzer
   ├── Relay module
   │      ├── Pump
   │      ├── Solenoid valve
   │      ├── Ventilation fan
   │      └── Grow light
   │
   └── Wi-Fi
          │
          ▼
        n8n
          │
   ┌──────┼─────────┬──────────────┐
   ▼      ▼         ▼              ▼
Google  ThingSpeak Telegram       AI Agent
Sheets  Dashboard  Alerts         Responses

Main software functions

  • Sensor reading and calibration.
  • Automatic irrigation using soil-moisture hysteresis.
  • Fan control using temperature hysteresis.
  • Grow-light control using light-intensity thresholds.
  • Low-water safety shutdown.
  • pH and MQ-135 warning detection.
  • OLED local monitoring.
  • HTTPS JSON telemetry to n8n.
  • Google Sheets data logging.
  • ThingSpeak cloud visualization.
  • Telegram text alerts.
  • Telegram voice alerts using text-to-speech.
  • AI-based greenhouse analysis and authorized commands.

Key safety principle

The ESP32 must retain control of essential safety functions. For example, when the water tank is low, the ESP32 must switch off the pump and solenoid valve locally, even if the internet, n8n, Telegram, or the AI service is unavailable.

Final project title

AI-Powered Agentic IoT Greenhouse Monitoring and Automatic Control System Using ESP32, n8n Automation, Telegram Voice Alerts, Google Sheets, and ThingSpeak

mindmap

AI-Powered IoT Greenhouse Mind Map

              AI-POWERED AGENTIC IoT GREENHOUSE SYSTEM
          USING ESP32, n8n, TELEGRAM, GOOGLE SHEETS & THINGSPEAK
                                   │
 ┌─────────────────┬───────────────┼────────────────┬──────────────────┐
 ▼                 ▼               ▼                ▼                  ▼
Hardware        ESP32 Edge       n8n Automation    IoT Services      AI Agent
                 Control
 │                 │               │                │                  │
 ├─ DHT22         ├─ Sensor read  ├─ Webhook       ├─ ThingSpeak      ├─ Analyze data
 ├─ Soil sensor   ├─ Thresholds   ├─ Validation    │  ├─ Live charts  ├─ Summarize status
 ├─ BH1750        ├─ Hysteresis   ├─ Routing       │  └─ History      ├─ Explain alerts
 ├─ Water level   ├─ Relay logic  ├─ Google Sheets ├─ Google Sheets   ├─ Voice/text input
 ├─ pH sensor     ├─ OLED output  ├─ ThingSpeak    │  └─ Data log     ├─ Recommend actions
 └─ MQ-135        ├─ Buzzer       ├─ Alert rules   └─ Telegram        └─ Authorized commands
                   ├─ Wi-Fi        ├─ TTS voice        ├─ Text alerts
                   └─ Safety       └─ AI workflow     └─ Voice alerts

Detailed mind map

AI-POWERED AGENTIC IoT GREENHOUSE SYSTEM
│
├── 1. Hardware
│   ├── ESP32 DevKit
│   │   ├── Main controller
│   │   ├── Wi-Fi connectivity
│   │   ├── ADC inputs
│   │   ├── Digital GPIO
│   │   └── I²C communication
│   │
│   ├── Sensors
│   │   ├── DHT22
│   │   │   ├── Temperature
│   │   │   └── Humidity
│   │   ├── Capacitive soil-moisture sensor
│   │   ├── BH1750 light sensor
│   │   ├── Water-level sensor
│   │   ├── pH sensor
│   │   └── MQ-135 air-quality sensor
│   │
│   ├── Actuators
│   │   ├── 12 V water pump
│   │   ├── 12 V solenoid valve
│   │   ├── Ventilation fan
│   │   └── LED grow light
│   │
│   ├── Indicators
│   │   ├── OLED display
│   │   └── Active buzzer
│   │
│   └── Power
│       ├── 12 V, 5 A SMPS
│       ├── Fuse
│       ├── Main switch
│       └── LM2596 buck converter
│
├── 2. ESP32 Edge Control
│   ├── Read sensor values
│   ├── Convert ADC values
│   ├── Apply calibration
│   ├── Compare thresholds
│   ├── Use hysteresis
│   ├── Control relays
│   ├── Update OLED
│   ├── Activate buzzer
│   ├── Create JSON telemetry
│   ├── Send data to n8n
│   └── Continue local operation during cloud failure
│
├── 3. Automatic Rules
│   ├── Irrigation
│   │   ├── Soil moisture below lower limit
│   │   ├── Check water level
│   │   ├── Pump ON
│   │   └── Valve ON
│   │
│   ├── Irrigation stop
│   │   ├── Soil moisture reaches upper limit
│   │   └── Pump and valve OFF
│   │
│   ├── Low-water protection
│   │   ├── Tank level below limit
│   │   ├── Pump OFF
│   │   ├── Valve OFF
│   │   └── Buzzer alert
│   │
│   ├── Ventilation
│   │   ├── Temperature above ON limit
│   │   └── Fan ON
│   │
│   ├── Lighting
│   │   ├── Light intensity below limit
│   │   └── Grow light ON
│   │
│   ├── pH warning
│   │   └── Alert if pH is outside configured range
│   │
│   └── Air-quality warning
│       └── Alert if MQ-135 reading exceeds limit
│
├── 4. n8n Automation
│   ├── Webhook
│   │   └── Receives ESP32 JSON data
│   ├── API-key validation
│   ├── Data normalization
│   ├── Timestamp generation
│   ├── Alert evaluation
│   ├── Google Sheets node
│   │   └── Appends telemetry row
│   ├── HTTP Request node
│   │   └── Updates ThingSpeak
│   ├── Telegram node
│   │   └── Sends text notification
│   ├── Text-to-speech node
│   │   └── Creates voice alert
│   ├── Telegram voice node
│   │   └── Sends audio message
│   └── AI Agent node
│       ├── Reads sensor data
│       ├── Interprets conditions
│       ├── Provides recommendations
│       └── Handles authorized commands
│
├── 5. IoT Cloud Services
│   ├── ThingSpeak
│   │   ├── Temperature field
│   │   ├── Humidity field
│   │   ├── Soil-moisture field
│   │   ├── Light field
│   │   ├── Water-level field
│   │   ├── pH field
│   │   ├── MQ-135 field
│   │   └── Pump-status field
│   │
│   ├── Google Sheets
│   │   ├── Timestamp
│   │   ├── Device ID
│   │   ├── Sensor readings
│   │   ├── Actuator status
│   │   └── Alert history
│   │
│   └── Telegram
│       ├── Text alerts
│       ├── Voice alerts
│       ├── User commands
│       └── AI conversation
│
├── 6. AI Agent
│   ├── Inputs
│   │   ├── Current readings
│   │   ├── Historical data
│   │   ├── ThingSpeak data
│   │   └── Telegram messages
│   │
│   ├── Processing
│   │   ├── Detect abnormal conditions
│   │   ├── Summarize greenhouse state
│   │   ├── Identify trends
│   │   ├── Explain alerts
│   │   └── Recommend actions
│   │
│   ├── Outputs
│   │   ├── Text response
│   │   ├── Voice response
│   │   ├── Alert message
│   │   └── Authorized control request
│   │
│   └── Safety restrictions
│       ├── No unsafe relay commands
│       ├── No pump operation during low water
│       ├── Confirmation for manual control
│       └── Local ESP32 rules have priority
│
├── 7. Communication
│   ├── Sensor-to-ESP32
│   │   ├── Analog
│   │   ├── Digital
│   │   └── I²C
│   ├── ESP32-to-n8n
│   │   └── HTTPS POST with JSON
│   ├── n8n-to-Google Sheets
│   │   └── Authenticated API
│   ├── n8n-to-ThingSpeak
│   │   └── REST API
│   ├── n8n-to-Telegram
│   │   └── Bot API
│   └── Telegram-to-AI Agent
│       ├── Text input
│       └── Voice input
│
├── 8. Security
│   ├── HTTPS
│   ├── API-key validation
│   ├── Telegram chat-ID validation
│   ├── Secure n8n credentials
│   ├── Authorized control commands
│   ├── Command logging
│   ├── Rate limiting
│   └── Local safety override
│
├── 9. Testing
│   ├── Sensor testing
│   ├── OLED testing
│   ├── Relay testing
│   ├── Pump and valve testing
│   ├── Low-water test
│   ├── n8n webhook test
│   ├── Google Sheets test
│   ├── ThingSpeak test
│   ├── Telegram text test
│   ├── Telegram voice test
│   └── AI command authorization test
│
└── 10. Future Scope
    ├── CO₂ sensor
    ├── Camera monitoring
    ├── AI disease detection
    ├── Automatic nutrient dosing
    ├── Solar power
    ├── Weather-based irrigation
    ├── Predictive maintenance
    ├── Multilingual voice control
    ├── LoRaWAN connectivity
    └── Crop-specific AI agents

Workflow mind map

ESP32 SENSOR DATA
        │
        ▼
n8n WEBHOOK
        │
        ▼
VALIDATE API KEY
        │
        ▼
NORMALIZE DATA
        │
 ┌──────┼─────────┬─────────────┐
 ▼      ▼         ▼             ▼
Sheets ThingSpeak Alert Check  AI Agent
 │      │         │             │
 ▼      ▼         ▼             ▼
History Charts  Telegram     Analysis
                         ┌─────┴─────┐
                         ▼           ▼
                    Recommendation  Command
                                        │
                                        ▼
                              Authorization check
                                        │
                                        ▼
                                  ESP32 control

Core concept

ESP32 = Real-time local controller
n8n   = Automation and integration layer
AI    = Interpretation and decision-support layer
Telegram = Human interaction and alert channel
Google Sheets = Historical record
ThingSpeak = IoT dashboard

The most important design rule is that the ESP32 retains authority over safety-critical actions. Cloud automation and AI can analyze data and request an action, but they must not override local protections such as low-water pump shutdown.