Tuesday, 29 September 2026

AI Smart Pillow for Sleep Disorder Detection #SleepAI

Yes. I can structure this as a complete engineering-project document covering the smart pillow hardware, ESP32 firmware, AI/agent layer, n8n workflow, Telegram voice alerts, Google Sheets logging, ThingSpeak dashboard, webpage, circuit schematic, data flow, and testing.

I’ll treat the system as a sleep-monitoring prototype, not a medical diagnostic device: it can detect and flag patterns such as unusual movement, breathing-related anomalies, snoring/noise, and sleep-session irregularities, but those signals should not be presented as a clinical diagnosis.

Proposed project title

AI Smart Pillow for Sleep Monitoring & Disorder-Risk Detection using ESP32, IoT, n8n Automation, AI Agent, Telegram Voice Alerts, Google Sheets & ThingSpeak

Core architecture

                    ┌──────────────────────────────┐
                    │        SMART PILLOW           │
                    │                              │
                    │  ESP32                      │
                    │   ├─ Pressure sensors        │
                    │   ├─ MPU6050 / accelerometer │
                    │   ├─ MAX30102*               │
                    │   ├─ Microphone*             │
                    │   ├─ Temperature/Humidity    │
                    │   └─ Optional sensors        │
                    └──────────────┬───────────────┘
                                   │ Wi-Fi / MQTT / HTTP
                                   ▼
                    ┌──────────────────────────────┐
                    │       IoT / n8n SERVER        │
                    │                              │
                    │  Webhook → Data processing   │
                    │           ↓                  │
                    │       AI Agent               │
                    │           ↓                  │
                    │   Decision / Classification  │
                    │           ↓                  │
                    │   ┌───────┼────────┐         │
                    └───┼───────┼────────┼─────────┘
                        │       │        │
                        ▼       ▼        ▼
                  Telegram   Google    ThingSpeak
                  Voice      Sheets    Dashboard
                  Alert
                        │
                        ▼
                   User / Caregiver

*The exact sensors should be selected according to the desired measurements and electrical/mechanical constraints. In particular, a pillow-based prototype should not be described as measuring clinical SpO₂ or diagnosing sleep apnea unless it has been appropriately validated.

Main operating cycle

START
  │
  ▼
ESP32 initializes sensors
  │
  ▼
Connect to Wi-Fi
  │
  ▼
Collect sleep data
  │
  ├── Movement
  ├── Pressure
  ├── Temperature
  ├── Sound/snoring features
  └── Optional physiological signals
  │
  ▼
Filter / preprocess data
  │
  ▼
Create JSON telemetry
  │
  ▼
Send to n8n Webhook
  │
  ▼
n8n validates data
  │
  ▼
AI Agent analyzes sleep event
  │
  ├────────────── Normal ──────────────┐
  │                                    │
  ├──────────── Warning ───────────────┤
  │                                    │
  └──────────── Critical ──────────────┤
                                       ▼
                              Store / notify
                                       │
                    ┌──────────────────┼─────────────────┐
                    ▼                  ▼                 ▼
               Google Sheets       ThingSpeak        Telegram
                    │                  │                 │
                    ▼                  ▼                 ▼
                History             Graphs          Voice alert

Example AI-agent decision

The ESP32 could send:

{
  "device_id": "SMARTPILLOW_01",
  "timestamp": "2026-09-29T21:30:00+05:30",
  "movement": 0.72,
  "pressure_left": 61,
  "pressure_center": 43,
  "pressure_right": 18,
  "temperature": 28.4,
  "humidity": 61,
  "sound_level": 68,
  "snoring_event": true,
  "sleep_state": "sleeping"
}

The n8n/AI layer can transform this into something such as:

{
  "sleep_event": "possible_disturbance",
  "severity": "warning",
  "reason": "Repeated movement and elevated sound events detected",
  "action": "log_and_notify"
}

The important design principle is that the AI agent should reason over sensor observations rather than pretending that one sensor reading proves a medical condition.

Telegram alert example

🚨 Smart Pillow Alert

Sleep disturbance detected.

Time: 02:17 AM
Movement: High
Sound event: Detected
Duration: 42 seconds
Sleep state: Interrupted

The system recommends reviewing the sleep-session
data rather than treating this alert as a diagnosis.

For a voice notification:

"Smart Pillow alert. A repeated sleep disturbance
was detected at 2:17 AM. Please review the recorded
sleep data."

n8n workflow

             ESP32
               │
               │ HTTP POST
               ▼
       ┌─────────────────┐
       │  n8n Webhook    │
       └────────┬────────┘
                ▼
       ┌─────────────────┐
       │ Validate JSON   │
       └────────┬────────┘
                ▼
       ┌─────────────────┐
       │ Data Processing │
       └────────┬────────┘
                ▼
       ┌─────────────────┐
       │ AI Agent / LLM  │
       └────────┬────────┘
                ▼
        ┌───────┴────────┐
        │                │
        ▼                ▼
   Normal event      Abnormal/
        │             warning
        │                │
        ▼                ▼
 Google Sheets      Telegram
        │             │
        ▼             ▼
 ThingSpeak       Text/Voice
        │
        ▼
 Dashboard

Suggested n8n nodes

  1. Webhook

  2. Set / Edit Fields

  3. Code – validate and normalize ESP32 data

  4. IF – basic threshold checks

  5. AI Agent

  6. Google Sheets

  7. HTTP Request → ThingSpeak

  8. Telegram

  9. Text-to-Speech service if voice generation is required

  10. Telegram audio/message node

  11. Error handling / notification workflow

ESP32 hardware block diagram

                 +-----------------------+
                 |       ESP32           |
                 |                       |
                 | GPIO / I2C / ADC      |
                 +----+----+----+--------+
                      │    │    │
          ┌───────────┘    │    └────────────┐
          ▼                ▼                 ▼
   Pressure Array       MPU6050        Temp/Humidity
          │                │                 │
          └────────────────┼─────────────────┘
                           │
                           ▼
                    Sensor Processing
                           │
                           ▼
                         Wi-Fi
                           │
                           ▼
                     n8n Webhook

Example electrical concept

For an ESP32 Dev Kit:

             ESP32 DEVKIT
        ┌─────────────────────┐
        │                     │
3V3 ────┼──── Sensor VCC      │
GND ────┼──── Sensor GND      │
        │                     │
GPIO21 ─┼──── I2C SDA         │
GPIO22 ─┼──── I2C SCL         │
        │                     │
ADC pins ┼──── Pressure       │
        │      sensors       │
GPIO     ┼──── Digital       │
        │      sensors       │
        └─────────────────────┘

Important: the actual schematic must account for the specific sensor modules, their operating voltage, pull-up resistors, ADC characteristics, current consumption, and whether their outputs are analog, I ²C, SPI, UART, or digital.

ESP32 firmware structure

I would organize the firmware like this:

ESP32
│
├── Wi-Fi Manager
│
├── Sensor Manager
│   ├── Pressure
│   ├── Motion
│   ├── Temperature
│   ├── Humidity
│   └── Audio/event features
│
├── Signal Processing
│
├── Sleep Event Detection
│
├── JSON Generator
│
├── HTTP/MQTT Client
│
├── OTA Update
│
└── Error / watchdog handling

Basic ESP32 Arduino example

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

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

const char* N8N_WEBHOOK =
    "https://YOUR-N8N-SERVER/webhook/smart-pillow";

const int PRESSURE_PIN = 34;

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

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

  Serial.println("\nWiFi connected");
}

void sendSleepData() {

  int pressure = analogRead(PRESSURE_PIN);

  float temperature = 28.4;
  float humidity = 61.0;
  float movement = 0.72;
  float soundLevel = 68.0;

  bool snoringEvent = soundLevel > 65;

  StaticJsonDocument<512> doc;

  doc["device_id"] = "SMARTPILLOW_01";
  doc["pressure"] = pressure;
  doc["temperature"] = temperature;
  doc["humidity"] = humidity;
  doc["movement"] = movement;
  doc["sound_level"] = soundLevel;
  doc["snoring_event"] = snoringEvent;

  String payload;
  serializeJson(doc, payload);

  HTTPClient http;

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

  int responseCode = http.POST(payload);

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

  Serial.println(http.getString());

  http.end();
}

void setup() {

  Serial.begin(115200);

  pinMode(PRESSURE_PIN, INPUT);

  connectWiFi();
}

void loop() {

  sendSleepData();

  delay(10000);
}

For a real deployment, I would add Wi-Fi reconnection, TLS certificate validation, authentication, sensor calibration, non-blocking timing, watchdog recovery, OTA firmware updates, local buffering when Wi-Fi is unavailable, and rate limiting.

AI-agent logic

The AI agent should receive structured observations rather than raw uncontrolled text.

Example system instruction:

You are the analysis component of a smart sleep-monitoring IoT system.

Analyze the supplied sensor observations.

Do not diagnose medical conditions.

Classify the observation as:
NORMAL
DISTURBANCE
WARNING

Consider:
- movement
- pressure changes
- sound events
- duration
- repeated events
- temperature
- sleep-state transitions

Return valid JSON only:

{
  "classification": "...",
  "severity": "...",
  "reason": "...",
  "notify": true/false
}

This creates a much safer separation:

Sensors
   ↓
Measurements
   ↓
Signal processing
   ↓
Rules / thresholds
   ↓
AI interpretation
   ↓
Notification

rather than:

Sensor → AI → "You have sleep apnea"

The latter would be an unjustified medical conclusion.

Google Sheets database

A useful sheet structure is:

Timestamp Device Movement Pressure Temp Humidity Sound Event Severity
21:30 PILLOW01 0.72 61 28.4 61 68 Disturbance Warning
21:40 PILLOW01 0.18 57 28.2 60 35 Normal Normal

This provides a simple historical dataset for later analysis.

ThingSpeak

A possible field mapping:

Field 1 = Movement
Field 2 = Pressure
Field 3 = Temperature
Field 4 = Humidity
Field 5 = Sound level
Field 6 = Sleep state
Field 7 = Disturbance count
Field 8 = Alert severity

Dashboard:

┌───────────────────────────────────────────┐
│          SMART PILLOW DASHBOARD           │
├───────────────────────────────────────────┤
│                                           │
│ Temperature      28.4 °C                  │
│ Humidity         61 %                     │
│ Movement         0.72                     │
│ Sound            68 dB*                   │
│                                           │
│ ───── Movement over time ──────────────   │
│       /\       /\                         │
│  ____/  \_____/  \_____                   │
│                                           │
│ ───── Disturbance events ─────────────   │
│       █   ███      █                     │
│                                           │
└───────────────────────────────────────────┘

*If the microphone is not calibrated, it is better to call this a relative sound level rather than claim an accurate dB measurement.

Webpage

The project can have a local/cloud webpage:

                 SMART PILLOW AI
        ┌───────────────────────────────┐
        │ 🟢 Device Online              │
        │                               │
        │ Current Sleep State            │
        │        SLEEPING                │
        │                               │
        │ Movement       █████░ 72%      │
        │ Pressure       ████░░           │
        │ Temperature    28.4 °C         │
        │ Humidity       61%             │
        │ Sound          █████░           │
        │                               │
        │ Events Today: 7                │
        │ Warnings: 2                    │
        └───────────────────────────────┘

Possible architecture:

Browser
   │
   ▼
HTML / CSS / JavaScript
   │
   ▼
Backend/API
   │
   ├──── ThingSpeak
   ├──── n8n
   └──── Database

Complete project data flow

                    ┌─────────────┐
                    │   PERSON    │
                    └──────┬──────┘
                           │
                           ▼
                    ┌─────────────┐
                    │ SMART PILLOW│
                    └──────┬──────┘
                           │
                    Sensor measurements
                           │
                           ▼
                    ┌─────────────┐
                    │    ESP32    │
                    └──────┬──────┘
                           │
                       Wi-Fi
                           │
                           ▼
                    ┌─────────────┐
                    │ n8n Webhook  │
                    └──────┬──────┘
                           │
                           ▼
                  ┌─────────────────┐
                  │ Data Processing │
                  └────────┬────────┘
                           │
                           ▼
                     ┌───────────┐
                     │ AI Agent  │
                     └─────┬─────┘
                           │
                 ┌─────────┼─────────┐
                 │         │         │
                 ▼         ▼         ▼
              Sheets   ThingSpeak Telegram
                 │         │         │
                 ▼         ▼         ▼
              History   Dashboard   Alert

