Friday, 2 October 2026

AI Voice Recognition Home Automation System using Raspberry Pi

AI-Powered Voice-Controlled Home Automation with Raspberry Pi + ESP32 + n8n + Telegram + Google Sheets + ThingSpeak

Below is a complete project architecture that combines:

  • Raspberry Pi — voice-recognition gateway and local web dashboard

  • ESP32 — IoT sensor/actuator controller

  • AI Agent — interprets natural-language commands

  • n8n — automation/orchestration layer

  • Telegram — remote control and voice/text alerts

  • Google Sheets — event/history logging

  • ThingSpeak — IoT cloud monitoring

  • Web dashboard — live home-control interface

  • Voice recognition — speech → command → device action

  • Text-to-speech — system responses

  • Agentic IoT workflow — AI decides which available tool/action should be executed

The design below deliberately separates safety-critical device control from the AI layer: the AI can request an action, but the ESP32 remains responsible for actually driving the hardware.

Raspberry Pi provides a 40-pin GPIO header on current boards, and its official documentation recommends GPIO Zero for Python GPIO work. Raspberry Pi+1 ESP32 supports Wi-Fi station mode for connecting to the home network. Espressif Systems+1


1. Project title

AI Voice Recognition Based Smart Home Automation and Agentic IoT System Using Raspberry Pi, ESP32, n8n and Telegram

Alternative title

AI-Powered Agentic IoT Home Automation Using Raspberry Pi and ESP32 with n8n, Telegram Voice Alerts, Google Sheets and ThingSpeak Cloud Dashboard


2. Abstract

This project develops an intelligent IoT-based home automation system in which household appliances can be monitored and controlled using voice commands, a web interface and Telegram.

A Raspberry Pi acts as the local intelligent gateway. The user can speak commands such as:

"Turn on the living room light."

The Raspberry Pi converts speech into text and sends the command to an AI/n8n automation layer. The AI Agent interprets the user's intention and selects the appropriate IoT operation. n8n communicates with the ESP32, which controls appliances through relay modules and simultaneously collects sensor information.

The ESP32 can monitor parameters such as:

  • Temperature

  • Humidity

  • Light intensity

  • Motion

  • Gas/smoke

  • Door status

  • Appliance status

The collected data can be sent to ThingSpeak for visualization and to Google Sheets for historical logging. ThingSpeak supports both REST and MQTT interfaces for IoT data collection and visualization. MathWorks+1

When an important event occurs, n8n can automatically generate a Telegram notification. n8n's Telegram integration supports sending messages and audio files as well as obtaining Telegram files. n8n Documentation

Thus, the system combines AI + IoT + voice recognition + automation + cloud analytics + messaging into one integrated smart-home platform.


3. Main objectives

The project has the following objectives:

  1. Develop a voice-controlled home automation system.

  2. Use Raspberry Pi as the local voice/AI gateway.

  3. Use ESP32 as the IoT controller.

  4. Control lights/fans/appliances using natural language.

  5. Monitor environmental sensors.

  6. Provide a browser-based IoT dashboard.

  7. Integrate an AI Agent with n8n.

  8. Store device events in Google Sheets.

  9. Display sensor data using ThingSpeak.

  10. Send Telegram alerts automatically.

  11. Support Telegram voice commands.

  12. Provide voice notifications.

  13. Maintain an event history.

  14. Provide local/manual control if AI or Internet connectivity fails.


4. Proposed system

The complete system can be divided into six layers.

┌──────────────────────────────────────────────────────────────┐
│                         USER LAYER                           │
│                                                              │
│   🎤 Voice       🌐 Web Dashboard       📱 Telegram          │
└───────────────┬──────────────┬──────────────┬───────────────┘
                │              │              │
                ▼              ▼              ▼
┌──────────────────────────────────────────────────────────────┐
│                    RASPBERRY PI GATEWAY                      │
│                                                              │
│ Speech Recognition │ Web Server │ Command Parser │ TTS       │
└──────────────────────────────┬───────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────┐
│                         n8n AUTOMATION                       │
│                                                              │
│ Webhook → AI Agent → Decision → IoT API → Logging → Alert   │
└───────────────┬──────────────────┬───────────────────────────┘
                │                  │
                ▼                  ▼
       ┌────────────────┐   ┌─────────────────┐
       │     ESP32      │   │ Cloud Services  │
       │ IoT Controller │   │ Sheets/Telegram │
       └───────┬────────┘   │ /ThingSpeak     │
               │            └─────────────────┘
       ┌───────┴─────────┐
       │                 │
       ▼                 ▼
   Sensors           Relays
       │                 │
       ▼                 ▼
 Temperature         Light
 Humidity            Fan
 Motion              Appliance
 Gas                 Motor

5. Why use both Raspberry Pi and ESP32?

This is an important part of the project design.

Raspberry Pi

The Raspberry Pi is suitable for:

  • Linux

  • Python

  • Speech recognition

  • AI APIs/models

  • Web server

  • Database

  • Local dashboard

  • Audio input/output

  • Higher-level decision making

ESP32

ESP32 is suitable for:

  • GPIO

  • Sensors

  • Relays

  • Wi-Fi

  • Low-power operation

  • Real-time device control

ESP32's Arduino environment provides Wi-Fi station functionality, allowing the controller to join the home's Wi-Fi network. Espressif Systems

n8n

n8n becomes the automation brain/orchestration layer.

It can connect applications and APIs and also provides AI functionality and AI-agent/tool capabilities. n8n Documentation+1

Therefore:

Raspberry Pi = Voice + Local Gateway
ESP32        = Hardware/IoT Controller
n8n          = Automation + AI orchestration
ThingSpeak   = IoT Analytics
Google Sheet = Event Database
Telegram     = Remote Notification/Control

6. Hardware required

Main components

Component Quantity Purpose
Raspberry Pi 4/5 1 Voice gateway
ESP32 DevKit 1 IoT controller
USB microphone 1 Voice input
Speaker 1 Voice response
4-channel relay module 1 Appliance control
DHT22/DHT11 1 Temperature/humidity
PIR sensor 1 Motion detection
LDR module 1 Light measurement
MQ-2/MQ-135 1 Gas/air-quality experiment
LEDs 2–4 Demonstration loads
Push buttons 2 Manual override
Breadboard 1 Prototype
Jumper wires Several Connections
5-V supply 1 Raspberry Pi
USB power supply 1 ESP32
Wi-Fi router 1 Network

For a university demonstration, use LEDs or low-voltage DC loads first. Do not connect mains AC appliances directly to a breadboard.


7. Recommended GPIO assignment

ESP32

Device ESP32 GPIO
DHT22 DATA GPIO 4
PIR GPIO 27
LDR GPIO 34
Gas sensor GPIO 35
Relay 1 GPIO 16
Relay 2 GPIO 17
Relay 3 GPIO 18
Relay 4 GPIO 19
Status LED GPIO 2

GPIO assignments can be changed according to the actual ESP32 board and modules.


8. Schematic diagram

                         HOME Wi-Fi
                             │
             ┌───────────────┴────────────────┐
             │                                │
             ▼                                ▼
     ┌───────────────┐                ┌───────────────┐
     │ Raspberry Pi  │                │     ESP32     │
     │               │                │               │
     │ USB MIC       │                │ GPIO4 ── DHT22│
     │ USB Speaker   │                │ GPIO27 ─ PIR  │
     │ Web Server    │                │ GPIO34 ─ LDR  │
     │ Python        │                │ GPIO35 ─ GAS  │
     └───────┬───────┘                │               │
             │                        │ GPIO16 ─ Relay1
             │                        │ GPIO17 ─ Relay2
             │                        │ GPIO18 ─ Relay3
             │                        │ GPIO19 ─ Relay4
             │                        └───────┬───────┘
             │                                │
             │                                ▼
             │                       ┌─────────────────┐
             │                       │ Relay Module   │
             │                       ├─────────────────┤
             │                       │ CH1 → Light     │
             │                       │ CH2 → Fan       │
             │                       │ CH3 → Appliance │
             │                       │ CH4 → Spare     │
             │                       └─────────────────┘
             │
             ▼
       ┌─────────────┐
       │     n8n     │
       │ Automation  │
       └───┬─────┬───┘
           │     │
     ┌─────┘     └──────────────┐
     ▼                          ▼
┌───────────┐              ┌────────────┐
│ Telegram  │              │ AI Agent   │
└───────────┘              └────────────┘
     │                          │
     ▼                          ▼
┌───────────┐              ┌────────────┐
│ User      │              │ Commands   │
└───────────┘              └────────────┘

                  n8n
                   │
           ┌───────┴────────┐
           ▼                ▼
   Google Sheets        ThingSpeak
      History          IoT Dashboard

9. ESP32 electrical schematic

                     ESP32
              ┌─────────────────┐
              │                 │
 DHT22 DATA ──┤ GPIO 4          │
 PIR OUT ─────┤ GPIO 27         │
 LDR AO ──────┤ GPIO 34         │
 GAS AO ──────┤ GPIO 35         │
              │                 │
 Relay IN1 ───┤ GPIO 16         │
 Relay IN2 ───┤ GPIO 17         │
 Relay IN3 ───┤ GPIO 18         │
 Relay IN4 ───┤ GPIO 19         │
              │                 │
              │ 3V3 ────────────┼── DHT22 VCC
              │ GND ────────────┼── Sensor GND
              └─────────────────┘

Important: Raspberry Pi GPIO and ESP32 GPIO are 3.3-V logic. Raspberry Pi documentation specifically warns not to put 5 V onto 3.3-V components. Raspberry Pi

For relay modules, verify the relay board's input requirements. If necessary, use a transistor/driver or an appropriately rated relay module rather than powering a relay coil directly from an MCU GPIO.


10. Software architecture

                    ┌─────────────┐
                    │ Voice Input │
                    └──────┬──────┘
                           │
                           ▼
                  ┌─────────────────┐
                  │ Speech-to-Text  │
                  │ Vosk / Cloud STT│
                  └───────┬─────────┘
                          │
                          ▼
                ┌────────────────────┐
                │ Command Processing │
                └─────────┬──────────┘
                          │
                          ▼
                  ┌──────────────┐
                  │     n8n      │
                  │ AI Agent     │
                  └──────┬───────┘
                         │
             ┌───────────┼───────────┐
             ▼           ▼           ▼
          ESP32       Telegram    Google Sheets
             │
             ▼
          Sensors
             │
             ▼
        ThingSpeak

11. Voice-control sequence

Suppose the user says:

"Turn on the bedroom light."

The sequence is:

USER SPEAKS
    │
    ▼
Microphone
    │
    ▼
Raspberry Pi
    │
    ▼
Speech-to-Text
    │
    ▼
"turn on bedroom light"
    │
    ▼
n8n Webhook
    │
    ▼
AI Agent
    │
    ├── intent = device_control
    ├── device = bedroom_light
    └── action = ON
    │
    ▼
HTTP Request
    │
    ▼
ESP32
    │
    ▼
GPIO
    │
    ▼
Relay
    │
    ▼
Bedroom Light ON
    │
    ├──────────────► Google Sheets
    │
    ├──────────────► ThingSpeak
    │
    └──────────────► Telegram

12. AI Agent concept

The AI Agent should not directly receive unrestricted GPIO access.

Instead, define a limited tool set:

AVAILABLE TOOLS

turn_light_on(room)
turn_light_off(room)

turn_fan_on(room)
turn_fan_off(room)

get_temperature()
get_humidity()

get_device_status()
get_sensor_status()

send_notification(message)

The AI converts natural language into one of these controlled operations.

For example:

User:
"Can you switch the hall fan on?"

AI:
{
  "intent": "device_control",
  "device": "fan",
  "room": "hall",
  "action": "ON"
}

n8n then validates this command before sending it to ESP32.

This is much safer than allowing an LLM to generate arbitrary HTTP URLs or GPIO instructions.


13. AI Agent system prompt

Use a prompt along these lines in the n8n AI Agent:

You are the AI controller for a smart home IoT system.

Your job is to interpret natural-language user commands and select
one of the available smart-home tools.

Available devices:

- living_room_light
- bedroom_light
- hall_light
- living_room_fan
- bedroom_fan

Available actions:

- ON
- OFF
- STATUS

Rules:

1. Never invent a device.
2. Never invent a room.
3. Never execute an unsupported action.
4. If the user's command is ambiguous, ask for clarification.
5. For status requests, use the sensor/status tool.
6. For appliance control, return the device and action.
7. Do not expose API keys or credentials.
8. Do not directly generate arbitrary URLs.
9. Use only the provided IoT tools.

Return structured JSON whenever a device-control action is requested.

14. Raspberry Pi setup

Install Raspberry Pi OS and update the system.

Raspberry Pi provides official documentation for Raspberry Pi OS, hardware and software configuration. Raspberry Pi

sudo apt update
sudo apt upgrade -y

Install Python tools:

sudo apt install -y python3-pip python3-venv

Create project directory:

mkdir ~/smart-home
cd ~/smart-home

Create virtual environment:

python3 -m venv venv
source venv/bin/activate

Install packages:

pip install flask requests sounddevice vosk pyttsx3

Depending on your Raspberry Pi OS/audio configuration, additional system packages may be required for audio.


15. Voice recognition

For an offline prototype, Vosk is a suitable architecture because speech recognition can be performed locally rather than sending every microphone recording to a cloud service.

Project structure:

smart-home/
│
├── app.py
├── voice.py
├── esp32.py
├── config.py
├── requirements.txt
├── templates/
│   └── index.html
├── static/
│   └── style.css
└── models/
    └── vosk-model/

16. Configuration file

Create:

config.py

WIFI_NAME = "YOUR_WIFI"

N8N_WEBHOOK = "https://YOUR-N8N-DOMAIN/webhook/home-command"

ESP32_URL = "http://ESP32_IP"

VOICE_LANGUAGE = "en"

DEVICE_NAME = "SmartHome"

Do not commit credentials, Telegram bot tokens or API keys into GitHub.


17. Raspberry Pi voice program

voice.py

import json
import queue
import sounddevice as sd
from vosk import Model, KaldiRecognizer

MODEL_PATH = "models/vosk-model"

model = Model(MODEL_PATH)

audio_queue = queue.Queue()


def audio_callback(indata, frames, time, status):
    if status:
        print(status)

    audio_queue.put(bytes(indata))


def listen():

    recognizer = KaldiRecognizer(model, 16000)

    with sd.RawInputStream(
        samplerate=16000,
        blocksize=8000,
        dtype="int16",
        channels=1,
        callback=audio_callback
    ):

        print("Listening...")

        while True:

            data = audio_queue.get()

            if recognizer.AcceptWaveform(data):

                result = json.loads(
                    recognizer.Result()
                )

                text = result.get("text", "").strip()

                if text:
                    print("Recognized:", text)
                    return text

18. Send command from Raspberry Pi to n8n

app.py

from flask import Flask, render_template, request, jsonify
import requests
from datetime import datetime

N8N_WEBHOOK = "https://YOUR-N8N-DOMAIN/webhook/home-command"

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/command", methods=["POST"])
def command():

    data = request.get_json()

    command = data.get("command", "")

    payload = {
        "source": "web",
        "command": command,
        "timestamp": datetime.now().isoformat()
    }

    try:

        response = requests.post(
            N8N_WEBHOOK,
            json=payload,
            timeout=15
        )

        return jsonify({
            "success": True,
            "response": response.text
        })

    except Exception as e:

        return jsonify({
            "success": False,
            "error": str(e)
        }), 500


if __name__ == "__main__":

    app.run(
        host="0.0.0.0",
        port=5000,
        debug=False
    )

19. ESP32 firmware

The following firmware uses HTTP rather than MQTT for the basic version because it makes the demonstration architecture easier to understand.

Install these Arduino libraries:

WiFi
WebServer
ArduinoJson
DHT sensor library

ESP32 code

#include <WiFi.h>
#include <WebServer.h>
#include <ArduinoJson.h>
#include "DHT.h"

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

#define DHT_PIN 4
#define DHT_TYPE DHT22

#define PIR_PIN 27
#define LDR_PIN 34
#define GAS_PIN 35

#define RELAY_LIGHT 16
#define RELAY_FAN 17
#define RELAY_APPLIANCE 18
#define RELAY_SPARE 19

DHT dht(DHT_PIN, DHT_TYPE);

WebServer server(80);

bool lightState = false;
bool fanState = false;
bool applianceState = false;
bool spareState = false;


void setRelay(int pin, bool state)
{
    // Change HIGH/LOW if your relay is active HIGH.
    digitalWrite(pin, state ? LOW : HIGH);
}


void handleStatus()
{
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();

    int motion = digitalRead(PIR_PIN);
    int light = analogRead(LDR_PIN);
    int gas = analogRead(GAS_PIN);

    StaticJsonDocument<512> doc;

    doc["temperature"] = temperature;
    doc["humidity"] = humidity;
    doc["motion"] = motion;
    doc["light"] = light;
    doc["gas"] = gas;

    doc["lightState"] = lightState;
    doc["fanState"] = fanState;
    doc["applianceState"] = applianceState;
    doc["spareState"] = spareState;

    String output;

    serializeJson(doc, output);

    server.send(
        200,
        "application/json",
        output
    );
}


void handleControl()
{
    if (!server.hasArg("plain"))
    {
        server.send(
            400,
            "application/json",
            "{\"error\":\"Missing JSON\"}"
        );

        return;
    }

    StaticJsonDocument<256> doc;

    DeserializationError error =
        deserializeJson(
            doc,
            server.arg("plain")
        );

    if (error)
    {
        server.send(
            400,
            "application/json",
            "{\"error\":\"Invalid JSON\"}"
        );

        return;
    }

    String device = doc["device"];
    String action = doc["action"];

    bool state = action == "ON";

    if (device == "light")
    {
        lightState = state;
        setRelay(RELAY_LIGHT, state);
    }

    else if (device == "fan")
    {
        fanState = state;
        setRelay(RELAY_FAN, state);
    }

    else if (device == "appliance")
    {
        applianceState = state;
        setRelay(RELAY_APPLIANCE, state);
    }

    else if (device == "spare")
    {
        spareState = state;
        setRelay(RELAY_SPARE, state);
    }

    else
    {
        server.send(
            400,
            "application/json",
            "{\"error\":\"Unknown device\"}"
        );

        return;
    }

    StaticJsonDocument<256> response;

    response["success"] = true;
    response["device"] = device;
    response["action"] = action;

    String output;

    serializeJson(response, output);

    server.send(
        200,
        "application/json",
        output
    );
}


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

    pinMode(PIR_PIN, INPUT);

    pinMode(RELAY_LIGHT, OUTPUT);
    pinMode(RELAY_FAN, OUTPUT);
    pinMode(RELAY_APPLIANCE, OUTPUT);
    pinMode(RELAY_SPARE, OUTPUT);

    setRelay(RELAY_LIGHT, false);
    setRelay(RELAY_FAN, false);
    setRelay(RELAY_APPLIANCE, false);
    setRelay(RELAY_SPARE, false);

    dht.begin();

    WiFi.begin(
        WIFI_SSID,
        WIFI_PASSWORD
    );

    Serial.print("Connecting");

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

    Serial.println();

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

    server.on(
        "/status",
        HTTP_GET,
        handleStatus
    );

    server.on(
        "/control",
        HTTP_POST,
        handleControl
    );

    server.begin();

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


void loop()
{
    server.handleClient();
}

20. Testing the ESP32 manually

After uploading the program, open Serial Monitor.

You should see something similar to:

Connecting....
ESP32 IP: 192.168.1.50
HTTP server started

From a computer on the same network:

curl http://192.168.1.50/status

Example:

{
  "temperature": 27.4,
  "humidity": 62.1,
  "motion": 1,
  "light": 1832,
  "gas": 412,
  "lightState": false,
  "fanState": false,
  "applianceState": false,
  "spareState": false
}

Control a light:

curl -X POST http://192.168.1.50/control \
-H "Content-Type: application/json" \
-d '{"device":"light","action":"ON"}'

Turn it off:

curl -X POST http://192.168.1.50/control \
-H "Content-Type: application/json" \
-d '{"device":"light","action":"OFF"}'

21. n8n architecture

Create the following workflows.

Workflow 1 — Voice/Web command

Webhook
   ↓
Validate Input
   ↓
AI Agent
   ↓
Parse Structured Command
   ↓
Validate Device
   ↓
HTTP Request → ESP32
   ↓
Google Sheets
   ↓
Telegram Confirmation
   ↓
Webhook Response

n8n is designed specifically to connect applications and APIs and provides both normal workflow automation and AI capabilities. n8n Documentation


22. n8n Webhook

Create:

Webhook

Method:

POST

Path:

home-command

Example input:

{
  "source": "voice",
  "command": "turn on the bedroom light",
  "timestamp": "2026-10-02T22:00:00"
}

Your production webhook should be protected with authentication or another access-control mechanism rather than exposing an unrestricted control endpoint. n8n also provides security-audit functionality that can identify issues such as unprotected webhooks and outdated instances. n8n Documentation


23. AI Agent node

Input:

{{$json.command}}

Example:

turn on the bedroom light

Expected structured result:

{
  "intent": "control",
  "device": "light",
  "room": "bedroom",
  "action": "ON"
}