Telegram conversation concept

SMART PILLOW BOT
        │
        ▼
┌──────────────────────────────┐
│ User: /status                │
└──────────────┬───────────────┘
               ▼
        n8n Telegram Trigger
               │
               ▼
          Query data
               │
               ▼
           AI Agent
               │
               ▼
┌──────────────────────────────┐
│ Bot:                         │
│                              │
│ Current state: Sleeping      │
│ Movement: Low                │
│ Events tonight: 4            │
│ Last disturbance: 02:17      │
└──────────────────────────────┘

You can also implement commands such as:

/start
/status
/today
/events
/report
/device
/help

Suggested project folders

AI-Smart-Pillow/
│
├── ESP32/
│   ├── smart_pillow.ino
│   ├── sensors.h
│   ├── sensors.cpp
│   ├── wifi_manager.h
│   └── config.h
│
├── n8n/
│   ├── workflow.json
│   ├── ai-agent-prompt.txt
│   └── webhook-schema.json
│
├── Web/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── Documentation/
│   ├── architecture.md
│   ├── wiring.md
│   ├── installation.md
│   ├── testing.md
│   └── user-manual.md
│
├── Hardware/
│   ├── block-diagram
│   ├── schematic
│   └── BOM
│
└── README.md

What the full documentation should contain

I would document the finished project in this order:

  1. Abstract

  2. Introduction

  3. Problem statement

  4. Objectives

  5. Existing-system limitations

  6. Proposed system

  7. System architecture

  8. Hardware requirements

  9. Detailed sensor selection

  10. ESP32 pin configuration

  11. Circuit/schematic

  12. Smart-pillow mechanical arrangement

  13. Firmware architecture

  14. Complete ESP32 source code

  15. Wi-Fi communication

  16. HTTP/MQTT protocol

  17. JSON data format

  18. n8n installation

  19. Complete n8n workflow

  20. AI-agent prompt and logic

  21. Telegram bot configuration

  22. Telegram voice-alert pipeline

  23. Google Sheets integration

  24. ThingSpeak integration

  25. Web dashboard

  26. Database/data model

  27. Flowcharts

  28. Sequence diagrams

  29. Testing methodology

  30. Test cases

  31. Error handling

  32. Security

  33. Privacy

  34. Limitations

  35. Future improvements

  36. Cost/BOM

  37. Installation procedure

  38. Troubleshooting

  39. Results

  40. Conclusion

One important design decision

For a serious project, I recommend calling the output “sleep monitoring / sleep-event detection” rather than claiming the pillow can independently detect or diagnose a specific sleep disorder. You can still make the project highly sophisticated by using AI to identify patterns and anomalies and then generate alerts for review.

If you want, I can next produce the complete implementation package in one structured answer, including the full circuit/pin table, detailed wiring schematic, ESP32 Arduino code, n8n workflow JSON, AI-agent prompt, Telegram bot/voice workflow, Google Sheets setup, ThingSpeak configuration, HTML/CSS/JavaScript dashboard, database schema, flowcharts, sequence diagrams, BOM, installation steps, and final project-report format.

 

Absolutely. That is a strong structure for a final-year engineering/IoT/AI project report. I would expand it into the following complete documentation structure so that it works both as a technical implementation manual and as an academic project report.

AI Smart Pillow — Complete Project Documentation Structure

Project title:
AI Smart Pillow for Sleep Monitoring and Sleep-Event Detection using ESP32, IoT, n8n Automation, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak


1. Abstract

The abstract should briefly explain:

  • What the Smart Pillow is.

  • Why sleep monitoring is important.

  • Why ESP32 is used.

  • Which sensors are used.

  • How IoT connectivity works.

  • How n8n automates the system.

  • How the AI agent analyzes events.

  • How Telegram provides notifications.

  • How Google Sheets stores historical data.

  • How ThingSpeak provides visualization.

  • What the prototype can and cannot determine.

Example

This project presents an AI-enabled smart pillow designed for continuous sleep monitoring and detection of unusual sleep-related events. The system uses an ESP32 microcontroller together with multiple sensors to collect parameters such as movement, pressure distribution, environmental conditions, and acoustic events. The collected data is transmitted through Wi-Fi to an n8n automation server, where it is processed and analyzed using an AI agent. Based on predefined rules and sensor patterns, the system classifies events and can automatically record the data in Google Sheets, update a ThingSpeak cloud dashboard, and send text or voice notifications through Telegram. A web-based dashboard provides real-time monitoring and historical visualization. The proposed system demonstrates an agentic IoT architecture in which an embedded device collects information while cloud automation and AI perform higher-level event interpretation. The prototype is intended for experimental sleep monitoring and anomaly detection and is not a replacement for clinical sleep diagnosis.


2. Introduction

Explain the background of:

  • Sleep and sleep monitoring

  • Problems associated with poor sleep

  • Conventional sleep-monitoring systems

  • IoT-based healthcare/wellness systems

  • Embedded sensors

  • ESP32

  • Artificial intelligence

  • Agentic automation

  • Cloud dashboards

  • Telegram notifications

Suggested structure

2.1 Background
2.2 Sleep Monitoring
2.3 IoT in Healthcare
2.4 AI-Based Monitoring
2.5 Motivation
2.6 Proposed Approach

3. Problem Statement

Clearly identify the engineering problem.

Example

Conventional sleep-monitoring systems can involve expensive equipment, dedicated monitoring environments, or complicated interfaces. There is a need for a low-cost prototype capable of collecting multiple sleep-related signals in a comfortable environment and automatically processing those signals.

The proposed system attempts to solve this engineering problem by integrating:

Sensors
   ↓
ESP32
   ↓
Wi-Fi
   ↓
n8n
   ↓
AI Agent
   ↓
Cloud storage
   ↓
Dashboard
   ↓
Telegram notification

4. Objectives

Primary objective

Develop an IoT-enabled smart pillow capable of collecting and analyzing sleep-related sensor data.

Secondary objectives

  • Develop an ESP32-based sensor platform.

  • Monitor pillow pressure/movement.

  • Monitor environmental parameters.

  • Detect acoustic/sleep events where appropriate.

  • Transmit data over Wi-Fi.

  • Develop an n8n automation workflow.

  • Integrate an AI agent.

  • Store data in Google Sheets.

  • Display data using ThingSpeak.

  • Develop a web dashboard.

  • Send Telegram alerts.

  • Generate Telegram voice notifications.

  • Maintain historical sleep-session records.

  • Implement error handling and device recovery.


5. Existing-System Limitations

Discuss limitations without claiming that every commercial sleep product has the same limitations.

Possible areas:

  • Cost

  • Comfort

  • Limited customization

  • Lack of real-time alerts

  • Limited integration between IoT and AI

  • Limited user-controlled automation

  • Limited historical data access

  • Lack of open hardware/software architecture

Then clearly distinguish your prototype from clinical polysomnography and medically validated sleep devices.


6. Proposed System

Explain the complete proposed solution.

              SMART PILLOW
                   │
                   ▼
             ┌───────────┐
             │   ESP32   │
             └─────┬─────┘
                   │
             Sensor data
                   │
                   ▼
              Wi-Fi/HTTP
                   │
                   ▼
             ┌───────────┐
             │    n8n    │
             └─────┬─────┘
                   │
              AI Agent
                   │
        ┌──────────┼──────────┐
        ▼          ▼          ▼
    Telegram   Google       ThingSpeak
               Sheets
                   │
                   ▼
             Web Dashboard

7. System Architecture

Divide the architecture into four layers.

Layer 1 — Physical layer

Pressure
Motion
Temperature
Humidity
Audio/event sensor
        │
        ▼
      ESP32

Layer 2 — Communication layer

ESP32
  │
  └── Wi-Fi
        │
        ├── HTTP
        └── MQTT (optional)

Layer 3 — Intelligence/automation layer

n8n
 │
 ├── Validation
 ├── Processing
 ├── Rules
 ├── AI Agent
 └── Decision

Layer 4 — Application layer

Telegram
Google Sheets
ThingSpeak
Web Dashboard

8. Hardware Requirements

Create a complete Bill of Materials.

Example:

Component Quantity Purpose
ESP32 DevKit 1 Main controller
Pressure sensors/FSRs Multiple Pillow pressure
MPU6050 1 Motion/orientation
DHT22/SHT31 1 Temperature/humidity
Microphone module 1 Acoustic events
Resistors As required Sensor circuits
Breadboard/PCB 1 Prototyping
Jumper wires — Connections
5 V USB supply 1 Power
Pillow/foam enclosure 1 Mechanical integration

The final BOM should include:

  • Part number

  • Quantity

  • Voltage

  • Current

  • Approximate price

  • Supplier

  • Purpose


9. Detailed Sensor Selection

For each sensor, document:

9.1 Sensor name

9.2 Operating voltage

9.3 Interface

For example:

I²C
SPI
UART
ADC
GPIO

9.4 Measurement range

9.5 Resolution

9.6 Accuracy

9.7 Why it was selected

9.8 Connection to ESP32

9.9 Calibration method

9.10 Limitations


10. ESP32 Pin Configuration

Create a table such as:

ESP32 Pin Device Function
GPIO21 I²C sensors SDA
GPIO22 I²C sensors SCL
GPIO34 Pressure sensor ADC
GPIO35 Pressure sensor ADC
GPIO25 Audio/event input Digital/ADC
3V3 Sensors Power
GND Sensors Ground

The actual pins must be finalized after selecting the exact modules. Avoid assigning pins that conflict with bootstrapping, flash, or other ESP32-specific functions.


11. Circuit/Schematic

Include three diagrams:

11.1 Block schematic

                 ESP32
             ┌───────────┐
             │           │
Pressure ───►│ ADC       │
MPU6050 ────►│ I²C       │
Temp ───────►│ I²C       │
Audio ──────►│ ADC/GPIO   │
             │           │
             │ Wi-Fi     │
             └─────┬─────┘
                   │
                   ▼
                 n8n

11.2 Wiring diagram

Show:

VCC
GND
SDA
SCL
ADC
GPIO

11.3 Complete electrical schematic

This should eventually be created in:

  • KiCad

  • EasyEDA

  • Fritzing

  • Altium

  • Or another schematic tool.


12. Smart-Pillow Mechanical Arrangement

This section is particularly important.

Show where sensors physically sit.

Example:

        TOP VIEW
┌─────────────────────────────┐
│                             │
│      P1       P2       P3   │
│                             │
│                             │
│          ┌───────┐          │
│          │ HEAD  │          │
│          │ AREA  │          │
│          └───────┘          │
│                             │
│      M1               M2    │
│                             │
└─────────────────────────────┘

P1/P2/P3 = pressure sensing areas
M1/M2     = motion/event sensing

Document:

  • Sensor placement

  • Cushioning

  • Wiring channels

  • Electronics enclosure

  • Washable pillow cover

  • User comfort

  • Heat generation

  • Cable strain relief

  • Electrical isolation


13 . Firmware Architecture

setup()
 │
 ├── Initialize GPIO
 ├── Initialize I²C
 ├── Initialize sensors
 ├── Load configuration
 ├── Connect Wi-Fi
 └── Start timers
       │
       ▼
     loop()
       │
       ├── Read sensors
       ├── Filter data
       ├── Detect events
       ├── Build JSON
       ├── Send telemetry
       └── Handle errors

14. Complete ESP32 Source Code

The final documentation should contain:

main.ino
config.h
sensors.cpp
sensors.h
wifi_manager.cpp
wifi_manager.h
communication.cpp
communication.h
event_detector.cpp
event_detector.h

Instead of placing everything in one huge .ino file, modular code makes the project easier to maintain.