For:

What is the temperature?

the agent might return:

{
  "intent": "sensor",
  "sensor": "temperature",
  "action": "READ"
}

24. Validation node

Before allowing the command to reach the ESP32, use an n8n Code node.

Example:

const allowedDevices = [
  "light",
  "fan",
  "appliance"
];

const allowedActions = [
  "ON",
  "OFF"
];

const data = $json;

if (!allowedDevices.includes(data.device)) {
  throw new Error("Invalid device");
}

if (!allowedActions.includes(data.action)) {
  throw new Error("Invalid action");
}

return [
  {
    json: {
      device: data.device,
      action: data.action,
      room: data.room || "unknown"
    }
  }
];

This gives you a critical safety boundary:

AI
 │
 ▼
VALIDATION
 │
 ├── Invalid → STOP
 │
 └── Valid
       │
       ▼
     ESP32

25. n8n HTTP Request to ESP32

Configure:

Method:
POST

URL:
http://192.168.1.50/control

Headers:

Content-Type: application/json

Body:

{
  "device": "{{$json.device}}",
  "action": "{{$json.action}}"
}

The ESP32 returns:

{
  "success": true,
  "device": "light",
  "action": "ON"
}

26. Google Sheets logging

Create a Google Sheet called:

Smart Home IoT Logs

Columns:

Timestamp
Source
Command
Intent
Device
Room
Action
Temperature
Humidity
Motion
Result

Example:

Timestamp Source Command Device Action Result
22:10 Voice Turn on hall light light ON Success
22:12 Web Turn off fan fan OFF Success
22:15 Telegram Turn on bedroom light light ON Success

Use n8n's Google Sheets integration to append the execution information.

This gives the project an excellent data-logging component for demonstration and analysis.


27. ThingSpeak integration

ThingSpeak is useful for long-term sensor visualization. It is designed for collecting, visualizing and analyzing IoT data, and supports REST and MQTT interfaces. MathWorks+1

Create a ThingSpeak channel with fields such as:

Field 1 = Temperature
Field 2 = Humidity
Field 3 = Light
Field 4 = Gas
Field 5 = Motion
Field 6 = Light State
Field 7 = Fan State

Example:

Temperature = 28.2
Humidity    = 61
Light       = 1540
Gas         = 390
Motion      = 1
LightState  = 1
FanState    = 0

28. Sending data to ThingSpeak

One simple architecture is:

ESP32
  │
  ▼
n8n
  │
  ▼
HTTP Request
  │
  ▼
ThingSpeak

The request can contain:

field1 = temperature
field2 = humidity
field3 = light
field4 = gas
field5 = motion
field6 = lightState
field7 = fanState

For a more IoT-native implementation, the ESP32 can publish through ThingSpeak's MQTT interface. ThingSpeak documents MQTT publish/subscribe operation for channel feeds. MathWorks


29. ThingSpeak architecture

              ESP32
                │
        Sensor Measurements
                │
                ▼
           ┌─────────┐
           │ ThingSpeak│
           └────┬────┘
                │
       ┌────────┼─────────┐
       ▼        ▼         ▼
 Temperature Humidity   Light
   Chart       Chart     Chart

This gives you a cloud dashboard without needing to develop your own time-series database.


30. Telegram integration

Create a Telegram bot using BotFather.

Store:

TELEGRAM_BOT_TOKEN
TELEGRAM_CHAT_ID

in n8n credentials rather than hard-coding them.

n8n's Telegram node supports sending messages and audio files and retrieving Telegram files. n8n Documentation


31. Telegram text alert

Example:

🏠 SMART HOME ALERT

Device: Bedroom Light
Action: ON

Temperature: 27.6 °C
Humidity: 61 %

Time: 22:15
Status: Successful

32. Telegram voice alert

For a voice notification:

ESP32 event
     │
     ▼
n8n
     │
     ▼
Generate text
     │
     ▼
Text-to-Speech
     │
     ▼
MP3/OGG
     │
     ▼
Telegram
     │
     ▼
Voice message

Example generated sentence:

"Attention. Motion was detected in the living room."

n8n's Telegram node supports sending audio files, so the TTS output can be delivered through Telegram. n8n Documentation


33. Telegram voice-command workflow

This is an especially good feature for your project.

User
 │
 │ 🎤 Voice message
 ▼
Telegram Bot
 │
 ▼
n8n Telegram Trigger
 │
 ▼
Get File
 │
 ▼
Speech-to-Text
 │
 ▼
AI Agent
 │
 ▼
Validate Command
 │
 ▼
ESP32
 │
 ▼
Telegram Confirmation

Example:

USER:
🎤 "Turn off the living room fan."

        ↓

AI:

device = fan
room = living_room
action = OFF

        ↓

ESP32:

Fan OFF

        ↓

TELEGRAM:

"Living room fan has been turned off."

34. Telegram emergency alert

Suppose the gas sensor exceeds a configured threshold.

Gas sensor
    │
    ▼
ESP32
    │
    ▼
n8n
    │
    ├──────────────► Google Sheets
    │
    ├──────────────► ThingSpeak
    │
    ▼
Telegram
    │
    ▼
🚨 ALERT

Example:

🚨 SMART HOME ALERT

Possible gas/air-quality event detected.

Gas sensor value: 780
Location: Kitchen
Time: 22:31

Please inspect the area.

For a real safety system, treat inexpensive hobby gas sensors as project/demo sensors, not certified life-safety equipment.


35. Complete n8n workflow 1

Voice command

┌─────────────┐
│   Webhook   │
└──────┬──────┘
       │
       ▼
┌───────────────┐
│ Normalize Data│
└──────┬────────┘
       │
       ▼
┌─────────────┐
│  AI Agent   │
└──────┬──────┘
       │
       ▼
┌───────────────┐
│ JSON Parser   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Validate Cmd  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ HTTP → ESP32  │
└──────┬────────┘
       │
       ├───────────────┐
       ▼               ▼
┌────────────┐   ┌─────────────┐
│Google Sheet│   │  Telegram   │
└────────────┘   └─────────────┘

36. Complete n8n workflow 2 — Sensor monitoring

┌───────────────┐
│ Schedule      │
│ Every 1 min   │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ HTTP ESP32    │
│ /status       │
└───────┬───────┘
        │
        ▼
┌─────────────────┐
│ Parse Sensor    │
└───────┬─────────┘
        │
        ├─────────────────┐
        ▼                 ▼
┌─────────────┐     ┌──────────────┐
│ ThingSpeak  │     │ Google Sheet │
└─────────────┘     └──────────────┘
        │
        ▼
┌──────────────────┐
│ Threshold Check  │
└────────┬─────────┘
         │
       ALERT?
       /    \
     YES     NO
      │       │
      ▼       ▼
 Telegram    End
 Alert

37. Complete n8n workflow 3 — Telegram voice command

┌────────────────────┐
│ Telegram Trigger   │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ Is Voice Message?  │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ Telegram Get File  │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ Speech-to-Text      │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ AI Agent            │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ Command Validation │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ ESP32 HTTP Request │
└─────────┬──────────┘
          │
          ▼
┌────────────────────┐
│ Telegram Response  │
└────────────────────┘

38. Web dashboard

The dashboard can contain:

╔══════════════════════════════════════════════╗
║             🏠 SMART HOME AI                ║
╠══════════════════════════════════════════════╣
║                                              ║
║ Temperature       27.4 °C       🌡️           ║
║ Humidity          61 %          💧           ║
║ Motion            DETECTED      👤           ║
║ Gas               NORMAL        🟢           ║
║                                              ║
╠══════════════════════════════════════════════╣
║ DEVICE CONTROL                               ║
║                                              ║
║ Living Light       [ ON ] [ OFF ]            ║
║ Bedroom Light     [ ON ] [ OFF ]             ║
║ Hall Light        [ ON ] [ OFF ]             ║
║ Fan               [ ON ] [ OFF ]             ║
║                                              ║
╠══════════════════════════════════════════════╣
║ 🎤 Ask your smart home:                     ║
║                                              ║
║ [ Turn on the bedroom light            ]     ║
║                     [ SEND ]                 ║
╚══════════════════════════════════════════════╝

39. HTML dashboard

templates/index.html

<!DOCTYPE html>
<html>

<head>

    <title>AI Smart Home</title>

    <style>

        body {
            font-family: Arial;
            background: #101827;
            color: white;
            margin: 0;
            padding: 30px;
        }

        .container {
            max-width: 1000px;
            margin: auto;
        }

        .card {
            background: #1c2738;
            padding: 20px;
            margin: 10px;
            border-radius: 15px;
            display: inline-block;
            min-width: 200px;
        }

        button {
            padding: 12px 20px;
            margin: 5px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
        }

        .on {
            background: #22c55e;
        }

        .off {
            background: #ef4444;
            color: white;
        }

        input {
            width: 70%;
            padding: 14px;
            border-radius: 8px;
            border: none;
        }

    </style>

</head>

<body>

<div class="container">

<h1>🏠 AI Smart Home</h1>

<div class="card">
<h2>Temperature</h2>
<p id="temperature">-- °C</p>
</div>

<div class="card">
<h2>Humidity</h2>
<p id="humidity">-- %</p>
</div>

<div class="card">
<h2>Motion</h2>
<p id="motion">--</p>
</div>

<h2>Device Control</h2>

<button class="on"
onclick="sendCommand('turn on the light')">
Light ON
</button>

<button class="off"
onclick="sendCommand('turn off the light')">
Light OFF
</button>

<button class="on"
onclick="sendCommand('turn on the fan')">
Fan ON
</button>

<button class="off"
onclick="sendCommand('turn off the fan')">
Fan OFF
</button>

<h2>AI Command</h2>

<input id="command"
placeholder="Example: Turn on the bedroom light">

<button onclick="submitCommand()">
SEND
</button>

<p id="response"></p>

</div>


<script>

function sendCommand(command)
{
    fetch("/command", {

        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify({
            command: command
        })

    })

    .then(response => response.json())

    .then(data => {

        document.getElementById(
            "response"
        ).innerText =
            JSON.stringify(data);

    });
}


function submitCommand()
{
    const command =
        document.getElementById(
            "command"
        ).value;

    sendCommand(command);
}

</script>

</body>

</html>

40. Improved dashboard architecture

For a more advanced final-year project, use:

Frontend
   │
   ├── HTML/CSS
   ├── JavaScript
   ├── Chart.js
   └── WebSocket/AJAX
           │
           ▼
       Flask/FastAPI
           │
      ┌────┴────┐
      ▼         ▼
   ESP32       n8n
      │         │
      ▼         ▼
 Sensors      AI Agent