15. Wi-Fi Communication

Document:

ESP32
  │
  │ SSID/password
  ▼
Wi-Fi router
  │
  ▼
Internet
  │
  ▼
n8n server

Include:

  • Connection procedure

  • Reconnection

  • Timeout

  • Authentication

  • TLS/HTTPS

  • Offline buffering

  • Retry mechanism


16. HTTP/M QTT Protocol

You can support either HTTP or MQTT.

HTTP

POST /webhook/smart-pillow
Content-Type: application/json

MQTT

Topic:

smartpillow/device01/telemetry

Payload:

{
  "movement": 0.72,
  "pressure": 61,
  "temperature": 28.4
}

For a first prototype, HTTPS POST to an n8n webhook is simpler. MQTT becomes attractive when you have multiple devices or require continuous publish/subscribe telemetry.


17. JSON Data Format

Define a formal schema.

{
  "device_id": "SMARTPILLOW_01",
  "timestamp": "2026-09-29T21:30:00+05:30",
  "sensors": {
    "movement": 0.72,
    "pressure_left": 61,
    "pressure_center": 43,
    "pressure_right": 18,
    "temperature": 28.4,
    "humidity": 61,
    "sound_level": 68
  },
  "events": {
    "movement_event": true,
    "sound_event": true
  }
}

18. n8n Installation

Document:

Install n8n
     ↓
Create credentials
     ↓
Create webhook
     ↓
Configure processing
     ↓
Configure AI
     ↓
Configure Telegram
     ↓
Configure Google Sheets
     ↓
Configure ThingSpeak
     ↓
Activate workflow

Also document whether n8n is running:

  • Locally

  • Docker

  • VPS

  • Cloud-hosted server


19. Complete n8n Workflow

The finished workflow should look approximately like:

                 Webhook
                    │
                    ▼
              Validate JSON
                    │
                    ▼
             Normalize Data
                    │
                    ▼
             Basic Rule Check
                    │
                    ▼
                AI Agent
                    │
              ┌─────┴─────┐
              ▼           ▼
            Normal      Alert
              │           │
              ▼           ▼
         Google Sheets  Telegram
              │           │
              ▼           ▼
          ThingSpeak   Voice Alert

The documentation should include screenshots of every important n8n node and its configuration.


20. AI-Agent Prompt and Logic

Document:

  • System prompt

  • Input schema

  • Output schema

  • Decision rules

  • Thresholds

  • Safety constraints

  • Error handling

Example:

INPUT
 ↓
Sensor observations
 ↓
Rule engine
 ↓
AI Agent
 ↓
Structured JSON
 ↓
Action router

The AI should not be instructed to diagnose a disease from these signals.


21. Telegram Bot Configuration

Document:

  1. Create Telegram bot.

  2. Obtain bot token.

  3. Configure n8n credentials.

  4. Obtain permitted chat ID.

  5. Configure message node.

  6. Test /start.

  7. Test /status.

  8. Test alert message.

Example:

/start
/status
/report
/events

22. Telegram Voice-Alert Pipeline

AI Agent
    │
    ▼
Alert decision
    │
    ▼
Generate natural-language message
    │
    ▼
Text-to-Speech
    │
    ▼
Audio file
    │
    ▼
Telegram Bot
    │
    ▼
User's phone

Example:

"Smart Pillow alert.
A repeated sleep disturbance was detected.
Please review the sleep-session data."

23. Google Sheets Integration

Columns:

Timestamp
Device ID
Session ID
Movement
Pressure
Temperature
Humidity
Sound
Event
Severity
AI Summary
Notification Sent

The documentation should explain:

  • Authentication

  • Spreadsheet creation

  • Column mapping

  • Append operation

  • Error handling


24. ThingSpeak Integration

Document :

ESP32/n8n
     │
     ▼
ThingSpeak
     │
     ├── Field 1: Movement
     ├── Field 2: Pressure
     ├── Field 3: Temperature
     ├── Field 4: Humidity
     ├── Field 5: Sound
     ├── Field 6: Event
     └── Field 7: Alert level

Include screenshots of the resulting charts.


25. Web Dashboard

The dashboard can show:

┌──────────────────────────────────────────────┐
│             AI SMART PILLOW                 │
├──────────────────────────────────────────────┤
│ Device: 🟢 ONLINE                           │
│ Session: 01                                  │
│                                               │
│ Temperature     28.4 °C                      │
│ Humidity        61 %                         │
│ Movement        72 %                         │
│ Pressure        61                            │
│ Sound event     DETECTED                     │
│                                               │
│ ─────── Live Sensor Graph ───────────────    │
│                                               │
│ ─────── Event History ───────────────────    │
│ 02:17  Disturbance                           │
│ 03:06  Movement event                        │
└──────────────────────────────────────────────┘

26. Database/Data Model

Define:

Device

device_id
device_name
firmware_version
last_seen
status

Sleep session

session_id
device_id
start_time
end_time

Sensor record

record_id
session_id
timestamp
movement
pressure
temperature
humidity
sound

Event

event_id
session_id
timestamp
event_type
severity
ai_summary
notification_status

27. Flowcharts

Include at least:

System flowchart

START
  ↓
Initialize ESP32
  ↓
Initialize sensors
  ↓
Connect Wi-Fi
  ↓
Read sensors
  ↓
Process data
  ↓
Create JSON
  ↓
Send to n8n
  ↓
AI analysis
  ↓
Event?
 ┌┴─────┐
No     Yes
 │       │
 ▼       ▼
Log    Alert
 │       │
 └───┬───┘
     ▼
Repeat

28. Sequence Diagrams

Normal operation

ESP32       n8n       AI       Sheets       ThingSpeak
  │           │        │           │             │
  │──data────►│        │           │             │
  │           │──data─►│           │             │
  │           │◄─JSON──│           │             │
  │           │────────────log────►│             │
  │           │────────────────────────data──────►│
  │           │        │           │             │

Alert operation

ESP32 → n8n → AI Agent
              │
              ▼
          Alert detected
              │
        ┌─────┴─────┐
        ▼           ▼
    Telegram     Sheets
        │
        ▼
    Voice alert

29. Testing Methodology

Testing should cover:

Hardware testing

  • Sensor connectivity

  • Voltage

  • Current

  • ADC response

  • I²C communication

  • Wi-Fi stability

Software testing

  • JSON generation

  • Webhook reception

  • AI response

  • Google Sheets

  • ThingSpeak

  • Telegram

End-to-end testing

Sensor
 ↓
ESP32
 ↓
Wi-Fi
 ↓
n8n
 ↓
AI
 ↓
Cloud
 ↓
Telegram

30. Test Cases

Example:

Test Input Expected result
T01 Power ON ESP32 boots
T02 Wi-Fi available Device connects
T03 Wi-Fi disconnected Reconnection attempted
T04 Sensor movement Movement value changes
T05 Webhook request n8n receives JSON
T06 Normal data Logged without alert
T07 Alert condition Telegram notification
T08 Data record Google Sheets updated
T09 Telemetry ThingSpeak updated
T10 Telegram command Bot responds

31. Error Handling

Handle:

Sensor failure
Wi-Fi failure
Internet failure
n8n unavailable
AI API failure
Google Sheets failure
ThingSpeak failure
Telegram failure
Invalid JSON
Low power
ESP32 crash

Example:

Wi-Fi lost
   ↓
Retry connection
   ↓
Still unavailable?
   ↓
Store data locally
   ↓
Connection restored
   ↓
Upload buffered records

32. Security

This section is essential.

Include:

  • HTTPS

  • API-key protection

  • Telegram bot-token protection

  • Wi-Fi credential protection

  • n8n authentication

  • Access control

  • Secrets management

  • Input validation

  • Rate limiting

  • Secure OTA

  • No hard-coded production credentials

Never put real credentials in the published source code.

Use:

#define WIFI_SSID "..."
#define WIFI_PASSWORD "..."
#define N8N_TOKEN "..."

only in a private configuration file that is excluded from Git.


33. Privacy

The project may potentially process sensitive sleep-related information.

Document:

  • What data is collected

  • Why it is collected

  • Where it is stored

  • Who can access it

  • How long it is retained

  • Whether audio is stored

  • Whether raw sensor data leaves the device

  • How the user can delete the data

If audio is only used to calculate an event feature, consider processing it locally and transmitting features/events rather than raw audio.


34. Limitations

Be explicit.

Examples:

  • Prototype sensor accuracy

  • Pillow-position dependence

  • Individual differences

  • Limited training data

  • False positives

  • False negatives

  • Wi-Fi dependence

  • Cloud-service dependency

  • AI interpretation uncertainty

  • Lack of clinical validation

Most importantly:

The prototype should not be represented as a clinically validated diagnostic device or as proof that a user has a specific sleep disorder.


35. Future Improvements

Possible future versions:

ESP32-S3
      ↓
Edge AI
      ↓
TinyML model
      ↓
Local event detection

Other improvements:

  • Flexible pressure-sensor matrix

  • Better acoustic processing

  • Edge AI

  • Personalized sleep models

  • On-device anomaly detection

  • BLE connectivity

  • Battery operation

  • Low-power modes

  • Secure OTA

  • Mobile application

  • More sophisticated dashboard

  • Multi-user support

  • Long-term trend analysis


36. Cost/BOM

Final report should contain something like:

Component Qty Estimated cost Total
ESP32 1 ₹___ ₹___
MPU6050 1 ₹___ ₹___
Pressure sensors ___ ₹___ ₹___
Temperature sensor 1 ₹___ ₹___
Microphone 1 ₹___ ₹___
PCB/wires — ₹___ ₹___
Pillow enclosure 1 ₹___ ₹___
Power supply 1 ₹___ ₹___
Total     ₹___

Prices should be filled using the actual components you purchase rather than assumed values.


37. Installation Procedure

A good installation chapter should be reproducible by another student.

Step 1 → Assemble hardware
Step 2 → Flash ESP32 firmware
Step 3 → Configure Wi-Fi
Step 4 → Create n8n instance
Step 5 → Import workflow
Step 6 → Configure credentials
Step 7 → Create Telegram bot
Step 8 → Configure Google Sheets
Step 9 → Create ThingSpeak channel
Step 10 → Start dashboard
Step 11 → Power Smart Pillow
Step 12 → Verify telemetry
Step 13 → Test alert
Step 14 → Start sleep-session recording

38. Troubleshooting

Create a table:

Problem Possible cause Solution
ESP32 doesn't boot Power issue Check 5 V/3.3 V
Sensor unavailable Wiring Check SDA/SCL
Wi-Fi fails Credentials Verify SSID/password
n8n receives nothing Webhook/network Test endpoint
Telegram doesn't alert Bot credentials/chat ID Verify credentials
Sheets not updating Authentication Reauthorize
Dashboard empty Wrong channel/API Check ThingSpeak configuration
AI output invalid Prompt/API issue Validate structured output

39 . Results

This section should contain actual measured results, not expected results.

Recommended measurements:

Sensor performance

Pressure response
Movement response
Temperature stability
Sound/event detection

Communication performance

ESP32 → n8n latency
n8n processing time
Telegram notification latency
Cloud update interval

Reliability

24-hour test
Wi-Fi reconnection
Sensor failure recovery
Server failure recovery

Example result table

Parameter Measured result
ESP32 → n8n latency ___ ms
Telegram alert latency ___ sec
Wi-Fi reconnection ___ sec
Sensor sampling rate ___ Hz
Successful transmissions ___ %
False alerts during test ___
Missed events ___

40. Conclusion

The conclusion should summarize what was actually built and demonstrated.

A suitable conclusion would state that the project successfully demonstrates an integrated ESP32 + IoT + n8n + AI + cloud + Telegram architecture for experimental sleep monitoring, while clearly identifying the limitations of the prototype and the need for further validation before any medical application.


Recommended final project architecture