You can display real-time charts for:

  • Temperature

  • Humidity

  • Light

  • Gas

  • Motion

  • Appliance state


41. Natural-language commands

Your system should support commands such as:

Lighting

Turn on the living room light.
Switch off the bedroom light.
Turn all lights off.

Fan

Turn on the fan.
Switch off the bedroom fan.

Sensors

What is the temperature?
What's the humidity?
Is there motion in the house?

Combined command

Turn on the hall light and tell me the temperature.

The AI Agent can break this into two tool calls:

Tool 1:
get_sensor_status()

Tool 2:
turn_light_on("hall")

42. Agentic IoT concept

This is where your project becomes more than conventional IoT.

Traditional IoT:

Button
  ↓
Fixed program
  ↓
Relay

Your system:

Natural language
       ↓
     AI Agent
       ↓
   Understand intent
       ↓
 Select appropriate tool
       ↓
Validate operation
       ↓
    IoT device
       ↓
 Observe result
       ↓
 Log + notify user

The AI is therefore operating as an orchestrator, while deterministic code remains responsible for device execution.


43. Example agent conversation

User

Turn on the living room light.

AI Agent

Intent detected:
device control

Device:
light

Room:
living room

Action:
ON

n8n

Validation successful.
Sending command to ESP32.

ESP32

{
  "success": true,
  "device": "light",
  "action": "ON"
}

AI response

The living room light is now on.

Google Sheets

22:31 | Voice | living room light | ON | Success

Telegram

🏠 Living room light turned ON.

44. Example sensor conversation

User

What's the temperature?

AI

I will check the temperature sensor.

n8n:

GET http://ESP32/status

ESP32:

{
  "temperature": 28.1,
  "humidity": 58.2
}

AI:

The current temperature is 28.1 °C and
the humidity is 58.2%.

45. Automated temperature workflow

You can add intelligent automation:

Temperature
    │
    ▼
ESP32
    │
    ▼
n8n
    │
    ▼
IF temperature > 30°C
    │
   YES
    │
    ▼
AI / Automation Rule
    │
    ▼
Turn ON Fan
    │
    ├── Google Sheets
    │
    └── Telegram

Telegram:

🌡️ Temperature automation

Temperature reached 30.4 °C.

Fan automatically turned ON.

46. Motion detection workflow

PIR
 │
 ▼
ESP32
 │
 ▼
n8n
 │
 ▼
Motion detected?
 │
 YES
 │
 ├────► Google Sheets
 │
 ├────► ThingSpeak
 │
 └────► Telegram

Telegram:

👤 Motion detected.

Location: Living Room
Time: 23:04

47. Voice notification architecture

EVENT
 │
 ▼
n8n
 │
 ▼
Generate message
 │
 ▼
Text-to-Speech
 │
 ▼
Audio file
 │
 ▼
Telegram Send Audio
 │
 ▼
📱 User receives voice alert

Example:

"Attention. Motion has been detected
in the living room."

48. Data flow diagram

                 ┌───────────────┐
                 │     USER      │
                 └───────┬───────┘
                         │
              ┌──────────┼──────────┐
              │          │          │
              ▼          ▼          ▼
           Voice       Web       Telegram
              │          │          │
              └──────────┼──────────┘
                         ▼
                ┌────────────────┐
                │ Raspberry Pi   │
                │ Gateway        │
                └───────┬────────┘
                        │
                        ▼
                  ┌───────────┐
                  │    n8n    │
                  └─────┬─────┘
                        │
                ┌───────┼────────┐
                │       │        │
                ▼       ▼        ▼
              AI     Logging   Alerts
             Agent      │        │
                │       ▼        ▼
                │   Sheets    Telegram
                │
                ▼
             ESP32
                │
        ┌───────┼────────┐
        ▼       ▼        ▼
     Sensors  Relays   Status
        │       │
        ▼       ▼
    ThingSpeak Appliances

49. Sequence diagram

User       Raspberry Pi      n8n       AI Agent       ESP32       Telegram
 │              │             │           │             │            │
 │ "Light ON"   │             │           │             │            │
 ├─────────────►│             │           │             │            │
 │              │ POST        │           │             │            │
 │              ├────────────►│           │             │            │
 │              │             │ command   │             │            │
 │              │             ├──────────►│             │            │
 │              │             │           │             │            │
 │              │             │           │ decision    │            │
 │              │             │◄──────────┤             │            │
 │              │             │           │             │            │
 │              │             ├────────────────────────►│            │
 │              │             │           │             │ relay ON   │
 │              │             │◄────────────────────────┤            │
 │              │             │           │             │            │
 │              │             ├─────────────────────────────────────►│
 │              │             │           │             │            │
 │              │◄────────────┤           │             │            │
 │◄─────────────┤             │           │             │            │
 │              │             │           │             │            │

50. Project directory

A good final implementation can use:

AI-Smart-Home/
│
├── raspberry_pi/
│   │
│   ├── app.py
│   ├── voice.py
│   ├── esp32.py
│   ├── config.py
│   ├── requirements.txt
│   │
│   ├── templates/
│   │   └── index.html
│   │
│   ├── static/
│   │   ├── style.css
│   │   └── app.js
│   │
│   └── models/
│       └── vosk-model/
│
├── esp32/
│   └── smart_home.ino
│
├── n8n/
│   ├── voice-control.json
│   ├── sensor-monitor.json
│   └── telegram-control.json
│
├── documentation/
│   ├── architecture.md
│   ├── wiring.md
│   ├── api.md
│   └── testing.md
│
└── README.md

51. API design

Define a simple API between n8n and ESP32.

Get status

GET /status

Response:

{
  "temperature": 27.8,
  "humidity": 60.5,
  "motion": 0,
  "light": 1700,
  "gas": 390,
  "lightState": true,
  "fanState": false
}

Control

POST /control

Request:

{
  "device": "fan",
  "action": "ON"
}

Response:

{
  "success": true,
  "device": "fan",
  "action": "ON"
}

52. Security design

Security should be explicitly discussed in your project report.

Do not expose the ESP32 directly to the Internet.

Instead:

Internet
   │
   ▼
n8n
   │
   ▼
Local network
   │
   ▼
ESP32

Better:

Internet
   │
   ▼
Authenticated n8n
   │
   ▼
VPN / secure network
   │
   ▼
ESP32

Use:

  • Authentication

  • HTTPS for Internet-facing services

  • Strong Wi-Fi password

  • n8n credential store

  • No API keys inside source code

  • Command validation

  • Device allow-list

  • Rate limiting where appropriate

  • Local fallback

  • Network isolation

n8n includes a security-audit capability that checks areas including credentials, risky nodes, webhooks and instance configuration. n8n Documentation


53. Fail-safe architecture

A good project should continue functioning if one component fails.

Internet failure

Internet OFF
     │
     ▼
Raspberry Pi
     │
     ▼
Local voice
     │
     ▼
ESP32
     │
     ▼
Local appliance

n8n failure

n8n unavailable
      │
      ▼
Local Raspberry Pi
      │
      ▼
Direct ESP32 API

ESP32 failure

ESP32 unavailable
      │
      ▼
Dashboard reports:
"Device offline"

AI failure

AI unavailable
     │
     ▼
Use deterministic commands:
"light on"
"light off"
"fan on"
"fan off"

This hybrid approach makes the system much more robust than putting every operation behind an AI model.


54. Testing plan

Test 1 — ESP32 Wi-Fi

Expected:

ESP32 connected
IP address obtained

Test 2 — Temperature

Expected:

Temperature displayed correctly.

Test 3 — Relay

Command:

light ON

Expected:

Relay activates.

Test 4 — Web control

Click:

Light ON

Expected:

Light turns on.

Test 5 — Voice

Say:

Turn on the light.

Expected:

Speech → text → n8n → AI → ESP32 → relay

Test 6 — Telegram

Send:

Turn on the fan.

Expected:

Fan ON

Test 7 — Sensor logging

Expected:

ESP32 → n8n → Google Sheets

Test 8 — ThingSpeak

Expected:

Charts update with sensor measurements.

Test 9 — Alert

Trigger motion.

Expected:

ESP32 → n8n → Telegram alert

Test 10 — Voice alert

Expected:

Telegram receives audio notification.

55. Testing table for your report

Test Input Expected result Status
Wi-Fi ESP32 startup Network connected PASS
Temperature DHT22 Temperature displayed PASS
Humidity DHT22 Humidity displayed PASS
Light ON Voice Relay ON PASS
Light OFF Web Relay OFF PASS
Fan ON Telegram Fan ON PASS
Motion PIR Alert generated PASS
Gas threshold Sensor Alert generated PASS
Logging Sensor data Google Sheets row PASS
Cloud Sensor data ThingSpeak update PASS
Voice alert Event Telegram audio PASS

56. Advantages

The system provides:

  • Hands-free control

  • Natural-language interaction

  • Local IoT processing

  • Cloud monitoring

  • Historical logging

  • Remote Telegram control

  • Automated alerts

  • Voice notifications

  • Web-based control

  • AI-based command interpretation

  • Expandability

  • Multiple communication methods


57. Limitations

For your academic report, also mention:

  1. Speech recognition accuracy depends on microphone quality and background noise.

  2. Internet-dependent AI/cloud functions may fail when the Internet is unavailable.

  3. ESP32 has limited processing resources compared with Raspberry Pi.

  4. Hobby sensors are not laboratory-grade.

  5. Relay hardware requires appropriate electrical isolation and ratings.

  6. AI commands require validation before device execution.

  7. ThingSpeak and other cloud services may impose service/API limitations.

  8. Telegram requires Internet connectivity for remote alerts.


58. Future enhancements

This project can be expanded considerably.

Face recognition

Camera
  ↓
Raspberry Pi
  ↓
Face Recognition
  ↓
Authorized User

Energy monitoring

Add:

Current sensor
Voltage sensor
Energy calculation

Then display:

Power = 124 W
Energy = 3.2 kWh

Solar monitoring

Add:

Solar voltage
Solar current
Battery voltage
Battery SOC

More AI tools

The AI Agent could have:

Weather tool
Energy tool
Security tool
Lighting tool
Fan tool
Sensor tool
Notification tool
Schedule tool

Scheduling

User:

"Turn the bedroom light on at 7 PM."

n8n:

AI
 ↓
Schedule
 ↓
7:00 PM
 ↓
ESP32
 ↓
Light ON

Geofencing

User leaves home
       ↓
Location event
       ↓
n8n
       ↓
Turn off appliances

59. Complete final architecture