The complete project can ultimately be presented as:

                         AI SMART PILLOW
                              │
                    ┌─────────┴─────────┐
                    │                   │
                 SENSORS            ESP32
                    │                   │
                    └─────────┬─────────┘
                              │
                           Wi-Fi
                              │
                              ▼
                    ┌─────────────────┐
                    │   n8n WEBHOOK   │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │ DATA PROCESSING  │
                    └────────┬────────┘
                             │
                             ▼
                    ┌─────────────────┐
                    │    AI AGENT     │
                    └────────┬────────┘
                             │
               ┌─────────────┼─────────────┐
               │             │             │
               ▼             ▼             ▼
         Google Sheets   ThingSpeak    Telegram
               │             │             │
               │             ▼             ▼
               │        Cloud Graphs   Text/Voice
               │                           │
               └─────────────┬─────────────┘
                             ▼
                       WEB DASHBOARD
                             │
                             ▼
                           USER

This structure is suitable for turning the project into a full engineering report, implementation manual, GitHub README, viva presentation, and demonstration project rather than just a conceptual description.

 

🧠 AI Smart Pillow — Project Mind Map

                         ┌──────────────────────────────┐
                         │     🛏️ AI SMART PILLOW       │
                         │   Sleep Monitoring + IoT AI   │
                         └──────────────┬───────────────┘
                                        │
          ┌─────────────────────────────┼─────────────────────────────┐
          │                             │                             │
          ▼                             ▼                             ▼
   🔧 HARDWARE                    🧠 AI & SOFTWARE              ☁️ CLOUD / IoT
          │                             │                             │
    ┌─────┼─────┐                 ┌─────┼─────┐                ┌─────┼─────┐
    │     │     │                 │     │     │                │     │     │
    ▼     ▼     ▼                 ▼     ▼     ▼                ▼     ▼     ▼
 ESP32  Sensors Power           Firmware n8n  AI Agent       Wi-Fi  Sheets ThingSpeak
    │     │                       │       │       │
    │     ├─ Pressure             │       │       ├─ Event analysis
    │     ├─ MPU6050              │       │       ├─ Classification
    │     ├─ Temperature          │       │       └─ Decision
    │     ├─ Humidity             │       │
    │     └─ Audio/Event          │       ├─ Webhook
    │                             │       ├─ Processing
    └────────── GPIO/I²C/ADC ─────┘       ├─ Routing
                                          └─ Automation


                     ┌────────────────────────────────┐
                     │       📡 DATA PIPELINE          │
                     └───────────────┬────────────────┘
                                     │
        ┌────────────────────────────┼────────────────────────────┐
        ▼                            ▼                            ▼
   Sensor Data                  JSON Payload                 Timestamp
        │                            │                            │
        └────────────────────────────┼────────────────────────────┘
                                     ▼
                              ┌─────────────┐
                              │    n8n      │
                              └──────┬──────┘
                                     ▼
                              Data Validation
                                     │
                                     ▼
                              AI Agent Analysis
                                     │
                         ┌───────────┼───────────┐
                         ▼           ▼           ▼
                      NORMAL     DISTURBANCE   WARNING
                         │           │           │
                         └───────────┼───────────┘
                                     ▼
                              Action / Automation
                                     │
                ┌────────────────────┼────────────────────┐
                ▼                    ▼                    ▼
           Google Sheets         ThingSpeak           Telegram
                │                    │                    │
                ▼                    ▼                    ▼
            Historical            Graphs             Text Alert
              Data                                      │
                                                        ▼
                                                  Voice Alert

🔩 Hardware Branch

AI Smart Pillow
      │
      └── Hardware
           ├── ESP32
           │    ├── GPIO
           │    ├── ADC
           │    ├── I²C
           │    └── Wi-Fi
           │
           ├── Pressure Sensors
           │    └── Pressure distribution
           │
           ├── MPU6050
           │    ├── Movement
           │    └── Orientation
           │
           ├── Temperature/Humidity
           │
           ├── Microphone
           │    └── Acoustic events
           │
           └── Power Supply

💻 Software Branch

Software
│
├── ESP32 Firmware
│   ├── Sensor drivers
│   ├── Calibration
│   ├── Filtering
│   ├── Event detection
│   ├── JSON generation
│   └── Wi-Fi communication
│
├── n8n
│   ├── Webhook
│   ├── Validation
│   ├── Data processing
│   ├── AI Agent
│   ├── IF / routing
│   └── Error handling
│
├── AI
│   ├── Sensor interpretation
│   ├── Event classification
│   ├── Severity
│   └── Notification decision
│
└── Web Dashboard
    ├── Live status
    ├── Sensor values
    ├── Event history
    └── Graphs

📱 Notification Branch

AI Agent
   │
   ▼
Alert Decision
   │
   ├── No Alert
   │
   └── Alert
        │
        ▼
     Telegram
        │
        ├── Text Message
        │
        └── Text-to-Speech
                 │
                 ▼
             Voice File
                 │
                 ▼
              User

☁️ Cloud/Data Branch

                n8n
                 │
       ┌─────────┼─────────┐
       ▼         ▼         ▼
 Google Sheets ThingSpeak Telegram
       │         │         │
       ▼         ▼         ▼
 Historical    Charts    Notifications
   Records

🔐 Security & Privacy Branch

Security / Privacy
│
├── HTTPS
├── API authentication
├── Secret management
├── Telegram token protection
├── Wi-Fi credential protection
├── Input validation
├── Access control
├── Secure OTA
└── Data retention

🧪 Testing Branch

Testing
│
├── Hardware
│   ├── Sensor test
│   ├── Power test
│   └── ESP32 test
│
├── Communication
│   ├── Wi-Fi
│   ├── HTTP/MQTT
│   └── n8n webhook
│
├── AI
│   ├── Normal event
│   ├── Disturbance
│   └── Warning
│
├── Cloud
│   ├── Google Sheets
│   └── ThingSpeak
│
└── Telegram
    ├── Text
    └── Voice

🚀 Future Development

Future
│
├── Edge AI / TinyML
├── ESP32-S3
├── Flexible pressure matrix
├── Better acoustic processing
├── Personalized models
├── Mobile application
├── Battery operation
├── Secure OTA
├── Long-term sleep trends
└── Clinical validation research

One-line mind map

🛏️ Smart Pillow
→ Sensors
→ ESP32
→ Wi-Fi
→ n8n
→ AI Agent
→ Decision
→ Google Sheets + ThingSpeak + Telegram
→ Voice Alert
→ Web Dashboard
→ Testing + Security + Privacy
→ Future AI/IoT Improvements

This gives you the complete high-level map from physical sensor → ESP32 → AI agent → automation → cloud → user notification.

 

AI Smart Organic Farming using Weather Prediction & Soil Analysis

AI Smart Organic Farming Using Weather Prediction, Soil Analysis, ESP32, IoT, n8n, AI Agent, Telegram Voice Alerts, Google Sheets & Thing Speak

Below is a complete reference architecture that you can use as a final-year project, diploma project, engineering project, prototype, or real farm automation system.

The design combines:

  • ESP32 IoT controller

  • Soil-moisture sensing

  • Temperature/humidity sensing

  • Optional soil pH/NPK sensing

  • Weather prediction

  • AI-based agricultural decision support

  • Automatic irrigation

  • n8n workflow automation

  • AI Agent

  • Telegram text + voice alerts

  • Google Sheets logging

  • ThingSpeak cloud dashboard

  • ESP32 local IoT webpage

  • Remote monitoring

  • Safety/override logic

ESP32 is well suited for this because its Arduino core supports Wi-Fi station mode for Internet-connected IoT applications. Espressif Systems+1


1. Project Title

AI Smart Organic Farming System Using Weather Prediction, Soil Analysis and Agentic IoT Automation

Short name

AI-AgriSense: ESP32 + n8n + AI Agent + Weather + Telegram + ThingSpeak


2. Abstract

The proposed system is an intelligent IoT-based organic farming platform that continuously monitors soil and environmental conditions and uses weather information and AI-based decision-making to assist with irrigation and crop management.

An ESP32 controller collects data from soil-moisture and environmental sensors. The measurements are transmitted through Wi-Fi to an n8n automation server.

n8n acts as the central orchestration layer. It receives sensor data, obtains weather information, stores measurements in Google Sheets, updates ThingSpeak, evaluates irrigation conditions, and communicates with an AI Agent.

The AI Agent analyzes parameters such as:

  • soil moisture

  • air temperature

  • humidity

  • soil temperature

  • rainfall probability

  • expected rainfall

  • recent irrigation

  • crop type

  • soil type

  • user-defined moisture limits

The system can then generate an agricultural recommendation such as:

"Soil moisture is low, but significant rainfall is expected within the next few hours. Delay irrigation and recheck the soil later."

or:

"Soil moisture is critically low and no useful rainfall is expected. Irrigation is recommended for 8 minutes."

The final actuator decision should still pass through deterministic safety rules rather than allowing an LLM to directly operate a pump.

The system can send an alert through Telegram and optionally generate a spoken voice message. Telegram's Bot API supports voice messages through sendVoice; Telegram documents OGG/Opus voice messages and separate audio-file handling. Telegram Core


3. Main Objectives

The project has eight major objectives.

  1. Monitor soil conditions

  2. Monitor environmental conditions

  3. Retrieve weather forecasts

  4. Predict irrigation requirements

  5. Use AI for agricultural recommendations

  6. Automatically control irrigation

  7. Store historical farm data

  8. Notify the farmer through Telegram


4. Complete System Architecture

                         ┌─────────────────────┐
                         │     FARM / FIELD    │
                         └──────────┬──────────┘
                                    │
              ┌─────────────────────┼──────────────────────┐
              │                     │                      │
              ▼                     ▼                      ▼
       Soil Moisture            DHT22                  Soil pH
          Sensor               Temp/Humidity           Sensor
              │                     │                      │
              └─────────────────────┼──────────────────────┘
                                    │
                                    ▼
                           ┌────────────────┐
                           │     ESP32      │
                           │ IoT Controller │
                           └───────┬────────┘
                                   │
                       Wi-Fi / HTTPS / JSON
                                   │
                                   ▼
                         ┌──────────────────┐
                         │       n8n        │
                         │ Automation Hub   │
                         └────────┬─────────┘
                                  │
             ┌────────────────────┼───────────────────┐
             │                    │                   │
             ▼                    ▼                   ▼
       Weather API             AI Agent          Google Sheets
             │                    │                   │
             │                    ▼                   │
             │             Agricultural              │
             │             Recommendation            │
             │                    │                   │
             └────────────────────┼───────────────────┘
                                  │
                                  ▼
                         ┌─────────────────┐
                         │ Safety / Rules  │
                         │ Decision Layer  │
                         └────────┬────────┘
                                  │
                         ┌────────┴─────────┐
                         │                  │
                         ▼                  ▼
                     Irrigation          Telegram
                      Control             Alert
                         │                  │
                         ▼                  ▼
                       Relay          Text + Voice
                         │
                         ▼
                     Water Pump

                                  │
                                  ▼
                           ┌─────────────┐
                           │ ThingSpeak  │
                           │ Cloud       │
                           │ Dashboard   │
                           └─────────────┘

ThingSpeak supports REST-based channel updates using api.thingspeak.com/update, with up to eight channel fields available for sensor values. MathWorks+1


5. Hardware Required

Essential hardware

Component Quantity Purpose
ESP32 DevKit 1 Main controller
Capacitive soil-moisture sensor 1–4 Soil moisture
DHT22 1 Temperature/humidity
1-channel/2-channel relay 1 Pump control
DC water pump 1 Irrigation
Water pipe As required Irrigation
5V/12V power supply 1 Pump
USB power supply 1 ESP32
Jumper wires As required Connections
Breadboard/PCB 1 Prototype

Optional sensors

Sensor Purpose
DS18B20 Soil temperature
pH sensor Soil pH
NPK sensor Nitrogen/phosphorus/potassium
Rain sensor Local rain detection
LDR Sunlight
Water-level sensor Tank monitoring
Flow sensor Measure irrigation quantity

Recommendation

For the first working prototype, use:

ESP32 + capacitive soil sensor + DHT22 + relay + pump.

Then add pH/NPK/rain/water-level sensors.


6. ESP32 Pin Configuration

Example:

ESP32
────────────────────────────
GPIO 34  ← Soil Moisture
GPIO 4   ← DHT22 DATA
GPIO 27  ← Relay
GPIO 26  ← Water Level
GPIO 25  ← Rain Sensor
GPIO 18  ← DS18B20
3.3V     → Sensors
GND      → Common GND

Example pin table

Device ESP32
Soil moisture AO GPIO34
DHT22 DATA GPIO4
Relay IN GPIO27
Water sensor GPIO26
Rain sensor GPIO25
DS18B20 DATA GPIO18

Important: ESP32 GPIOs are 3.3-V logic. Do not feed 5 V directly into an ESP32 input.

For a pump, don't power the pump from the ESP32. Use an appropriately rated external supply and relay/MOSFET driver.


7. Electrical Schematic

Sensor side

              ESP32
        ┌────────────────┐
        │                │
        │ GPIO34 ◄───────┼──── Soil Moisture AO
        │                │
        │ GPIO4  ◄───────┼──── DHT22 DATA
        │                │
        │ GPIO27 ────────┼──── Relay IN
        │                │
        │ 3.3V ──────────┼──── Sensor VCC
        │                │
        │ GND ───────────┼──── Sensor GND
        └────────────────┘

Pump circuit

              AC/DC SUPPLY
                   │
                   │
             ┌─────▼─────┐
             │   RELAY   │
             │           │
             │ COM   NO  │
             └─┬─────┬───┘
               │     │
               │     └──────── Pump +
               │
          Supply +
               
Pump -
   │
   └──────────────────────── Supply -

For mains-voltage pumps, use an appropriately rated enclosure, fuse/protection, isolation and qualified electrical installation. For a student prototype, a low-voltage DC pump is much safer.


8. Soil Moisture Measurement

A resistive sensor can corrode over time. A capacitive soil-moisture sensor is preferable for a long-running prototype.

The raw ADC reading must be calibrated.

For example:

Dry soil ADC = 3200
Wet soil ADC = 1300

Then:

moisturePercent =
       (dryADC - currentADC)
       ---------------------- × 100
       (dryADC - wetADC)

Clamp the result between 0 and 100.

Example:

currentADC = 2200

moisture =
(3200 - 2200)/(3200 - 1300) × 100

= 52.6%

9. Irrigation Decision Logic

Don't simply use:

if moisture < 40%
    pump ON

Instead use multiple parameters.

Example:

IF soil moisture < minimum threshold
AND rain forecast < rain threshold
AND water tank available
AND temperature is reasonable
THEN irrigation recommended

If substantial rainfall is predicted:

IF soil moisture < threshold
AND rainfall probability > 70%
THEN delay irrigation

Example:

Moisture = 28%

Rain probability = 10%
Rain forecast = 0 mm

→ Irrigation ON

Another situation:

Moisture = 28%

Rain probability = 85%
Rain forecast = 15 mm

→ Irrigation OFF
→ Wait for rainfall

10. AI Agent Architecture

The AI Agent should not directly control the relay without safeguards.

Use:

Sensors
   ↓
Weather
   ↓
AI Agent
   ↓
Recommendation
   ↓
Deterministic Safety Rules
   ↓
Actuator

The AI Agent can perform reasoning:

"What should the farmer do?"

The safety layer determines:

"Is the requested action actually allowed?"

This is much safer than:

LLM → Pump

11. AI Agent Tools

The n8n AI Agent can conceptually have these tools:

AI AGRICULTURE AGENT
│
├── get_sensor_data()
│
├── get_weather_forecast()
│
├── get_crop_profile()
│
├── get_historical_data()
│
├── calculate_irrigation()
│
├── log_decision()
│
├── send_farmer_alert()
│
└── request_irrigation()

For example, the AI receives:

{
  "crop": "Tomato",
  "soil_moisture": 27,
  "temperature": 31,
  "humidity": 46,
  "rain_probability": 15,
  "forecast_rain_mm": 0,
  "last_irrigation_minutes": 0,
  "tank_level": 82
}

AI output:

{
  "decision": "IRRIGATE",
  "duration_minutes": 8,
  "reason": "Soil moisture is below the configured minimum and significant rainfall is not expected."
}

12. Weather Prediction

The system can use a weather API such as OpenWeather.

OpenWeather's current-weather API supports location coordinates and provides temperature, humidity, pressure, wind, cloud information and precipitation where available. OpenWeather

For example:

Latitude
Longitude
   │
   ▼
Weather API
   │
   ▼
Temperature
Humidity
Rain
Wind
Forecast
   │
   ▼
n8n

Use coordinates rather than relying on old city-name approaches when possible. OpenWeather's current documentation recommends coordinate-based requests and provides API-key authentication. OpenWeather+1


13. Recommended Weather Parameters

Collect:

temperature
humidity
rain probability
rainfall
wind speed
cloud cover
forecast temperature
forecast rainfall

The agricultural decision becomes:

Soil + Weather + Crop + History
              │
              ▼
           AI Agent
              │
              ▼
        Farm Decision

14. n8n Overall Workflow

Create the following workflow:

Webhook
   ↓
Validate ESP32 Data
   ↓
Store Raw Data
   ↓
Get Weather
   ↓
Get Crop Configuration
   ↓
AI Agent
   ↓
Safety Rules
   ↓
 ┌───────────────┬───────────────┐
 │               │               │
 ▼               ▼               ▼
Pump ON        Pump OFF        Warning
 │               │               │
 ▼               └───────┬───────┘
Telegram                 │
 │                       │
 ▼                       ▼
Voice Alert          Google Sheets
 │                       │
 └───────────┬───────────┘
             ▼
        ThingSpeak

15. n8n Workflow 1 — ESP32 Data Receiver

Create:

Webhook

Method:

POST

Example endpoint:

POST /webhook/farm-sensor

ESP32 sends:

{
  "device_id": "FARM001",
  "soil_moisture": 31.5,
  "temperature": 29.4,
  "humidity": 63,
  "soil_temperature": 27.2,
  "rain_sensor": 0,
  "tank_level": 76
}

16. n8n Validation Node

Use a Code node:

const d = $json;

const required = [
  "device_id",
  "soil_moisture",
  "temperature",
  "humidity"
];

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

if (d.soil_moisture < 0 || d.soil_moisture > 100) {
  throw new Error("Invalid soil moisture");
}

if (d.humidity < 0 || d.humidity > 100) {
  throw new Error("Invalid humidity");
}

return [
  {
    json: {
      ...d,
      received_at: new Date().toISOString()
    }
  }
];

17. Weather API Node

n8n HTTP Request:

GET

Example:

https://api.openweathermap.org/data/2.5/weather

Parameters:

lat     = YOUR_LATITUDE
lon     = YOUR_LONGITUDE
appid   = YOUR_API_KEY
units   = metric

For more advanced forecasting, use the forecast API available under your OpenWeather plan.


18. Combining Sensor + Weather Data

Use an n8n Code node:

const sensor = $('Validate Sensor Data').first().json;
const weather = $json;

return [
  {
    json: {
      device_id: sensor.device_id,

      soil_moisture: sensor.soil_moisture,
      temperature: sensor.temperature,
      humidity: sensor.humidity,

      weather_temperature: weather.main?.temp,
      weather_humidity: weather.main?.humidity,
      wind_speed: weather.wind?.speed,

      weather_description:
        weather.weather?.[0]?.description || "unknown",

      timestamp: new Date().toISOString()
    }
  }
];

19. AI Agent Prompt

Use a structured prompt rather than asking the AI to simply "control my farm."

Example:

You are an agricultural decision-support AI.

Analyze the sensor and weather information.

Your objectives are:
1. Avoid unnecessary irrigation.
2. Prevent prolonged soil dryness.
3. Consider predicted rainfall.
4. Consider crop type.
5. Consider soil type.
6. Never exceed the configured maximum irrigation duration.
7. Never irrigate when the water tank is empty.
8. Return structured JSON only.

Return:

{
  "decision": "IRRIGATE | WAIT | ALERT",
  "duration_minutes": number,
  "reason": "short explanation",
  "risk": "LOW | MEDIUM | HIGH"
}

Do not directly assume that your recommendation will activate a pump.
A separate safety controller will validate the recommendation.

20. Example AI Response

{
  "decision": "IRRIGATE",
  "duration_minutes": 7,
  "reason": "Soil moisture is significantly below the target range and meaningful rainfall is not expected.",
  "risk": "LOW"
}

21. Safety Rule Engine

This is extremely important.

Use deterministic rules after the AI.

const d = $json;

let approved = false;
let reason = "";

const moisture = Number(d.soil_moisture);
const rainProbability = Number(d.rain_probability || 0);
const tankLevel = Number(d.tank_level || 0);
const requestedMinutes = Number(d.duration_minutes || 0);

if (tankLevel < 10) {
  approved = false;
  reason = "Water tank level too low";
}
else if (rainProbability >= 70) {
  approved = false;
  reason = "Significant rainfall expected";
}
else if (moisture >= 45) {
  approved = false;
  reason = "Soil moisture already sufficient";
}
else if (requestedMinutes <= 0) {
  approved = false;
  reason = "Invalid irrigation duration";
}
else {
  approved = true;
  reason = "Irrigation conditions satisfied";
}

return [
  {
    json: {
      ...d,
      irrigation_approved: approved,
      safety_reason: reason,
      irrigation_minutes: approved
        ? Math.min(requestedMinutes, 15)
        : 0
    }
  }
];

22. Pump Control

There are two approaches.

Approach A — ESP32 polls n8n

ESP32
 ↓
GET /farm-command
 ↓
n8n
 ↓
COMMAND
 ↓
ESP32
 ↓
Relay

Approach B — n8n sends command to ESP32

For an Internet-based installation, a better architecture is often:

ESP32 → MQTT/HTTP → Cloud
Cloud → Command → ESP32

For a simple student project, use HTTP.


23. Recommended ESP32 API

The ESP32 can expose:

GET /
GET /api/status
GET /api/sensors
GET /api/pump/on
GET /api/pump/off
GET /api/command

Example:

http://192.168.1.50/

opens the local farm dashboard.


24. ESP32 Local Webpage

Example UI:

┌─────────────────────────────────────┐
│       🌱 AI SMART FARM              │
├─────────────────────────────────────┤
│ Soil Moisture       31 %            │
│ Temperature         29.4 °C         │
│ Humidity             63 %           │
│ Tank Level           76 %           │
│                                     │
│ Pump Status          OFF             │
│                                     │
│ AI Recommendation                   │
│ Irrigation required                 │
│                                     │
│ [ START PUMP ] [ STOP PUMP ]        │
└─────────────────────────────────────┘

25. ESP32 Complete Example Code

The following is a prototype starting point.

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

#define DHT_PIN 4
#define DHT_TYPE DHT22

#define SOIL_PIN 34
#define RELAY_PIN 27

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

const char* N8N_WEBHOOK =
  "https://YOUR-N8N-DOMAIN/webhook/farm-sensor";

const char* THINGSPEAK_API =
  "YOUR_THINGSPEAK_WRITE_KEY";

DHT dht(DHT_PIN, DHT_TYPE);
WebServer server(80);

float soilMoisture = 0;
float temperature = 0;
float humidity = 0;

bool pumpState = false;

const int DRY_VALUE = 3200;
const int WET_VALUE = 1300;

float readSoilMoisture()
{
  int raw = analogRead(SOIL_PIN);

  float moisture =
    ((float)(DRY_VALUE - raw) /
     (DRY_VALUE - WET_VALUE)) * 100.0;

  if (moisture < 0)
    moisture = 0;

  if (moisture > 100)
    moisture = 100;

  return moisture;
}

void pumpOn()
{
  digitalWrite(RELAY_PIN, LOW);
  pumpState = true;
}

void pumpOff()
{
  digitalWrite(RELAY_PIN, HIGH);
  pumpState = false;
}