The final project can be represented as:

                            ┌──────────────────┐
                            │      USER        │
                            └────────┬─────────┘
                                     │
               ┌─────────────────────┼─────────────────────┐
               │                     │                     │
               ▼                     ▼                     ▼
         🎤 Voice                🌐 Web                 📱 Telegram
               │                     │                     │
               └─────────────────────┼─────────────────────┘
                                     ▼
                         ┌───────────────────────┐
                         │     RASPBERRY PI      │
                         │                       │
                         │ Speech Recognition    │
                         │ Python                │
                         │ Flask Dashboard       │
                         │ TTS                   │
                         └───────────┬───────────┘
                                     │
                              HTTP/Webhook
                                     │
                                     ▼
                         ┌───────────────────────┐
                         │          n8n           │
                         │                       │
                         │ Workflow Automation   │
                         │ AI Agent               │
                         │ Validation             │
                         │ Decision Logic         │
                         └─────┬──────┬──────┬───┘
                               │      │      │
                    ┌──────────┘      │      └───────────┐
                    ▼                 ▼                  ▼
              ┌──────────┐      ┌───────────┐     ┌────────────┐
              │  ESP32   │      │  Google   │     │ Telegram   │
              │          │      │  Sheets   │     │ Bot        │
              └────┬─────┘      └───────────┘     └────────────┘
                   │
          ┌────────┼─────────┐
          │        │         │
          ▼        ▼         ▼
       Sensors   Relays    Status
          │        │
          ▼        ▼
       ThingSpeak Appliances
          │
          ▼
      Cloud Charts

60. Complete project operation

The entire system works as follows:

Step 1

The user speaks into the microphone.

Step 2

Raspberry Pi captures the audio.

Step 3

Speech recognition converts the audio into text.

Step 4

Raspberry Pi sends the text to n8n.

Step 5

n8n sends the command to the AI Agent.

Step 6

The AI Agent determines the user's intention.

Step 7

n8n validates the requested device and action.

Step 8

n8n sends a controlled HTTP command to ESP32.

Step 9

ESP32 changes the GPIO/relay state.

Step 10

ESP32 reads sensor values.

Step 11

Sensor information is forwarded to the cloud/automation layer.

Step 12

n8n stores the event in Google Sheets.

Step 13

n8n updates ThingSpeak.

Step 14

If an important event occurs, n8n sends Telegram notification.

Step 15

For voice notification, n8n converts the response to audio and sends it through Telegram.


61. Example complete interaction

👤 USER

"Hey, turn on the bedroom fan."

        ↓

🎤 MICROPHONE

Audio stream

        ↓

🍓 RASPBERRY PI

Speech recognition

        ↓

TEXT

"turn on the bedroom fan"

        ↓

⚙️ n8n

Webhook

        ↓

🤖 AI AGENT

Intent:
CONTROL

Device:
fan

Room:
bedroom

Action:
ON

        ↓

🛡️ VALIDATION

Device allowed?
YES

Action allowed?
YES

        ↓

📡 ESP32

POST /control

{
  "device": "fan",
  "action": "ON"
}

        ↓

⚡ RELAY

Fan ON

        ↓

📊 LOGGING

Google Sheets:
Fan | Bedroom | ON | Success

        ↓

☁️ CLOUD

ThingSpeak updated

        ↓

📱 TELEGRAM

"Bedroom fan has been turned on."

        ↓

🔊 OPTIONAL

Voice message:
"Bedroom fan has been turned on."

62. Suggested academic report structure

For a final-year project/documentation submission, use this chapter structure:

Chapter 1 — Introduction

  • Background

  • Problem statement

  • Motivation

  • Objectives

  • Scope

  • Applications

Chapter 2 — Literature/Technology Review

  • IoT

  • ESP32

  • Raspberry Pi

  • Speech recognition

  • Artificial intelligence

  • AI agents

  • n8n

  • Telegram

  • Google Sheets

  • ThingSpeak

Chapter 3 — System Analysis

  • Existing system

  • Proposed system

  • Requirements

  • Functional requirements

  • Non-functional requirements

Chapter 4 — System Design

  • Block diagram

  • Architecture

  • Flowchart

  • Circuit schematic

  • Data flow

  • Sequence diagram

  • API design

Chapter 5 — Hardware Implementation

  • Raspberry Pi

  • ESP32

  • DHT22

  • PIR

  • LDR

  • Gas sensor

  • Relay

  • Power supply

Chapter 6 — Software Implementation

  • Raspberry Pi OS

  • Python

  • Flask

  • Speech recognition

  • ESP32 Arduino firmware

  • n8n

  • AI Agent

  • Telegram

  • Google Sheets

  • ThingSpeak

Chapter 7 — Implementation

  • Hardware assembly

  • ESP32 programming

  • Raspberry Pi programming

  • n8n workflow

  • Dashboard

  • Telegram bot

Chapter 8 — Testing

  • Unit testing

  • Integration testing

  • Voice testing

  • Sensor testing

  • Relay testing

  • Cloud testing

  • Telegram testing

Chapter 9 — Results

  • Screenshots

  • Sensor graphs

  • Telegram alerts

  • Google Sheets logs

  • Dashboard

  • Voice-control demonstrations

Chapter 10 — Conclusion and Future Scope

  • Achievements

  • Limitations

  • Future improvements


63. Key technologies and documentation

For implementation/reference, the relevant official documentation includes:

  • Raspberry Pi Documentation — Raspberry Pi OS, hardware and GPIO documentation. Raspberry Pi+1

  • Arduino ESP32 documentation — ESP32 Arduino/Wi-Fi APIs. Espressif Systems+1

  • n8n Documentation — workflow automation and AI-agent capabilities. n8n Documentation

  • n8n Telegram node documentation — Telegram messaging/file/audio operations. n8n Documentation

  • ThingSpeak Documentation — IoT channels, REST/MQTT, visualization and analytics. MathWorks+1


64. Recommended final demonstration

For a strong project demonstration, show this sequence:

1. Dashboard is opened
          ↓
2. ESP32 sensor values appear
          ↓
3. Say:
   "Turn on the living room light."
          ↓
4. Light turns ON
          ↓
5. Google Sheets receives event
          ↓
6. ThingSpeak receives data
          ↓
7. Telegram receives confirmation
          ↓
8. Trigger PIR sensor
          ↓
9. Telegram alert appears
          ↓
10. Telegram voice command:
    "Turn off the fan."
          ↓
11. AI interprets command
          ↓
12. ESP32 turns fan OFF
          ↓
13. Telegram voice confirmation

That single demonstration showcases voice AI + agentic automation + ESP32 + Raspberry Pi + n8n + IoT cloud + database/logging + Telegram, rather than presenting these as disconnected technologies.

One important implementation refinement

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

Phase 1
ESP32 + Sensors + Relay
        ↓
Phase 2
ESP32 HTTP API
        ↓
Phase 3
Raspberry Pi Web Dashboard
        ↓
Phase 4
Raspberry Pi Speech Recognition
        ↓
Phase 5
n8n Webhook + ESP32 control
        ↓
Phase 6
AI Agent + validation
        ↓
Phase 7
Google Sheets
        ↓
Phase 8
ThingSpeak
        ↓
Phase 9
Telegram text alerts
        ↓
Phase 10
Telegram voice commands + voice alerts
        ↓
Phase 11
Fail-safe/security + final testing

This staged approach prevents a common project problem: trying to debug AI, Wi-Fi, ESP32, sensors, n8n, Telegram and cloud APIs simultaneously.

Project Summary

The project is an AI-powered smart-home automation system combining Raspberry Pi, ESP32, n8n, AI Agent, Telegram, Google Sheets, ThingSpeak, and a web dashboard.

Core architecture

             USER
        ┌──────┼──────┐
        ▼      ▼      ▼
      Voice   Web  Telegram
        │      │      │
        └──────┼──────┘
               ▼
        Raspberry Pi
     Voice + Web Gateway
               │
               ▼
             n8n
      Automation + AI Agent
               │
       ┌───────┼────────┐
       ▼       ▼        ▼
     ESP32   Sheets   Telegram
       │
 ┌─────┼────────┐
 ▼     ▼        ▼
Sensors Relays  Status
 │      │
 ▼      ▼
ThingSpeak Appliances

Main responsibilities

  • Raspberry Pi

    • Speech recognition

    • Web dashboard

    • Text-to-speech

    • Local gateway

    • Sends commands to n8n

  • ESP32

    • Reads sensors

    • Controls relays

    • Provides HTTP API

    • Controls lights/fans/appliances

  • n8n

    • Receives commands

    • Runs AI Agent

    • Validates commands

    • Communicates with ESP32

    • Logs data

    • Generates alerts

  • AI Agent

    • Understands natural-language commands

    • Converts them into structured actions

    • Uses controlled tools instead of directly accessing GPIO

  • Telegram

    • Remote commands

    • Text notifications

    • Voice commands

    • Voice alerts

  • Google Sheets

    • Stores command/event history

  • ThingSpeak

    • Stores and visualizes sensor data

  • Web dashboard

    • Device control

    • Sensor monitoring

    • AI command interface

Example operation

User says:

“Turn on the bedroom fan.”

Voice
 ↓
Raspberry Pi
 ↓
Speech → Text
 ↓
n8n
 ↓
AI Agent
 ↓
{device:"fan", action:"ON"}
 ↓
Validation
 ↓
ESP32
 ↓
Relay
 ↓
Fan ON

Then:

ESP32 → n8n → Google Sheets
             ↓
          ThingSpeak
             ↓
          Telegram

Sensors

The proposed prototype uses:

  • DHT22 — temperature/humidity

  • PIR — motion

  • LDR — light level

  • MQ-series sensor — gas/air-quality demonstration

Outputs

  • Light

  • Fan

  • Appliance

  • Additional relay-controlled loads

Key workflows

  1. Voice/Web → AI → ESP32 → appliance

  2. Telegram voice → speech recognition → AI → ESP32

  3. ESP32 → n8n → ThingSpeak

  4. ESP32 → n8n → Google Sheets

  5. Sensor event → n8n → Telegram alert

  6. Event → TTS → Telegram voice notification

Recommended development order

1. ESP32 + sensors + relay
2. ESP32 HTTP API
3. Raspberry Pi web dashboard
4. Voice recognition
5. n8n integration
6. AI Agent
7. Command validation
8. Google Sheets
9. ThingSpeak
10. Telegram alerts
11. Telegram voice commands
12. Voice notifications
13. Security + fail-safe testing

Final project concept

“An AI-driven, voice-controlled, agentic IoT smart-home platform in which Raspberry Pi provides local voice/web interaction, ESP32 performs real-time sensing and actuator control, and n8n coordinates AI decisions, cloud logging, dashboards, and Telegram-based remote notifications.”

 

Thursday, 1 October 2026

IoT-Based Smart Grid Load Redistribution and Monitoring System Using Arduino and ESP8266

Project Summary

Project Title:
Design and Implementation of a Smart Grid Load Redistribution System Using IoT