void readSensors()
{
  soilMoisture = readSoilMoisture();

  temperature = dht.readTemperature();
  humidity = dht.readHumidity();

  if (isnan(temperature))
    temperature = 0;

  if (isnan(humidity))
    humidity = 0;
}

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

  json += "\"device_id\":\"FARM001\",";
  json += "\"soil_moisture\":" +
          String(soilMoisture, 2) + ",";
  json += "\"temperature\":" +
          String(temperature, 2) + ",";
  json += "\"humidity\":" +
          String(humidity, 2) + ",";
  json += "\"pump\":";
  json += pumpState ? "1" : "0";

  json += "}";

  return json;
}

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

  HTTPClient http;

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

  String payload = createJSON();

  int response =
    http.POST(payload);

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

  http.end();
}

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

  HTTPClient http;

  String url =
    "https://api.thingspeak.com/update";

  http.begin(url);

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

  String data =
    "api_key=" + String(THINGSPEAK_API) +
    "&field1=" + String(soilMoisture) +
    "&field2=" + String(temperature) +
    "&field3=" + String(humidity) +
    "&field4=" + String(pumpState);

  int response =
    http.POST(data);

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

  http.end();
}

void handleRoot()
{
  readSensors();

  String html;

  html += "<html>";
  html += "<head>";
  html += "<meta name='viewport' "
          "content='width=device-width,initial-scale=1'>";
  html += "<style>";
  html += "body{font-family:Arial;background:#eef7ee;";
  html += "padding:20px;text-align:center}";
  html += ".card{background:white;padding:20px;";
  html += "margin:10px;border-radius:15px}";
  html += "button{padding:15px;margin:5px;";
  html += "font-size:16px}";
  html += "</style>";
  html += "</head>";

  html += "<body>";

  html += "<h1>🌱 AI Smart Farm</h1>";

  html += "<div class='card'>";
  html += "<h2>Soil Moisture</h2>";
  html += "<h1>" +
          String(soilMoisture, 1) +
          "%</h1>";
  html += "</div>";

  html += "<div class='card'>";
  html += "<h2>Temperature</h2>";
  html += "<h1>" +
          String(temperature, 1) +
          " °C</h1>";
  html += "</div>";

  html += "<div class='card'>";
  html += "<h2>Humidity</h2>";
  html += "<h1>" +
          String(humidity, 1) +
          "%</h1>";
  html += "</div>";

  html += "<div class='card'>";
  html += "<h2>Pump</h2>";

  html += pumpState ? "ON" : "OFF";

  html += "<br><br>";

  html += "<a href='/pump/on'>";
  html += "<button>START PUMP</button>";
  html += "</a>";

  html += "<a href='/pump/off'>";
  html += "<button>STOP PUMP</button>";
  html += "</a>";

  html += "</div>";

  html += "</body></html>";

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

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

  pinMode(RELAY_PIN, OUTPUT);

  pumpOff();

  dht.begin();

  WiFi.begin(
    WIFI_SSID,
    WIFI_PASSWORD
  );

  Serial.print("Connecting WiFi");

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

  Serial.println();

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);

  server.on("/pump/on", []()
  {
    pumpOn();
    server.sendHeader(
      "Location",
      "/"
    );
    server.send(
      302,
      "text/plain",
      ""
    );
  });

  server.on("/pump/off", []()
  {
    pumpOff();
    server.sendHeader(
      "Location",
      "/"
    );
    server.send(
      302,
      "text/plain",
      ""
    );
  });

  server.begin();
}

unsigned long lastUpload = 0;

void loop()
{
  server.handleClient();

  if (millis() - lastUpload > 60000)
  {
    lastUpload = millis();

    readSensors();

    Serial.println(
      createJSON()
    );

    sendToN8N();
    sendToThingSpeak();
  }
}

The current Arduino-ESP32 documentation is based on the modern ESP32 Arduino core and documents Wi-Fi functionality and APIs. Espressif Systems+1


26. ThingSpeak Configuration

Create a ThingSpeak channel:

Channel Name:
AI Smart Organic Farm

Configure fields:

Field 1 = Soil Moisture
Field 2 = Temperature
Field 3 = Humidity
Field 4 = Pump Status
Field 5 = Rain Probability
Field 6 = Rain Forecast
Field 7 = Soil Temperature
Field 8 = AI Irrigation Score

ThingSpeak channel data can be written through its REST API using the channel Write API Key. MathWorks+1

For a free license, ThingSpeak currently documents a 15-second minimum channel update interval, so a 1-minute upload interval is comfortably above that limit. MathWorks


27. ThingSpeak Dashboard

Your dashboard can contain:

┌─────────────────────────────────────────┐
│        AI SMART ORGANIC FARM            │
├─────────────────────────────────────────┤
│                                         │
│ Soil Moisture                           │
│ ███████████░░░░  31%                    │
│                                         │
│ Temperature                             │
│        📈 29.4°C                        │
│                                         │
│ Humidity                                │
│        📈 63%                           │
│                                         │
│ Rain Probability                        │
│        ☔ 15%                            │
│                                         │
│ Pump                                    │
│        ● OFF                            │
│                                         │
│ AI Recommendation                       │
│        IRRIGATE                         │
└─────────────────────────────────────────┘

28. Google Sheets Database

Create a spreadsheet called:

AI Smart Farm Data

Columns:

Timestamp
Device ID
Crop
Soil Moisture
Temperature
Humidity
Soil Temperature
Rain Probability
Forecast Rain mm
Tank Level
AI Decision
Irrigation Duration
Safety Decision
Alert Sent

Example:

Timestamp Moisture Temp Rain AI Pump
10:00 58 28 80 WAIT OFF
11:00 48 29 70 WAIT OFF
12:00 35 30 10 IRRIGATE ON
12:08 51 30 10 STOP OFF

This historical dataset can eventually be used for your own machine-learning model.


29. Telegram Architecture

              n8n
               │
               ▼
         AI Decision
               │
        ┌──────┴───────┐
        │              │
        ▼              ▼
    Telegram       TTS Engine
     Text              │
                       ▼
                  Audio File
                       │
                       ▼
                  Telegram
                  Voice Note

Telegram's Bot API supports sendVoice; the official documentation specifies OGG/Opus for voice messages and separately supports MP3/M4A for sendAudio. Telegram Core


30. Telegram Text Alert

Example message:

🌱 AI FARM ALERT

Crop: Tomato

Soil moisture: 26%
Temperature: 31°C
Humidity: 45%

Rain probability: 12%
Expected rain: 0 mm

AI recommendation:
IRRIGATE

Duration:
8 minutes

Reason:
Soil moisture is below the configured threshold
and significant rainfall is not expected.

Pump:
APPROVED

31. Telegram Voice Alert

The TTS text can be:

Attention farmer.

The tomato field has low soil moisture at twenty-six percent.

No significant rainfall is expected.

The irrigation system has been approved for eight minutes.

The TTS service generates audio, and n8n passes the resulting audio to Telegram.

For a Telegram voice note, configure the generated file in a format accepted by sendVoice, such as OGG/Opus. If using MP3/M4A instead, Telegram's sendAudio method is the appropriate API method. Telegram Core


32. Voice Alert Workflow

AI Decision
     │
     ▼
Create Voice Text
     │
     ▼
TTS API
     │
     ▼
Audio
     │
     ▼
Convert to OGG/Opus
     │
     ▼
Telegram sendVoice
     │
     ▼
👨‍🌾 Farmer's Phone

If your n8n installation supports an audio/TTS integration directly, use it. Otherwise a TTS API plus an audio conversion service can be inserted between those nodes.


33. n8n Main Workflow

Build the workflow approximately as:

[Webhook]
     │
     ▼
[Validate Sensor Data]
     │
     ▼
[Google Sheets - Raw Data]
     │
     ▼
[HTTP Request - Weather]
     │
     ▼
[Merge]
     │
     ▼
[Crop Configuration]
     │
     ▼
[AI Agent]
     │
     ▼
[Safety Rules]
     │
     ├───────────────┐
     │               │
     ▼               ▼
 APPROVED          REJECTED
     │               │
     ▼               ▼
Pump Command      Wait
     │               │
     └──────┬────────┘
            ▼
       [Google Sheets]
            │
            ▼
       [ThingSpeak]
            │
            ▼
        [Telegram]
            │
            ▼
       [Voice Alert]

34. Agentic IoT Concept

The important difference between ordinary IoT and Agentic IoT is that the system isn't simply:

Sensor → Dashboard

Instead:

Sensor
   ↓
Context
   ↓
Reasoning
   ↓
Decision
   ↓
Action
   ↓
Observation
   ↓
New Decision

Example:

ESP32:
"Soil moisture = 25%"

        ↓

Weather:
"Rain probability = 80%"

        ↓

AI:
"Wait for rainfall"

        ↓

System:
"Pump remains OFF"

        ↓

2 hours later

ESP32:
"Soil moisture = 19%"

Weather:
"Rain probability = 10%"

        ↓

AI:
"Irrigate"

        ↓

Safety:
"Approved"

        ↓

Pump:
"ON for 8 minutes"

That feedback loop is the key agentic component.


35. Complete Data Flow

┌───────────────┐
│ Soil Sensor   │
└───────┬───────┘
        │
┌───────▼───────┐
│ Temperature   │
│ Humidity      │
└───────┬───────┘
        │
        ▼
┌─────────────────┐
│      ESP32      │
│ Sensor Gateway  │
└────────┬────────┘
         │ JSON
         ▼
┌─────────────────┐
│       n8n       │
│ Workflow Engine │
└────────┬────────┘
         │
         ├──────────────► Google Sheets
         │
         ├──────────────► ThingSpeak
         │
         ▼
┌─────────────────┐
│ Weather Service │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│    AI Agent     │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Safety Engine   │
└────────┬────────┘
         │
     ┌───┴────┐
     ▼        ▼
   PUMP     WAIT
     │
     ▼
  ESP32
     │
     ▼
  RELAY
     │
     ▼
 WATER PUMP

36. AI + Rule Example

Suppose:

Crop             = Tomato
Soil moisture    = 22%
Temperature      = 34°C
Humidity         = 39%
Rain probability = 5%
Expected rain    = 0 mm
Tank level       = 80%

AI:

Decision = IRRIGATE
Duration = 10 minutes

Safety layer:

Moisture < 40%          YES
Rain probability < 70% YES
Tank > 10%              YES
Maximum duration        15 min

RESULT = APPROVED

Pump:

ON

After 10 minutes:

PUMP OFF

Then ESP32 measures the soil again.


37. Example Rain Scenario

Soil moisture = 30%

Rain probability = 90%
Expected rain = 12 mm

AI:

WAIT

Safety layer:

Irrigation = BLOCKED

Telegram:

🌧️ IRRIGATION DELAYED

Soil moisture: 30%

Rain probability: 90%
Expected rainfall: 12 mm

The system is waiting for expected rainfall
instead of using stored irrigation water.

38. Organic Farming Intelligence

You can add a crop database.

Example:

{
  "tomato": {
    "minimum_moisture": 40,
    "target_moisture": 65,
    "maximum_irrigation_minutes": 15
  },

  "chilli": {
    "minimum_moisture": 38,
    "target_moisture": 60,
    "maximum_irrigation_minutes": 12
  },

  "spinach": {
    "minimum_moisture": 45,
    "target_moisture": 70,
    "maximum_irrigation_minutes": 10
  }
}

These are example engineering thresholds, not universal agronomic recommendations. In a real deployment they should be calibrated for the specific crop variety, soil, climate, growth stage and irrigation system.


39. Soil pH Extension

For organic farming, add:

pH Sensor
   ↓
ESP32 / Analog Interface
   ↓
n8n
   ↓
AI

Example:

pH = 5.1

AI can report:

Soil pH is outside the configured crop target range.
Do not automatically apply a soil amendment.
Recommend testing/calibration and farmer review.

This is preferable to having the AI automatically dose chemicals or amendments.


40. NPK Extension

For advanced implementation:

NPK Sensor
   │
   ├── Nitrogen
   ├── Phosphorus
   └── Potassium
          │
          ▼
        ESP32
          │
          ▼
         n8n
          │
          ▼
       AI Agent

The system could generate:

N = low
P = adequate
K = adequate

and create a recommendation for farmer review.


41. Water Tank Monitoring

Add a water-level sensor:

Tank
 │
 ├── Water Level Sensor
 │
 ▼
 ESP32
 │
 ▼
 n8n

Rules:

Tank < 10%
   ↓
Pump disabled
   ↓
Telegram alert

Example:

🚨 WATER TANK ALERT

Tank level: 7%

Irrigation has been blocked
to prevent dry-running the pump.

42. Pump Protection

Add:

Maximum ON time

For example:

Maximum = 15 minutes

Even if an AI or network error occurs:

15 minutes reached
       ↓
Pump OFF

Also implement:

ESP32 local timeout

This means the cloud should never be the only safety mechanism.


43. Network Failure Protection

The ESP32 should continue operating safely if Internet connectivity disappears.

Recommended behavior:

Internet available
       ↓
Cloud AI mode

Internet unavailable
       ↓
Local fallback mode
       ↓
Simple moisture threshold
       ↓
Limited irrigation

Example:

if (WiFi.status() != WL_CONNECTED)
{
    if (soilMoisture < 25)
    {
        pumpOn();

        delay(120000);

        pumpOff();
    }
}

In a production system, avoid long blocking delays and implement the timeout using millis().


44. Security Architecture

Do not put these directly into publicly exposed HTML:

OpenWeather API key
n8n credentials
Telegram bot token
ThingSpeak write key
AI API key

Instead:

ESP32
  ↓
Authenticated webhook
  ↓
n8n credentials
  ↓
External APIs

Use:

  • HTTPS

  • webhook authentication

  • API keys stored as credentials/environment variables

  • separate ThingSpeak read/write keys

  • limited Telegram bot permissions

  • local authentication for manual pump control

ThingSpeak explicitly uses channel-level read/write API keys to control access to channel data. MathWorks+1


45. Suggested Project Directory

AI-Smart-Farm/
│
├── ESP32/
│   ├── smart_farm.ino
│   ├── config.h
│   └── webpage.h
│
├── n8n/
│   ├── sensor-workflow.md
│   ├── irrigation-workflow.md
│   └── telegram-workflow.md
│
├── AI/
│   ├── system-prompt.txt
│   └── crop_profiles.json
│
├── Dashboard/
│   └── thingspeak-config.md
│
├── Documentation/
│   ├── abstract.md
│   ├── methodology.md
│   ├── testing.md
│   └── conclusion.md
│
└── README.md

46. Project Execution Sequence

Step 1 — Assemble ESP32

Connect:

ESP32
 ↓
DHT22
 ↓
Soil moisture
 ↓
Relay
 ↓
Pump

Test each sensor separately.


Step 2 — Calibrate soil sensor

Record:

Dry soil ADC
Wet soil ADC

Change:

const int DRY_VALUE = 3200;
const int WET_VALUE = 1300;

to your actual measured values.


Step 3 — Test ESP32 webpage

Connect your phone to the same Wi-Fi.

Open:

http://ESP32-IP/

Verify:

Temperature
Humidity
Soil moisture
Pump

Step 4 — Create ThingSpeak channel

Create:

Field 1 → Soil moisture
Field 2 → Temperature
Field 3 → Humidity
Field 4 → Pump

Get the Write API Key.

Test:

https://api.thingspeak.com/update

ThingSpeak documents both GET and POST methods for channel updates. MathWorks


Step 5 — Create n8n Webhook

Create:

Webhook

Method:

POST

Copy the production webhook URL.


Step 6 — Connect ESP32 to n8n

Set:

const char* N8N_WEBHOOK =
"https://YOUR-N8N-DOMAIN/webhook/farm-sensor";

Test with:

ESP32
 ↓
n8n
 ↓
Execution successful

47. Test Using Postman/cURL

Before debugging ESP32, test n8n independently.

Example:

curl -X POST \
  "https://YOUR-N8N-DOMAIN/webhook/farm-sensor" \
  -H "Content-Type: application/json" \
  -d '{
    "device_id":"FARM001",
    "soil_moisture":25,
    "temperature":31,
    "humidity":42,
    "tank_level":80
  }'

If n8n receives this correctly, the cloud workflow is working.


48. Step 7 — Add Weather

n8n:

Sensor
 ↓
Weather HTTP Request
 ↓
Merge

Verify the weather JSON.


49. Step 8 — Add Google Sheets

Map:

Timestamp
Device
Moisture
Temperature
Humidity
Rain
AI decision
Pump

Test one row before enabling continuous operation.


50. Step 9 — Add AI Agent

Start with:

AI = recommendation only

Don't initially connect it to the pump.

For example:

ESP32
 ↓
n8n
 ↓
Weather
 ↓
AI
 ↓
Telegram

Run the system for several days and inspect the decisions.


51. Step 10 — Enable Automatic Irrigation

Only after validating the AI recommendations:

AI
 ↓
Safety Rules
 ↓
Pump command

Never:

AI → Relay

52. Step 11 — Add Telegram

Create a Telegram bot and configure its credentials in n8n.

Send:

Sensor alert
Irrigation decision
Pump start
Pump stop
Tank alert
Network alert

53. Step 12 — Add Voice

Workflow :

AI result
 ↓
Generate natural-language alert
 ↓
TTS
 ↓
OGG/Opus
 ↓
Telegram sendVoice

54. Example Complete Telegram Conversation

Farmer

/farm

AI Farm Agent

🌱 FARM STATUS

Crop: Tomato

Soil moisture: 34%
Temperature: 30.2°C
Humidity: 51%

Rain probability: 18%
Forecast rain: 0 mm

Water tank: 72%

AI status:
Irrigation recommended.

Suggested duration:
7 minutes

Safety:
APPROVED

Farmer

Why irrigation?

AI Agent

Soil moisture is below the configured
minimum range and meaningful rainfall
is not currently expected.

The recommendation is based on current
sensor measurements and weather data.

Farmer

/status

Agent

🌱 CURRENT STATUS

Soil: 41%
Temperature: 29.8°C
Humidity: 55%
Pump: OFF
Tank: 71%

Next sensor check: 10 minutes

55. Voice Conversation Concept

Farmer
   │
   │ Telegram
   ▼
n8n
   │
   ▼
AI Agent
   │
   ├── Sensor Tool
   ├── Weather Tool
   ├── Sheets Tool
   └── Farm Tool
   │
   ▼
Response
   │
   ▼
TTS
   │
   ▼
Telegram Voice

This makes Telegram effectively the farmer's conversational interface to the IoT system.


56. Advanced Agentic Architecture

For a more impressive final-year project, use:

                     ┌───────────────────┐
                     │    AI FARM AGENT  │
                     └─────────┬─────────┘
                               │
       ┌───────────────────────┼──────────────────────┐
       │                       │                      │
       ▼                       ▼                      ▼
Sensor Tool              Weather Tool          Farm History
       │                       │                      │
       ▼                       ▼                      ▼
   ESP32 data              Forecast              Sheets
       │                       │                      │
       └───────────────────────┼──────────────────────┘
                               │
                               ▼
                      Decision Engine
                               │
                    ┌──────────┴──────────┐
                    │                     │
                    ▼                     ▼
                 Irrigate                Wait
                    │                     │
                    ▼                     ▼
                  ESP32                Telegram
                    │
                    ▼
                   Pump
                    │
                    ▼
                New Sensor
                    │
                    └──────────► Agent

This creates a closed-loop intelligent IoT system.


57. Fault Handling

Your system should detect:

Sensor failure

DHT22 returns NaN
        ↓
Sensor fault
        ↓
Pump automatic mode disabled
        ↓
Telegram alert

Internet failure

Wi-Fi lost
 ↓
Local safety mode

Weather API failure

Weather unavailable
 ↓
Don't assume rain = 0
 ↓
Use conservative fallback

This is important: missing weather data should not automatically be interpreted as "no rain."

AI failure

AI unavailable
 ↓
Deterministic irrigation rules

Tank empty

Tank < minimum
 ↓
Pump OFF

58. Testing Table

Test Input Expected
Dry soil <25% Irrigation candidate
Wet soil >60% Pump OFF
Heavy rain forecast >70% probability Delay
Empty tank <10% Pump OFF
DHT failure NaN Alert
Wi-Fi failure Offline Local fallback
AI unavailable Timeout Rule-based fallback
Pump timeout >maximum Pump OFF
Manual OFF User command Pump OFF
Normal conditions Moisture adequate No irrigation

59. Performance Metrics

For your project report, measure:

Sensor accuracy

Sensor reading vs reference measurement

AI decision accuracy

AI recommendation
       vs
Agronomist/manual rule

Irrigation water saving

Compare:

Traditional schedule
        vs
AI + weather schedule

Notification latency

Sensor event
     ↓
n8n
     ↓
Telegram

Measure milliseconds/seconds.

System uptime

Uptime %

60. Database/Logging Architecture

                ESP32
                  │
                  ▼
                n8n
                  │
       ┌──────────┼───────────┐
       ▼          ▼           ▼
 Google Sheets ThingSpeak   Logs
       │          │
       ▼          ▼
Historical       Charts
Data             Dashboard

Google Sheets is convenient for demonstration and analysis; for a larger production installation, a proper time-series or relational database would be more appropriate.


61. AI Dataset for Future Machine Learning

After collecting several weeks/months:

Timestamp
Soil Moisture
Temperature
Humidity
Rain
Irrigation
Crop
Soil Type
Water Used

you can build a dataset:

INPUT

soil moisture
temperature
humidity
rain probability
rainfall
wind
crop
soil type
previous irrigation

              ↓

       MACHINE LEARNING

              ↓

OUTPUT

irrigation_required
irrigation_duration

Then your project evolves from:

AI Agent

to:

AI Agent + Predictive ML Model

62. Proposed Final Project Modules

Your project can be divided into 10 modules.

Module 1 — Sensor Layer

Soil
Temperature
Humidity
Rain
Tank

Module 2 — ESP32 IoT Layer

Data collection
Wi-Fi
Local webpage
Pump control

Module 3 — Cloud Layer

n8n
ThingSpeak
Google Sheets

Module 4 — Weather Layer

Current weather
Forecast
Rain probability

Module 5 — AI Layer

AI Agent
Reasoning
Recommendations

Module 6 — Decision Layer

Safety
Thresholds
Maximum pump time
Tank protection

Module 7 — Automation Layer

n8n
Triggers
Conditions
Actions

Module 8 — Communication Layer

Telegram
Text
Voice

Module 9 — Visualization Layer

ESP32 Webpage
ThingSpeak
Google Sheets

Module 10 — Feedback Layer

Sensor
→ Decision
→ Action
→ Sensor

63. Final Block Diagram for Your Report

                    ┌───────────────────────────┐
                    │       WEATHER API         │
                    │ Current + Forecast Data   │
                    └────────────┬──────────────┘
                                 │
                                 ▼
┌──────────────┐       ┌────────────────────────┐
│ Soil Sensor  │──────►│                        │
├──────────────┤       │         n8n             │
│ DHT22        │──────►│   Automation Platform  │
├──────────────┤       │                        │
│ Rain Sensor  │──────►│                        │
├──────────────┤       └───────────┬────────────┘
│ Tank Sensor  │──────►            │
└──────────────┘                    │
                                    ▼
                           ┌─────────────────┐
                           │    AI AGENT     │
                           │ Farm Reasoning  │
                           └────────┬────────┘
                                    │
                                    ▼
                           ┌─────────────────┐
                           │ SAFETY ENGINE   │
                           └────────┬────────┘
                                    │
                   ┌────────────────┼────────────────┐
                   │                │                │
                   ▼                ▼                ▼
                ESP32           Telegram        Google Sheets
                   │                │                │
                   ▼                ▼                │
                 Relay          Voice Alert          │
                   │                                 │
                   ▼                                 │
                 Pump                                │
                                                     ▼
                                              Historical Data
                                                     │
                                                     ▼
                                              AI Improvement

64. Recommended Technology Stack