This project presents an IoT-based smart electrical load management system designed to monitor grid voltage and current and automatically manage multiple electrical loads according to the measured load condition.

The system uses an Arduino as the main controller and an ESP8266 Wi-Fi module for IoT connectivity. A ZMP101B voltage sensor measures the AC supply voltage, while an ACS712 current sensor measures the load current. The Arduino processes these measurements and controls three relay channels, each connected to a different AC bulb representing an individual electrical load.

When the monitored load reaches a predefined limit, the controller can activate the alarm and progressively disconnect selected loads through the relays. This demonstrates the basic concept of automatic load shedding and load redistribution. The ESP8266 sends electrical parameters and load status to an IoT/web dashboard for remote monitoring.

Main Components

  • Arduino
  • ESP8266 Wi-Fi module
  • ZMP101B voltage sensor
  • ACS712 current sensor
  • 3 relay modules/coils
  • 3 AC bulbs as demonstration loads
  • Alarm/buzzer
  • Power supply

Working Flow

AC Grid Supply → Voltage & Current Sensors → Arduino → Load Analysis → Relay Control → 3 Loads

At the same time:

Arduino → ESP8266 → Wi-Fi → IoT/Web Dashboard

Major Features

  • Real-time voltage monitoring
  • Real-time current monitoring
  • Electrical load/power estimation
  • Automatic load management
  • Three independent relay-controlled loads
  • Overload detection
  • Automatic load shedding
  • Alarm indication
  • ESP8266 Wi-Fi communication
  • IoT/web-based remote monitoring
  • Load status monitoring
  • Improved electrical load management

Expected Operation

Normal condition:
All three loads remain ON.

High-load condition:
The system detects excessive current/power and disconnects a selected lower-priority load.

Persistent overload:
Additional loads can be disconnected according to the programmed priority.

Critical condition:
The alarm is activated and the system reports the condition through the IoT interface.

Safety: The three bulbs represent AC/mains loads in the prototype. Properly rated relays, fuses/MCBs, isolation, insulated wiring, and an enclosed mains section should be used.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Project Documentation

 

Below is a complete documentation structure for your project, including the project description, objectives, hardware, working principle, block diagram, circuit/pin connections, flowcharts, control algorithm, Arduino code, ESP8266 IoT code, testing procedure, advantages, limitations, applications, and future scope.

Design and Implementation of a Smart Grid Load Redistribution System Using IoT

  1. Abstract

The Smart Grid Load Redistribution System Using IoT is an intelligent electrical load monitoring and management system designed to monitor the voltage and current of an electrical supply and automatically control multiple electrical loads according to the measured load condition.

The proposed system uses an Arduino as the main controller, an ESP8266 Wi-Fi module for IoT communication, a ZMPT101B voltage sensor for AC voltage measurement, and an ACS712 current sensor for AC current measurement. Three relay channels are used to control three separate electrical loads represented by AC bulbs. An alarm/buzzer provides a local indication when an overload or abnormal electrical condition is detected.

The Arduino continuously measures the electrical parameters, calculates the approximate load power, compares the measured load with predefined safety limits, and controls the relay channels according to load priority. During normal operation, all loads can remain active. When excessive loading is detected, the system can disconnect lower-priority loads sequentially. The ESP8266 transmits the measured parameters and load status to an IoT/web platform for remote monitoring.

The project demonstrates the basic principles of smart load management, automatic load shedding, electrical parameter monitoring, IoT connectivity, and intelligent energy management.

Technical terminology: In this prototype, "load redistribution" is implemented primarily through priority-based load management/load shedding. It does not physically redistribute power between utility-grid phases.

  1. Introduction

Traditional electrical systems generally depend on manual monitoring and switching of loads. When several loads operate simultaneously, the total current can increase beyond the desired operating limit. This can result in excessive loading, unnecessary energy consumption, or activation of protective devices.

A smart load management system can continuously monitor electrical parameters and automatically control non-critical loads.

The proposed system combines:

  • Electrical sensing
  • Microcontroller processing
  • Automatic relay control
  • Overload detection
  • Alarm indication
  • Wi-Fi communication
  • IoT monitoring

The Arduino performs the real-time sensing and control functions, while the ESP8266 provides wireless communication between the physical system and an IoT/web platform.

  1. Project Objectives

The main objectives are:

  1. To continuously monitor AC voltage.
  2. To continuously monitor load current.
  3. To estimate electrical power consumption.
  4. To monitor multiple electrical loads.
  5. To control three independent loads using relays.
  6. To detect excessive electrical loading.
  7. To automatically disconnect lower-priority loads when required.
  8. To activate an alarm during abnormal conditions.
  9. To transmit electrical data through Wi-Fi.
  10. To provide IoT-based remote monitoring.
  11. To demonstrate intelligent electrical load management.
  1. Proposed System

The proposed system consists of five major sections:

Section 1 — Measurement

The ZMPT101B measures AC voltage and the ACS712 measures AC current.

Section 2 — Processing

The Arduino receives the sensor signals and calculates:

  • Voltage
  • Current
  • Approximate power
  • Load condition

Section 3 — Load Control

Three relay channels control three separate loads:

Relay 1 → Bulb 1 → Load 1

Relay 2 → Bulb 2 → Load 2

Relay 3 → Bulb 3 → Load 3

Section 4 — Protection

When the load exceeds the configured limit:

Overload

   ↓

Alarm ON

   ↓

Disconnect Load 3

   ↓

Check Load

   ↓

Still High?

   ↓

Disconnect Load 2

Section 5 — IoT

The ESP8266 sends information through Wi-Fi to an IoT/web dashboard.

  1. System Architecture

                         AC GRID SUPPLY

                              │

                ┌─────────────┴─────────────┐

                │                           │

         ZMPT101B Sensor              ACS712 Sensor

         Voltage Measurement          Current Measurement

                │                           │

                └─────────────┬─────────────┘

                              │

                         ARDUINO UNO

                       Main Controller

                              │

          ┌───────────────────┼──────────────────┐

          │                   │                  │

       Relay 1             Relay 2            Relay 3

          │                   │                  │

       Bulb 1              Bulb 2             Bulb 3

       Load 1              Load 2             Load 3

          │

          └───────────────┐

                          │

                     Alarm/Buzzer

                          │

                       ESP8266

                       Wi-Fi

                          │

                    INTERNET / IoT

                          │

                   WEB DASHBOARD

  1. Hardware Components

Component

Quantity

Function

Arduino UNO

1

Main controller

ESP8266

1

Wi-Fi/IoT communication

ZMPT101B

1

AC voltage measurement

ACS712

1

AC current measurement

Relay module

3

Load switching

AC Bulb

3

Demonstration loads

Buzzer/Alarm

1

Overload indication

5V Power Supply

1

Controller/relay supply

Connecting wires

As required

Connections

Fuse/MCB

1

AC protection

  1. ZMPT101B Voltage Sensor

The ZMPT101B is an isolated AC voltage sensing module.

It provides a low-voltage analog signal corresponding to the measured AC voltage.

Connection

ZMPT101B

 ├── VCC → 5V

 ├── GND → Arduino GND

 └── OUT → Arduino A0

The actual voltage calibration depends on the sensor module and its potentiometer/calibration setting.

Therefore, the voltage calibration constant in the software should be adjusted using a properly rated measuring instrument.

  1. ACS712 Current Sensor

The ACS712 measures current using the Hall-effect principle.

Typical versions include:

  • ACS712 5A
  • ACS712 20A
  • ACS712 30A

The output is an analog voltage proportional to the current.

ACS712

 ├── VCC → 5V

 ├── GND → Arduino GND

 └── OUT → Arduino A1

The sensitivity depends on the exact ACS712 version.

Typical nominal sensitivities are:

Version

Approx. Sensitivity

5A

185 mV/A

20A

100 mV/A

30A

66 mV/A

The correct value must match the actual module used.

  1. Relay and Load Section

Three relays are used to control three separate loads.

Arduino D5 → Relay 1 → Bulb 1

Arduino D6 → Relay 2 → Bulb 2

Arduino D7 → Relay 3 → Bulb 3

Suggested priority:

Load 1 = Highest Priority

Load 2 = Medium Priority

Load 3 = Lowest Priority

Therefore, during overload:

First disconnect → Load 3

Second disconnect → Load 2

Last disconnect → Load 1

This priority can be changed in the program.

  1. Alarm Circuit

The alarm/buzzer is controlled by the Arduino.

Arduino D8 → Buzzer control

When an overload condition occurs:

Overload detected

       ↓

Buzzer ON

       ↓

Load management begins

For a higher-power alarm, use a transistor/MOSFET driver rather than connecting the alarm directly to an Arduino pin.

  1. ESP8266 IoT Section

The ESP8266 provides Wi-Fi connectivity.

The communication structure is:

Sensors

   ↓

Arduino

   ↓

Serial Communication

   ↓

ESP8266

   ↓

Wi-Fi Router

   ↓

Internet

   ↓

IoT Platform / Web Dashboard

The ESP8266 can transmit:

  • Voltage
  • Current
  • Power
  • Load 1 status
  • Load 2 status
  • Load 3 status
  • Overload status
  • Alarm status
  1. Arduino Pin Configuration

A practical pin assignment is:

Arduino Pin

Connection

A0

ZMPT101B voltage output

A1

ACS712 current output

D2

ESP8266 TX → Arduino RX

D3

Arduino TX → ESP8266 RX through level shifting

D5

Relay 1

D6

Relay 2

D7

Relay 3

D8

Alarm/Buzzer

5V

Sensor/relay supply as appropriate

GND

Common low-voltage ground

Important ESP8266 note

The ESP8266 uses 3.3 V logic. Do not directly feed a 5 V Arduino TX signal into an ESP8266 RX pin. Use an appropriate 3.3 V logic-level interface/voltage divider.

  1. Complete Working Principle

Step 1 — System Initialization

When the system starts, the Arduino initializes:

  • Analog sensor inputs
  • Relay outputs
  • Alarm output
  • Serial communication
  • ESP8266 communication

Initially:

Load 1 → ON

Load 2 → ON

Load 3 → ON

Alarm → OFF

Step 2 — Sensor Measurement

The Arduino reads the ZMPT101B and ACS712 signals.

Voltage Sensor → Voltage

Current Sensor → Current

The controller then estimates the electrical power.

For a simplified resistive-load demonstration:

P=V×IP = V \times I

where:

  • P = power in watts
  • V = RMS voltage
  • I = RMS current

For real AC loads with significant power factor, actual real power requires power-factor measurement rather than simply multiplying RMS voltage and RMS current.

  1. Load Decision Algorithm

The controller compares measured power against a configured limit.

Example:

Power Limit = 1000 W