Layer Technology
Microcontroller ESP32
Firmware Arduino/C++
Connectivity Wi-Fi
Sensor protocol Analog/GPIO/1-Wire
Automation n8n
AI LLM/AI Agent
Weather OpenWeather or equivalent
Cloud IoT ThingSpeak
Database/logging Google Sheets
Messaging Telegram Bot
Voice TTS + Telegram
Dashboard ThingSpeak + ESP32 Web UI
Protocol HTTP/HTTPS
Optional MQTT
Optional database PostgreSQL/InfluxDB

65. What Makes This Project Innovative

The basic project:

ESP32 → Sensor → Pump

is a conventional automatic irrigation system.

Your proposed project becomes significantly more sophisticated:

ESP32
+
IoT
+
Weather Forecast
+
Soil Analysis
+
AI Agent
+
n8n
+
Automated Decision Making
+
Cloud Dashboard
+
Google Sheets
+
Telegram
+
Voice Notifications
+
Feedback Loop

The key concept to emphasize in your presentation is:

The system combines real-time physical sensor data with external weather information and AI-assisted reasoning, while a deterministic safety layer controls physical irrigation.


66. Recommended Demonstration

For your final demonstration, prepare four scenarios.

Demo 1 — Dry soil

Physically dry the sensor/put it in dry soil.

Moisture ↓
     ↓
AI detects irrigation requirement
     ↓
Safety approves
     ↓
Pump ON
     ↓
Telegram alert
     ↓
ThingSpeak graph changes

Demo 2 — Rain prediction

Set/test a high rain probability.

Moisture low
+
Rain probability high
        ↓
AI
        ↓
WAIT
        ↓
Pump remains OFF

Demo 3 — Low water tank

Tank = 5%
        ↓
AI may recommend irrigation
        ↓
Safety layer
        ↓
BLOCK
        ↓
Telegram alert

Demo 4 — Telegram

Send:

/status

and show:

soil
temperature
humidity
tank
pump
weather
AI recommendation

Then trigger:

/irrigate

but have the safety layer validate the command before activation.


67. Project Result

The final system should operate like this:

                    🌱 FARM
                      │
                      ▼
                  ESP32 IoT
                      │
              Sensor measurements
                      │
                      ▼
                    n8n
                      │
          ┌───────────┴───────────┐
          │                       │
      Weather                  History
          │                       │
          └───────────┬───────────┘
                      ▼
                  AI AGENT
                      │
                      ▼
             FARM RECOMMENDATION
                      │
                      ▼
              SAFETY VALIDATION
                      │
             ┌────────┴────────┐
             │                 │
             ▼                 ▼
          IRRIGATE             WAIT
             │
             ▼
           ESP32
             │
             ▼
           RELAY
             │
             ▼
          WATER PUMP
             │
             ▼
        NEW SOIL READING
             │
             └──────────────► AI

This is the complete closed-loop Agentic IoT architecture.


68. Important Implementation Note

For the first prototype, I recommend implementing the system in this order:

PHASE 1
ESP32 + Soil Sensor
        ↓
Local Webpage

PHASE 2
ESP32 + DHT22
        ↓
ThingSpeak

PHASE 3
ESP32
        ↓
n8n Webhook
        ↓
Google Sheets

PHASE 4
n8n
        ↓
Weather API

PHASE 5
Weather + Soil
        ↓
AI Agent

PHASE 6
AI
        ↓
Telegram Text

PHASE 7
AI
        ↓
TTS
        ↓
Telegram Voice

PHASE 8
AI
        ↓
Safety Engine
        ↓
Automatic Pump

PHASE 9
Historical Data
        ↓
Predictive ML

PHASE 10
Multi-zone Smart Farm

This staged approach makes troubleshooting much easier than trying to build the entire system simultaneously.

For the weather component, keep the API key inside n8n rather than firmware; OpenWeather requires an API key for API calls. OpenWeather+1 For ThingSpeak, use the channel's Write API Key rather than exposing it in a public webpage. MathWorks+1

Core project URLs/documentation

Espressif Arduino-ESP32 documentation
OpenWeather API documentation
ThingSpeak API documentation
Telegram Bot API
n8n documentation

For an actual college/project submission, this can be expanded into a formal document with: Abstract → Introduction → Existing System → Proposed System → Literature Survey → Requirements → Block Diagram → Circuit Diagram → Flowcharts → Hardware Design → Software Design → n8n workflow → AI Agent prompt → ESP32 source code → API configuration → Database/Google Sheets design → Telegram integration → Testing → Results → Advantages → Limitations → Future Scope → Conclusion → References.

Project Summary

AI Smart Organic Farming using Weather Prediction & Soil Analysis is an intelligent IoT-based agriculture system that combines ESP32, soil/environment sensors, weather forecasting, AI Agent, n8n automation, Telegram alerts, Google Sheets, and ThingSpeak.

System Flow

Soil + Environment Sensors
          ↓
        ESP32
          ↓
       Wi-Fi
          ↓
         n8n
          ↓
   ┌──────┼────────┐
   ↓      ↓        ↓
Weather   AI    Google Sheets
   ↓      ↓        ↓
   └──→ Decision ←─┘
          ↓
    Safety Rules
          ↓
     ┌────┴────┐
     ↓         ↓
   Pump      Wait
     ↓
  Irrigation

Main Functions

  • 🌱 Measures soil moisture

  • 🌡️ Measures temperature and humidity

  • 💧 Monitors water-tank level

  • 🌧️ Retrieves weather/rain forecasts

  • 🤖 AI Agent analyzes soil + weather + crop information

  • ⚙️ n8n automates the complete workflow

  • 🚿 Automatically controls the irrigation pump

  • 📱 Sends Telegram text alerts

  • 🔊 Sends Telegram voice notifications

  • 📊 Stores historical data in Google Sheets

  • 📈 Displays sensor information using ThingSpeak

  • 🌐 Provides an ESP32 local IoT webpage

  • 🛡️ Uses a separate safety/rule layer to prevent unsafe AI-driven pump operation

Key Innovation

Instead of simply:

Sensor → Pump

the project implements a closed-loop Agentic IoT system:

Sense
  ↓
Understand
  ↓
Check Weather
  ↓
AI Reasoning
  ↓
Safety Validation
  ↓
Act
  ↓
Measure Again
  ↓
Repeat

Example

If:

Soil moisture = 25%
Rain probability = 10%
Tank level = 80%

the AI can recommend irrigation. The safety layer validates the recommendation, the ESP32 activates the relay/pump for a limited duration, and Telegram reports the action.

If:

Soil moisture = 28%
Rain probability = 85%
Expected rain = 12 mm

the system can delay irrigation and notify the farmer.

Technology Stack

Component Technology
Controller ESP32
Sensors Soil moisture, DHT22, optional pH/NPK/rain/tank
Automation n8n
AI AI Agent / LLM
Weather Weather API
Cloud dashboard ThingSpeak
Data logging Google Sheets
Notifications Telegram
Voice TTS + Telegram
Irrigation Relay + Water Pump
Local UI ESP32 Web Server

Final Outcome

The project creates a smart, connected farming assistant that helps reduce unnecessary irrigation, continuously monitors field conditions, incorporates weather information into irrigation decisions, records farm data, and keeps the farmer informed through a web dashboard and Telegram text/voice notifications.

 

🌱 AI Smart Organic Farming — Project Mind Map

                         ┌──────────────────────────────┐
                         │  AI SMART ORGANIC FARMING     │
                         │ ESP32 + IoT + AI + n8n        │
                         └──────────────┬───────────────┘
                                        │
          ┌─────────────────────────────┼─────────────────────────────┐
          │                             │                             │
          ▼                             ▼                             ▼
   ┌─────────────┐              ┌──────────────┐              ┌─────────────┐
   │  HARDWARE   │              │   SOFTWARE   │              │    CLOUD    │
   └──────┬──────┘              └──────┬───────┘              └──────┬──────┘
          │                             │                             │
    ┌─────┼──────┐                ┌────┼─────┐                 ┌─────┼─────┐
    │     │      │                │    │     │                 │     │     │
    ▼     ▼      ▼                ▼    ▼     ▼                 ▼     ▼     ▼
  ESP32  Sensors Pump           n8n  AI Agent Web UI       ThingSpeak Sheets Weather
    │     │      │                │    │     │
    │     │      │                │    │     └── Local Dashboard
    │     │      │                │    │
    │     │      │                │    └── Decision Making
    │     │      │                │
    │     │      │                └──── Automation
    │     │      │
    │     │      └── Relay
    │     │
    │     ├── Soil Moisture
    │     ├── DHT22
    │     ├── Soil Temperature
    │     ├── pH Sensor
    │     ├── NPK Sensor
    │     ├── Rain Sensor
    │     └── Water Level
    │
    └── Wi-Fi
          │
          ▼
   ┌──────────────────────┐
   │   DATA PROCESSING    │
   └──────────┬───────────┘
              │
        ┌─────┼──────┐
        │     │      │
        ▼     ▼      ▼
      Soil  Weather  History
       Data   Data    Data
        │     │      │
        └─────┼──────┘
              ▼
      ┌─────────────────┐
      │    AI AGENT     │
      └────────┬────────┘
               │
       ┌───────┼────────┐
       │       │        │
       ▼       ▼        ▼
   Analyze  Predict   Recommend
       │       │        │
       └───────┼────────┘
               ▼
      ┌─────────────────┐
      │  SAFETY ENGINE  │
      └────────┬────────┘
               │
          ┌────┴────┐
          │         │
          ▼         ▼
       IRRIGATE    WAIT
          │
          ▼
       ESP32
          │
          ▼
       RELAY
          │
          ▼
       WATER PUMP
          │
          ▼
      NEW SENSOR DATA
          │
          └──────────────► AI AGENT

📱 Communication & Alerts

                         NOTIFICATION SYSTEM
                                  │
                ┌─────────────────┼─────────────────┐
                │                 │                 │
                ▼                 ▼                 ▼
            Telegram          Voice Alert       Dashboard
                │                 │                 │
                ▼                 ▼                 ▼
              Text              TTS           ThingSpeak
                │                 │
                └────────┬────────┘
                         ▼
                       Farmer

🤖 AI Agent Mind Map

                         AI FARM AGENT
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        ▼                     ▼                     ▼
   Sensor Data           Weather Data          Farm History
        │                     │                     │
        └─────────────────────┼─────────────────────┘
                              │
                              ▼
                         AI Analysis
                              │
              ┌───────────────┼───────────────┐
              │               │               │
              ▼               ▼               ▼
          Soil Status    Rain Prediction   Crop Needs
              │               │               │
              └───────────────┼───────────────┘
                              ▼
                       Irrigation Decision
                              │
                    ┌─────────┴─────────┐
                    │                   │
                    ▼                   ▼
                IRRIGATE               WAIT
                    │
                    ▼
              Safety Validation
                    │
                    ▼
                  Pump

🔄 Complete Project Flow

🌱 FARM
  ↓
📡 Sensors
  ↓
🔵 ESP32
  ↓
📶 Wi-Fi
  ↓
⚙️ n8n Automation
  ↓
🌦️ Weather API
  ↓
🤖 AI Agent
  ↓
🛡️ Safety Rules
  ↓
🚿 Irrigation Decision
  ↓
🔌 Relay
  ↓
💧 Pump
  ↓
🌱 Soil Changes
  ↓
📡 Sensors Again
  ↓
🔄 Continuous Feedback Loop

🎯 Project Goals

                    AI SMART FARM
                         │
       ┌─────────────────┼─────────────────┐
       ▼                 ▼                 ▼
   Save Water        Smart Farming     Reduce Manual Work
       │                 │                 │
       ▼                 ▼                 ▼
 Weather-aware      AI-assisted       Automation
 Irrigation         Decisions         & Alerts
       │                 │                 │
       └─────────────────┼─────────────────┘
                         ▼
                  🌱 Sustainable
                     Farming

Core concept:
Sense → Connect → Analyze → Predict → Decide → Validate → Act → Monitor → Learn.