Normal

Power ≤ 1000 W

 

Load 1 = ON

Load 2 = ON

Load 3 = ON

Alarm = OFF

Overload

Power > 1000 W

        ↓

Alarm ON

        ↓

Load 3 OFF

        ↓

Measure again

If the load is still excessive:

Load 2 OFF

        ↓

Measure again

If still excessive:

Load 1 OFF

  1. Load Redistribution Flow

             START

               │

               ▼

       Initialize Arduino

               │

               ▼

       Initialize ESP8266

               │

               ▼

          Connect Wi-Fi

               │

               ▼

        Read Voltage

               │

               ▼

         Read Current

               │

               ▼

        Calculate Power

               │

               ▼

       Send Data to IoT

               │

               ▼

       Is Load Safe?

          /         \

        YES          NO

         │            │

         ▼            ▼

     Keep Loads     Alarm ON

        ON             │

         │             ▼

         │         Turn OFF

         │          Load 3

         │             │

         │             ▼

         │       Check Load Again

         │             │

         │       Still Excessive?

         │          /       \

         │        NO         YES

         │        │           │

         │        │           ▼

         │        │       Turn OFF

         │        │        Load 2

         │        │           │

         │        │           ▼

         │        │       Check Again

         │        │

         └────────┴───────────┐

                              ▼

                       Update IoT Data

                              │

                              ▼

                    Continuous Monitoring

                              │

                              └──→ Repeat

  1. Detailed Circuit Concept

             AC 230V SUPPLY

               L       N

               │       │

               │       └───────────────────────┐

               │                               │

             FUSE                              │

               │                               │

               ├──── ZMPT101B ─────┐           │

               │                   │           │

               │              Voltage OUT      │

               │                   │           │

               │                  A0           │

               │                   │           │

               └──── ACS712 ───────┐           │

                                   │           │

                              Current OUT       │

                                   │           │

                                  A1           │

                                                │

              ARDUINO UNO                       │

          ┌───────────────────┐                 │

          │                   │                 │

 A0 ◄─────┤ ZMPT101B          │                 │

 A1 ◄─────┤ ACS712             │                 │

          │                   │                 │

 D5 ─────►│ Relay 1            │────► Load 1

 D6 ─────►│ Relay 2            │────► Load 2

 D7 ─────►│ Relay 3            │────► Load 3

 D8 ─────►│ Alarm              │

          │                   │

 D2 ◄─────┤ ESP8266 TX         │

 D3 ─────►│ ESP8266 RX*        │

          └───────────────────┘

                    │

                    ▼

                ESP8266

                    │

                  Wi-Fi

                    │

                    ▼

              IoT Dashboard

* Use appropriate 3.3 V level shifting between Arduino TX and ESP8266 RX.

  1. Control Logic

The software follows this logic:

IF voltage/current readings are valid

        ↓

Calculate electrical load

        ↓

IF load <= safe limit

        ↓

Keep all required loads ON

 

ELSE

        ↓

Activate alarm

        ↓

Turn OFF lowest-priority load

        ↓

Wait for stabilization

        ↓

Measure again

 

IF load is still high

        ↓

Turn OFF next lower-priority load

 

IF load becomes safe

        ↓

Maintain remaining loads

        ↓

Continue IoT monitoring

  1. Arduino Software

The following example assumes:

  • ZMPT101B OUT → A0
  • ACS712 OUT → A1
  • Relay 1 → D5
  • Relay 2 → D6
  • Relay 3 → D7
  • Buzzer → D8
  • ESP8266 serial → D2/D3

It also assumes an active-LOW relay module. If your relay is active-HIGH, reverse the relay logic.

#include <SoftwareSerial.h>

#include <math.h>

 

// ---------------- PIN DEFINITIONS ----------------

#define VOLTAGE_PIN A0

#define CURRENT_PIN A1

 

#define RELAY1 5

#define RELAY2 6

#define RELAY3 7

 

#define BUZZER 8

 

// Arduino RX, TX

SoftwareSerial espSerial(2, 3);

 

// ---------------- SETTINGS ----------------

 

// Adjust these after calibration

float VOLTAGE_CALIBRATION = 1.00;

 

// ACS712 sensitivity.

// Change according to your actual ACS712 version.

float ACS_SENSITIVITY = 0.100;   // 20A version = approx 100mV/A

 

// ADC reference

float ADC_REFERENCE = 5.0;

 

// Approximate safe power limit

float POWER_LIMIT = 1000.0;

 

// Recovery threshold with hysteresis

float RECOVERY_LIMIT = 800.0;

 

// Relay active LOW

#define RELAY_ON  LOW

#define RELAY_OFF HIGH

 

bool load1 = true;

bool load2 = true;

bool load3 = true;

 

unsigned long lastSend = 0;

 

// ------------------------------------------------

 

void setup()

{

  Serial.begin(9600);

  espSerial.begin(9600);

 

  pinMode(RELAY1, OUTPUT);

  pinMode(RELAY2, OUTPUT);

  pinMode(RELAY3, OUTPUT);

  pinMode(BUZZER, OUTPUT);

 

  digitalWrite(RELAY1, RELAY_ON);

  digitalWrite(RELAY2, RELAY_ON);

  digitalWrite(RELAY3, RELAY_ON);

  digitalWrite(BUZZER, LOW);

 

  delay(2000);

 

  Serial.println("SMART GRID LOAD MANAGEMENT SYSTEM");

}

 

// ------------------------------------------------

 

float readVoltage()

{

  long sum = 0;

 

  for (int i = 0; i < 500; i++)

  {

    sum += analogRead(VOLTAGE_PIN);

    delayMicroseconds(200);

  }

 

  float averageADC = sum / 500.0;

 

  float sensorVoltage =

      (averageADC * ADC_REFERENCE) / 1023.0;

 

  /*

    The exact conversion from sensor output

    to AC RMS voltage depends on calibration.

 

    Replace this factor after calibration.

  */

 

  float mainsVoltage =

      sensorVoltage * VOLTAGE_CALIBRATION;

 

  return mainsVoltage;

}

 

// ------------------------------------------------

 

float readCurrent()

{

  const int samples = 500;

 

  float sumSquares = 0;

 

  // Estimate ACS712 zero-current offset

  float offset = 512.0;

 

  for (int i = 0; i < samples; i++)

  {

    int adcValue = analogRead(CURRENT_PIN);

 

    float centered =

        adcValue - offset;

 

    float voltage =

        (centered * ADC_REFERENCE) / 1023.0;

 

    sumSquares += voltage * voltage;

 

    delayMicroseconds(200);

  }

 

  float rmsVoltage =

      sqrt(sumSquares / samples);

 

  float current =

      rmsVoltage / ACS_SENSITIVITY;

 

  return current;

}

 

// ------------------------------------------------

 

void controlLoads(float power)

{

  if (power > POWER_LIMIT)

  {

    digitalWrite(BUZZER, HIGH);

 

    // First shed lowest-priority load

    if (load3)

    {

      digitalWrite(RELAY3, RELAY_OFF);

      load3 = false;

 

      Serial.println("OVERLOAD: LOAD 3 OFF");

      delay(1000);

      return;

    }

 

    // Second priority

    if (load2)

    {

      digitalWrite(RELAY2, RELAY_OFF);

      load2 = false;

 

      Serial.println("OVERLOAD: LOAD 2 OFF");

      delay(1000);

      return;

    }

 

    // Last priority

    if (load1)

    {

      digitalWrite(RELAY1, RELAY_OFF);

      load1 = false;

 

      Serial.println("CRITICAL: LOAD 1 OFF");

      delay(1000);

      return;

    }

  }

  else

  {

    digitalWrite(BUZZER, LOW);

  }

}

 

// ------------------------------------------------

 

void sendData(float voltage,

              float current,

              float power)

{

  espSerial.print("V=");

  espSerial.print(voltage, 2);

 

  espSerial.print(",I=");

  espSerial.print(current, 2);

 

  espSerial.print(",P=");

  espSerial.print(power, 2);

 

  espSerial.print(",L1=");

  espSerial.print(load1 ? 1 : 0);

 

  espSerial.print(",L2=");

  espSerial.print(load2 ? 1 : 0);

 

  espSerial.print(",L3=");

  espSerial.print(load3 ? 1 : 0);

 

  espSerial.println();

}

 

// ------------------------------------------------

 

void loop()

{

  float voltage = readVoltage();

  float current = readCurrent();

 

  float power = voltage * current;

 

  Serial.print("Voltage: ");

  Serial.print(voltage);

  Serial.println(" V");

 

  Serial.print("Current: ");

  Serial.print(current);

  Serial.println(" A");

 

  Serial.print("Power: ");

  Serial.print(power);

  Serial.println(" W");

 

  controlLoads(power);

 

  if (millis() - lastSend > 5000)

  {

    sendData(voltage, current, power);

 

    lastSend = millis();

  }

 

  delay(1000);

}

  1. Important Sensor Calibration

The above program intentionally leaves the voltage conversion as a calibration parameter because the actual ZMPT101B module output depends on the particular module and adjustment.

For example:

float VOLTAGE_CALIBRATION = 1.00;

should be experimentally calibrated.

Calibration procedure

Use a properly rated AC measuring instrument.

  1. Apply the intended AC input.
  2. Measure the actual RMS voltage using the reference instrument.
  3. Observe the Arduino calculated voltage.
  4. Adjust the calibration factor.
  5. Repeat until the displayed value is reasonably close.
  6. Do the same for the ACS712 current measurement.

Do not calibrate or probe exposed mains wiring by hand.

  1. ESP8266 IoT Software

The ESP8266 can receive the Arduino data through serial communication and upload it to an IoT service.

One practical implementation is ThingSpeak.

Replace:

YOUR_WIFI_NAME

YOUR_WIFI_PASSWORD

YOUR_THINGSPEAK_API_KEY

with your actual credentials.

#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>

 

const char* ssid = "YOUR_WIFI_NAME";

const char* password = "YOUR_WIFI_PASSWORD";

 

String apiKey = "YOUR_THINGSPEAK_API_KEY";

 

WiFiClient client;

 

String serialData = "";

 

float voltage = 0;

float current = 0;

float power = 0;

 

int load1 = 0;

int load2 = 0;

int load3 = 0;

 

void setup()

{

  Serial.begin(9600);

 

  WiFi.begin(ssid, password);

 

  while (WiFi.status() != WL_CONNECTED)

  {

    delay(500);

  }

 

  Serial.println();

  Serial.println("ESP8266 CONNECTED");

  Serial.println(WiFi.localIP());

}

 

void parseData(String data)

{

  int p;

 

  p = data.indexOf("V=");

  if (p >= 0)

  {

    voltage =

      data.substring(p + 2,

      data.indexOf(",", p)).toFloat();

  }

 

  p = data.indexOf("I=");

  if (p >= 0)

  {

    current =

      data.substring(p + 2,

      data.indexOf(",", p)).toFloat();

  }

 

  p = data.indexOf("P=");

  if (p >= 0)

  {

    power =

      data.substring(p + 2,

      data.indexOf(",", p)).toFloat();

  }

 

  p = data.indexOf("L1=");

  if (p >= 0)

  {

    load1 =

      data.substring(p + 3,

      data.indexOf(",", p)).toInt();

  }

 

  p = data.indexOf("L2=");

  if (p >= 0)

  {

    load2 =

      data.substring(p + 3,

      data.indexOf(",", p)).toInt();

  }

 

  p = data.indexOf("L3=");

  if (p >= 0)

  {

    load3 =

      data.substring(p + 3).toInt();

  }

}

 

void uploadData()

{

  if (WiFi.status() != WL_CONNECTED)

  {

    WiFi.begin(ssid, password);

    return;

  }

 

  HTTPClient http;

 

  String url =

    "http://api.thingspeak.com/update?api_key="

    + apiKey

    + "&field1=" + String(voltage, 2)

    + "&field2=" + String(current, 2)

    + "&field3=" + String(power, 2)

    + "&field4=" + String(load1)

    + "&field5=" + String(load2)

    + "&field6=" + String(load3);

 

  http.begin(client, url);

 

  int httpCode = http.GET();

 

  Serial.print("ThingSpeak Response: ");

  Serial.println(httpCode);

 

  http.end();

}

 

void loop()

{

  if (Serial.available())

  {

    serialData = Serial.readStringUntil('\n');

 

    serialData.trim();

 

    if (serialData.length() > 0)

    {

      parseData(serialData);

 

      Serial.print("Voltage = ");

      Serial.println(voltage);

 

      Serial.print("Current = ");

      Serial.println(current);

 

      Serial.print("Power = ");

      Serial.println(power);

 

      uploadData();

    }

  }

 

  delay(100);

}

  1. IoT Data Fields

The IoT dashboard can contain:

Field

Parameter

Field 1

Voltage

Field 2

Current

Field 3

Power

Field 4

Load 1

Field 5

Load 2

Field 6

Load 3

Example:

Voltage       : 231 V

Current       : 3.25 A

Power         : 750 W

Load 1        : ON

Load 2        : ON

Load 3        : OFF

System Status : LOAD MANAGED

  1. Software Flowchart

                 ┌───────────┐

                 │   START   │

                 └─────┬─────┘

                       ↓

             ┌──────────────────┐

             │ Initialize System│

             └────────┬─────────┘

                      ↓

             ┌──────────────────┐

             │ Initialize Wi-Fi │

             └────────┬─────────┘

                      ↓

             ┌──────────────────┐

             │ Read Voltage     │

             │ Read Current     │

             └────────┬─────────┘

                      ↓

             ┌──────────────────┐

             │ Calculate Power  │

             └────────┬─────────┘

                      ↓

             ┌──────────────────┐

             │ Send IoT Data    │

             └────────┬─────────┘

                      ↓

                ┌────────────┐

                │ Load Safe? │

                └─────┬──┬───┘

                   YES│  │NO

                      │  │

                      ↓  ↓

             ┌─────────┐ ┌─────────────┐

             │ Keep ON │ │ Alarm ON    │

             └────┬────┘ └──────┬──────┘

                  │              ↓

                  │       ┌──────────────┐

                  │       │ Load 3 OFF   │

                  │       └──────┬───────┘

                  │              ↓

                  │       ┌──────────────┐

                  │       │ Measure Again│

                  │       └──────┬───────┘

                  │              ↓

                  │        Still High?

                  │         /        \

                  │       NO          YES

                  │       │            ↓

                  │       │      Load 2 OFF

                  │       │            ↓

                  │       │      Measure Again

                  │       │

                  └───────┴───────────────→

                              ↓

                       CONTINUOUS LOOP

  1. Hardware Flow

AC Supply

    ↓

┌──────────────────────┐

│ Voltage Measurement  │

│ ZMPT101B             │

└──────────┬───────────┘

           │

           ├─────────────┐

           ↓             ↓

      Arduino         ACS712

           │          Current

           │          Measurement

           └─────┬───────┘

                 ↓

          Load Calculation

                 ↓

          Decision Making

                 ↓

       ┌─────────┼─────────┐

       ↓         ↓         ↓

    Relay 1   Relay 2   Relay 3

       ↓         ↓         ↓

    Bulb 1    Bulb 2    Bulb 3

                 │

                 ↓

             Alarm

                 │

                 ↓

             ESP8266

                 ↓

               Wi-Fi

                 ↓

          IoT Dashboard

  1. Operating Modes

Mode 1 — Normal

Voltage Normal

Current Normal

Power Normal

 

Relay 1 = ON

Relay 2 = ON

Relay 3 = ON

Alarm = OFF

Mode 2 — High Load

Power > Limit

 

Alarm = ON

Relay 3 = OFF

Mode 3 — Continued Overload

Power still > Limit

 

Relay 2 = OFF

Mode 4 — Critical Load

Power remains excessive

 

Relay 1 = OFF

Alarm = ON

  1. Example Demonstration

Suppose:

Voltage = 230 V

Load 1 = 200 W

Load 2 = 300 W

Load 3 = 600 W

Total:

Ptotal=200+300+600P_{total}=200+300+600 Ptotal=1100WP_{total}=1100W

If the configured limit is:

1000 W

then:

1100 W > 1000 W

Therefore:

Alarm ON

Load 3 OFF

After Load 3 is disconnected:

200 W + 300 W = 500 W

The system is now below the limit.

Therefore:

Load 1 = ON

Load 2 = ON

Load 3 = OFF

Alarm = OFF/managed according to program

This demonstrates priority-based automatic load management.

  1. Expected Results

The expected prototype results are:

Condition

Load 1

Load 2

Load 3

Alarm

Normal

ON

ON

ON

OFF

High Load

ON

ON

OFF

ON

Continued High Load

ON

OFF

OFF

ON

Critical

OFF

OFF

OFF

ON

Load Normalized

Controlled recovery

Controlled recovery

Controlled recovery

OFF

The exact thresholds and recovery behavior should be determined from the actual prototype and programmed requirements.

  1. Testing Procedure

Test 1 — Voltage Sensor

Verify that the Arduino receives a changing analog signal when the monitored AC voltage changes.

Record:

Reference Voltage

Sensor Reading

Error

Test 2 — Current Sensor

Connect an appropriate test load and compare the ACS712 reading with a suitable reference meter.

Record:

Reference Current

ACS712 Current

Measurement Error

Test 3 — Relay Test

Test each relay individually:

Relay 1 → Bulb 1

Relay 2 → Bulb 2

Relay 3 → Bulb 3

Test 4 — Overload Test

Increase the demonstration load within safe limits.

Observe:

Power increases

       ↓

Threshold exceeded

       ↓

Alarm activates

       ↓

Lowest-priority relay switches OFF

       ↓

Power decreases

Test 5 — IoT Test

Check:

Arduino

   ↓

ESP8266

   ↓

Wi-Fi

   ↓

IoT platform

Verify that voltage, current, power and load status are updated.

  1. Advantages
  1. Automatic electrical load management.
  2. Real-time voltage monitoring.
  3. Real-time current monitoring.
  4. Multiple load control.
  5. Overload protection logic.
  6. Local alarm indication.
  7. IoT-based remote monitoring.
  8. Wireless communication.
  9. Reduced dependence on manual switching.
  10. Expandable architecture.
  11. Suitable for educational smart-grid demonstrations.
  1. Limitations
  1. The prototype uses simplified load-control logic.
  2. Voltage/current sensor calibration is required.
  3. ACS712 accuracy depends on the selected version and installation.
  4. Simple V × I gives apparent power for general AC loads unless power factor is accounted for.
  5. Wi-Fi-based monitoring depends on network availability.
  6. The prototype demonstrates load shedding rather than utility-scale grid power redistribution.
  7. Relay ratings must match the connected loads.
  1. Applications

The concept can be adapted for:

  • Smart homes
  • Smart buildings
  • Industrial load management
  • Energy monitoring systems
  • Educational smart-grid prototypes
  • Laboratory load management
  • Commercial building automation
  • IoT energy-management systems
  • Automatic non-critical-load shedding
  • Electrical safety monitoring
  1. Future Enhancements

The project can be extended with:

AI-Based Load Prediction

Historical power data can be analyzed to predict future load conditions.

Mobile Application

A mobile application can display:

Voltage

Current

Power

Load Status

Alarm Status

Remote Load Control

Authorized users could control individual loads through an IoT dashboard.

Cloud Database

Historical electrical data can be stored for:

  • Daily analysis
  • Weekly analysis
  • Monthly consumption
  • Peak-load identification

Energy Metering

Energy consumption can be calculated:

Energy=Power×TimeEnergy = Power \times Time

and displayed in kWh.

Advanced Power Measurement

A dedicated energy-metering IC or suitable power-monitoring hardware can be added for more accurate real-power and power-factor measurements.

AI-Based Load Scheduling

The system could automatically determine which loads should operate according to priority and predicted demand.

  1. Conclusion

The Design and Implementation of a Smart Grid Load Redistribution System Using IoT demonstrates how embedded systems and wireless communication can be combined to create an intelligent electrical load-management solution.

The ZMPT101B voltage sensor and ACS712 current sensor provide electrical measurements to the Arduino. The Arduino processes these measurements and controls three relay-operated loads. When the electrical load exceeds a predefined limit, the system can activate an alarm and progressively disconnect lower-priority loads. The ESP8266 provides wireless connectivity, allowing electrical parameters and load status to be monitored through an IoT platform.

The prototype therefore combines sensing, processing, automatic load control, alarm indication, and IoT monitoring into one integrated system.

  1. One-Line Project Architecture

ZMPT101B + ACS712

        ↓

     Arduino

        ↓

Load Calculation & Decision

        ↓

 ┌──────┼──────┐

 ↓      ↓      ↓

R1     R2     R3

 ↓      ↓      ↓

B1     B2     B3

        ↓

      Alarm

        ↓

    ESP8266 Wi-Fi

        ↓

 IoT / Web Dashboard

Important implementation note

For your actual prototype, use the exact sensor designation printed on your module—ZMPT101B is the commonly used AC voltage-sensor module. Also, the three bulbs are mains loads, so the AC side should use appropriately rated relays, fuse/MCB protection, insulated terminals/enclosure, and proper isolation from the Arduino/ESP8266 low-voltage circuitry. The circuit should be assembled and tested by someone qualified to work with mains voltage.