Friday, 2 October 2026

AI Wearable Cardiac Monitoring Device with Emergency Prediction

AI Wearable Cardiac Monitoring & Emergency Alert System

ESP32 + ECG/PPG Sensors + AI Anomaly Analysis + n8n Agentic Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak + IoT Web Dashboard

Below is a complete academic/engineering prototype design you can use for a final-year project, mini-project, research prototype, or proof-of-concept.

Important safety scope: this should be presented as an experimental cardiac-monitoring and anomaly-alert prototype, not as a certified medical device. The AI should detect potential abnormal patterns and trigger a request for human attention; it should not claim to diagnose a heart attack, predict death, or replace a doctor/emergency service.


1. Project title

AI-Powered Wearable Cardiac Monitoring and Emergency Alert System Using ESP32, n8n Agentic Automation, Telegram Voice Notifications, Google Sheets and ThingSpeak

Short title

Agentic AI Cardiac IoT Wearable


2. Project abstract

This project develops a wearable IoT system capable of continuously collecting physiological signals such as ECG, heart rate and optionally SpO₂, processing the measurements using an ESP32 microcontroller, transmitting the data to a cloud automation platform, and generating intelligent alerts when potentially abnormal patterns are detected.

The wearable consists of an ESP32, an ECG sensor such as AD8232, and optionally a MAX30102 optical sensor for heart-rate/SpO₂ measurements. ESP32 provides Wi-Fi connectivity and can operate as the Internet-connected edge controller. Espressif documents both Wi-Fi station mode and HTTP/HTTPS networking for ESP32. Espressif Systems+1

The sensor data is sent to an n8n workflow through an HTTPS webhook. n8n acts as the automation and agentic layer. It validates the incoming data, calculates an anomaly/risk state, records the measurements in Google Sheets, updates a ThingSpeak IoT dashboard, and, when an alert condition persists, sends a Telegram notification.

Telegram supports text and voice-message delivery through its Bot API, while n8n has a native Telegram integration. n8n Documentation+1

The system therefore combines:

  • Wearable sensing

  • Edge computing

  • IoT communication

  • Cloud automation

  • AI-assisted anomaly interpretation

  • Persistent data logging

  • Visualization

  • Emergency notification


3. Overall system concept

                 ┌───────────────────────────┐
                 │       HUMAN SUBJECT        │
                 │   Wearable chest/arm unit  │
                 └─────────────┬─────────────┘
                               │
              ┌────────────────┴────────────────┐
              │                                 │
        ┌─────▼─────┐                     ┌─────▼─────┐
        │ ECG       │                     │ MAX30102  │
        │ AD8232    │                     │ HR / SpO₂  │
        └─────┬─────┘                     └─────┬─────┘
              │                                 │
              └──────────────┬──────────────────┘
                             │
                       Analog / I²C
                             │
                    ┌────────▼────────┐
                    │     ESP32       │
                    │ Edge Controller │
                    │ Filtering       │
                    │ Feature Extract │
                    │ Local Web UI     │
                    └────────┬────────┘
                             │
                         HTTPS/Wi-Fi
                             │
                    ┌────────▼────────┐
                    │     n8n         │
                    │ Webhook         │
                    │ Automation      │
                    │ AI Agent        │
                    └───┬────┬────┬───┘
                        │    │    │
          ┌─────────────┘    │    └──────────────┐
          │                  │                   │
    ┌─────▼─────┐      ┌─────▼─────┐      ┌─────▼─────┐
    │ Google    │      │ ThingSpeak │      │ Telegram   │
    │ Sheets    │      │ Dashboard  │      │ Bot        │
    └───────────┘      └────────────┘      └─────┬─────┘
                                                  │
                                           Text + Voice Alert
                                                  │
                                          ┌───────▼────────┐
                                          │ Family/Carer/  │
                                          │ Authorized User│
                                          └────────────────┘

4. What the system actually detects

A very important design decision is to distinguish:

Monitoring

The system measures:

  • ECG waveform

  • Heart rate

  • Pulse rate

  • Optional SpO₂

  • Signal quality

  • Motion/noise

  • Timestamp

  • Device status

  • Battery level if hardware supports it

Anomaly detection

The system can identify conditions such as:

  • Heart rate outside a configured personal range

  • Sustained tachycardia-like pattern

  • Sustained bradycardia-like pattern

  • Irregular pulse intervals

  • Excessive signal noise

  • Loss of ECG contact

  • Sudden change from baseline

  • Multiple abnormal indicators occurring together

It should NOT claim

Do not write:

"The device predicts heart attack."

Instead write:

"The system detects potentially abnormal physiological patterns and generates an emergency alert for human verification."

This distinction is extremely important for a student prototype.


5. Hardware required

Core hardware

Component Purpose
ESP32 DevKit Main IoT controller
AD8232 ECG module ECG acquisition
MAX30102 Heart rate / SpO₂
OLED 0.96" I²C Local display
Buzzer Local alert
Push button SOS / acknowledge
Li-ion battery Portable power
TP4056 or appropriate protected charger Battery charging
3.3 V regulator Stable supply
Jumper wires/PCB Connections
Chest electrodes ECG sensing

Optional:

  • MPU6050/MPU6886 for motion detection

  • GPS module for outdoor location

  • vibration motor

  • RTC

  • battery fuel gauge

  • enclosure

  • smartwatch/wrist strap

  • external emergency button


6. Why use both ECG and MAX30102?

The two sensors provide different information.

AD8232

Primarily provides the ECG electrical signal.

Heart electrical activity
       ↓
Electrodes
       ↓
AD8232
       ↓
Analog ECG waveform
       ↓
ESP32 ADC

MAX30102

Uses optical sensing.

LED illumination
       ↓
Blood/tissue
       ↓
Photodetector
       ↓
PPG waveform
       ↓
Heart-rate estimation

Using both gives the project a useful sensor-fusion architecture.

For example:

ECG HR = 102 BPM
PPG HR = 104 BPM

Difference = 2 BPM

→ sensor agreement = good

Whereas:

ECG HR = 75 BPM
PPG HR = 145 BPM

→ possible motion/contact artifact
→ don't immediately generate emergency alarm

That reduces false alarms.


7. ESP32 hardware architecture

                    ESP32
             ┌─────────────────┐
             │                 │
AD8232 OUT ──► GPIO34 / ADC    │
             │                 │
MAX30102 SDA ─► GPIO21         │
MAX30102 SCL ─► GPIO22         │
             │                 │
OLED SDA ─────► GPIO21         │
OLED SCL ─────► GPIO22         │
             │                 │
Buzzer ───────► GPIO25         │
             │                 │
SOS button ───► GPIO27         │
             │                 │
             │ Wi-Fi           │
             └────────┬────────┘
                      │
                   Internet

8. Example schematic

                         +----------------+
                         |     ESP32      |
                         |                |
                         | GPIO34 <-------+------ AD8232 OUTPUT
                         |                |
                         | GPIO21 <-------+------ MAX30102 SDA
                         | GPIO22 <-------+------ MAX30102 SCL
                         |                |
                         | GPIO21 <-------+------ OLED SDA
                         | GPIO22 <-------+------ OLED SCL
                         |                |
                         | GPIO25 --------+------ BUZZER
                         |                |
                         | GPIO27 <-------+------ SOS BUTTON
                         |                |
                         | 3V3 -----------+------ Sensor VCC
                         | GND -----------+------ Common GND
                         +----------------+

Important electrical note

Do not blindly connect a sensor output to an ESP32 pin without checking its voltage range and the exact board revision.

The ESP32 ADC is not a medical-grade acquisition system. For a real clinical device, you would need considerably more rigorous analog front-end design, isolation, filtering, calibration, EMC testing and regulatory validation.


9. Power architecture

For a wearable prototype:

       Li-ion Battery
             │
             ▼
       Protection/Charger
             │
             ▼
       Power Regulation
             │
      ┌──────┴──────┐
      │             │
    ESP32         Sensors
      │             │
      └──────┬──────┘
             │
          Ground

Avoid powering an exposed patient-connected circuit directly from unsafe mains supplies.

For early testing, it is safer to develop the sensing system on a bench before attaching electrodes to a person.


10. Software architecture

┌─────────────────────────────────────────────┐
│                DEVICE LAYER                 │
│                                             │
│ ESP32 + AD8232 + MAX30102 + OLED + Button  │
└──────────────────────┬──────────────────────┘
                       │
                       │ HTTPS JSON
                       ▼
┌─────────────────────────────────────────────┐
│              AUTOMATION LAYER               │
│                                             │
│ n8n Webhook                                 │
│      ↓                                      │
│ Data Validation                             │
│      ↓                                      │
│ Signal Quality                              │
│      ↓                                      │
│ Feature Analysis                            │
│      ↓                                      │
│ AI Agent                                    │
│      ↓                                      │
│ Decision Engine                             │
└───────┬──────────────┬──────────────┬───────┘
        │              │              │
        ▼              ▼              ▼
 Google Sheets     ThingSpeak      Telegram
        │              │              │
        ▼              ▼              ▼
 Historical       IoT graph       Text alert
 records          dashboard       + voice

n8n is designed to connect applications and APIs and includes built-in AI capabilities and integrations. n8n Documentation


11. Data packet

The ESP32 should transmit structured JSON.

Example:

{
  "device_id": "CARDIO_001",
  "timestamp": 1727890000,
  "heart_rate": 82,
  "spo2": 98,
  "ecg": 2048,
  "signal_quality": 94,
  "motion": 0,
  "battery": 87,
  "sos": false
}

For a real ECG waveform, don't send only one ECG sample.

Instead you could periodically send:

{
  "device_id": "CARDIO_001",
  "heart_rate": 82,
  "spo2": 98,
  "ecg_samples": [
    2012,
    2025,
    2040,
    2061,
    2074,
    2060
  ]
}

For production-scale streaming, MQTT/WebSockets or a dedicated telemetry service may be preferable to sending every raw ADC sample through ordinary HTTP.


12. ESP32 firmware architecture

The ESP32 program should have these logical tasks:

setup()
 │
 ├── Initialize Serial
 ├── Initialize sensors
 ├── Initialize OLED
 ├── Initialize GPIO
 ├── Connect Wi-Fi
 └── Start web server
       │
loop()
 │
 ├── Read ECG
 ├── Read MAX30102
 ├── Calculate HR
 ├── Calculate SpO₂
 ├── Calculate signal quality
 ├── Detect local anomaly
 ├── Update OLED
 ├── Send cloud packet
 └── Repeat

ESP32's Arduino environment provides Wi-Fi functionality, and Espressif also documents HTTP/HTTPS client support. Espressif Systems+1


13. Example ESP32 firmware

The following is a prototype framework. Sensor-library APIs can vary by module/library, so test each sensor independently first.

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

// ---------------------------
// Wi-Fi
// ---------------------------
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";

// n8n webhook
const char* N8N_WEBHOOK =
    "https://YOUR-N8N-DOMAIN/webhook/cardiac-data";

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

const char* THINGSPEAK_KEY =
    "YOUR_THINGSPEAK_WRITE_KEY";

// ---------------------------
// Pins
// ---------------------------
#define ECG_PIN       34
#define BUZZER_PIN    25
#define SOS_BUTTON    27

// ---------------------------
// Device
// ---------------------------
String deviceID = "CARDIO_001";

unsigned long lastUpload = 0;
const unsigned long uploadInterval = 15000;

// Example values
float heartRate = 0;
float spo2 = 0;
int ecgValue = 0;
int signalQuality = 0;
int battery = 90;

bool sos = false;

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

  Serial.print("Connecting WiFi");

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

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

// ---------------------------
// Read ECG
// ---------------------------
int readECG()
{
  return analogRead(ECG_PIN);
}

// ---------------------------
// Basic local anomaly logic
// ---------------------------
bool localAnomaly()
{
  if (heartRate <= 0)
    return false;

  if (heartRate < 45 || heartRate > 130)
    return true;

  if (signalQuality < 40)
    return false;

  return false;
}

// ---------------------------
// Send to n8n
// ---------------------------
void sendToN8N()
{
  if (WiFi.status() != WL_CONNECTED)
    return;

  HTTPClient http;

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

  String json = "{";

  json += "\"device_id\":\"" + deviceID + "\",";
  json += "\"timestamp\":" + String(millis()) + ",";
  json += "\"heart_rate\":" + String(heartRate, 1) + ",";
  json += "\"spo2\":" + String(spo2, 1) + ",";
  json += "\"ecg\":" + String(ecgValue) + ",";
  json += "\"signal_quality\":" + String(signalQuality) + ",";
  json += "\"battery\":" + String(battery) + ",";
  json += "\"sos\":" + String(sos ? "true" : "false");

  json += "}";

  int response = http.POST(json);

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

  http.end();
}

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

  HTTPClient http;

  String url = String(THINGSPEAK_URL) +
               "?api_key=" + THINGSPEAK_KEY +
               "&field1=" + String(heartRate) +
               "&field2=" + String(spo2) +
               "&field3=" + String(signalQuality) +
               "&field4=" + String(battery);

  http.begin(url);

  int response = http.GET();

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

  http.end();
}

// ---------------------------
// Setup
// ---------------------------
void setup()
{
  Serial.begin(115200);

  pinMode(ECG_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);

  pinMode(SOS_BUTTON, INPUT_PULLUP);

  Wire.begin();

  connectWiFi();
}

// ---------------------------
// Main loop
// ---------------------------
void loop()
{
  ecgValue = readECG();

  // Replace with actual MAX30102 processing
  heartRate = 82;
  spo2 = 98;

  signalQuality = 90;

  sos = digitalRead(SOS_BUTTON) == LOW;

  bool anomaly = localAnomaly();

  if (anomaly || sos)
  {
    digitalWrite(BUZZER_PIN, HIGH);
  }
  else
  {
    digitalWrite(BUZZER_PIN, LOW);
  }

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

    sendToN8N();
    sendToThingSpeak();
  }

  delay(10);
}

For a serious implementation, replace the placeholder HR/SpO₂ calculation with the appropriate sensor library and implement filtering/beat detection rather than hard-coded values.

ThingSpeak accepts channel updates using HTTP GET or POST and supports multiple fields in one update. MathWorks


14. ThingSpeak configuration

Create a ThingSpeak channel.

Use:

Field Data
Field 1 Heart Rate
Field 2 SpO₂
Field 3 Signal Quality
Field 4 Battery
Field 5 Anomaly Score
Field 6 ECG status
Field 7 Motion
Field 8 Alert State

Example:

ThingSpeak
│
├── Field 1 → HR
├── Field 2 → SpO2
├── Field 3 → Signal Quality
├── Field 4 → Battery
├── Field 5 → Anomaly Score
├── Field 6 → ECG Status
├── Field 7 → Motion
└── Field 8 → Alert

ThingSpeak's REST API provides an /update endpoint and channel write API key for this purpose. MathWorks


15. n8n workflow

This is the heart of the project.

Main workflow

                 ┌───────────────┐
                 │ ESP32 Device  │
                 └───────┬───────┘
                         │
                         ▼
                 ┌───────────────┐
                 │ Webhook       │
                 └───────┬───────┘
                         │
                         ▼
                 ┌───────────────┐
                 │ Validate JSON  │
                 └───────┬───────┘
                         │
                         ▼
                 ┌───────────────┐
                 │ Code Node      │
                 │ Feature        │
                 │ Extraction     │
                 └───────┬───────┘
                         │
                  ┌──────▼───────┐
                  │ Quality OK?  │
                  └───┬──────┬───┘
                     NO      YES
                      │        │
                      ▼        ▼
                  Log only   AI Agent
                               │
                     ┌─────────┴─────────┐
                     │                   │
                     ▼                   ▼
                Google Sheets       Decision Node
                                         │
                               ┌─────────┴─────────┐
                               │                   │
                             NORMAL              ALERT
                               │                   │
                               ▼                   ▼
                         ThingSpeak         Telegram Text
                                                   │
                                                   ▼
                                                TTS
                                                   │
                                                   ▼
                                            Telegram Voice

16. n8n Webhook

Create:

Webhook

Method:

POST

Path:

cardiac-data

Your ESP32 therefore sends:

POST
https://YOUR-N8N-SERVER/webhook/cardiac-data

Body:

{
  "device_id": "CARDIO_001",
  "heart_rate": 82,
  "spo2": 98,
  "ecg": 2048,
  "signal_quality": 93,
  "battery": 88,
  "sos": false
}

17. n8n validation node

Add a Code node.

Example:

const d = $json;

const result = {
  device_id: d.device_id ?? "UNKNOWN",
  heart_rate: Number(d.heart_rate ?? 0),
  spo2: Number(d.spo2 ?? 0),
  ecg: Number(d.ecg ?? 0),
  signal_quality: Number(d.signal_quality ?? 0),
  battery: Number(d.battery ?? 0),
  sos: Boolean(d.sos),
  timestamp: new Date().toISOString()
};

result.valid =
  result.heart_rate >= 0 &&
  result.spo2 >= 0 &&
  result.spo2 <= 100 &&
  result.signal_quality >= 0 &&
  result.signal_quality <= 100;

return [
  {
    json: result
  }
];

18. Feature extraction

A second Code node can generate a preliminary risk state.

const d = $json;

let score = 0;
let reasons = [];

if (d.sos === true) {
  score += 100;
  reasons.push("Manual SOS activated");
}

if (d.heart_rate > 130) {
  score += 30;
  reasons.push("Heart rate above configured threshold");
}

if (d.heart_rate < 45 && d.heart_rate > 0) {
  score += 30;
  reasons.push("Heart rate below configured threshold");
}

if (d.spo2 > 0 && d.spo2 < 92) {
  score += 35;
  reasons.push("Low SpO2 reading");
}

if (d.signal_quality < 40) {
  score -= 25;
  reasons.push("Poor signal quality");
}

let state = "NORMAL";

if (score >= 60)
  state = "HIGH_ATTENTION";
else if (score >= 30)
  state = "REVIEW";

return [
  {
    json: {
      ...d,
      anomaly_score: score,
      state,
      reasons
    }
  }
];

These numbers are engineering-demo thresholds, not medical diagnostic thresholds. For a real system, thresholds should be derived and validated for the intended population and sensor characteristics.


19. The AI Agent

Now comes the agentic AI portion.

Instead of asking AI:

"Does this person have a heart attack?"

use:

"Interpret the telemetry and determine whether the system should continue monitoring, request human review, or issue a high-priority alert."

This is substantially safer.


20. AI Agent input

Give the AI something like:

{
  "heart_rate": 145,
  "spo2": 91,
  "signal_quality": 92,
  "motion": 0,
  "anomaly_score": 75,
  "state": "HIGH_ATTENTION"
}

21. AI Agent system prompt

Use a tightly constrained prompt.

You are the monitoring-assistance agent for an experimental wearable
cardiac monitoring system.

You are NOT a doctor and must not diagnose disease.

Your job is to interpret sensor telemetry and determine an automation
state.

Possible states:

NORMAL
REVIEW
HIGH_ATTENTION
SENSOR_ERROR

Rules:

1. Treat poor signal quality as a possible measurement artifact.
2. Never diagnose heart attack, arrhythmia, stroke, or other disease.
3. Never claim certainty about a medical condition.
4. If a manual SOS is active, classify the event as HIGH_ATTENTION.
5. If multiple physiological indicators are abnormal and signal quality
   is good, classify as HIGH_ATTENTION.
6. If the data is contradictory or unreliable, classify as SENSOR_ERROR.
7. If only one mildly abnormal parameter exists, use REVIEW.
8. Generate a short explanation.
9. Generate an alert message suitable for Telegram.
10. The alert must tell the recipient to verify the person's condition
    and seek appropriate emergency medical help when warranted.

Return ONLY valid JSON:

{
  "state": "...",
  "confidence": 0-1,
  "reason": "...",
  "telegram_message": "...",
  "voice_message": "..."
}

22. Example AI output

{
  "state": "HIGH_ATTENTION",
  "confidence": 0.91,
  "reason": "Multiple abnormal measurements were detected while signal quality was good.",
  "telegram_message": "High-attention event detected on CARDIO_001. Please check the person immediately and seek appropriate emergency medical assistance if symptoms are present.",
  "voice_message": "Attention. A high-priority monitoring event has been detected. Please check the person immediately and seek appropriate emergency medical assistance if needed."
}

Notice that the AI doesn't say:

"The patient is having a heart attack."

That's intentional.


23. Agentic architecture

Your project can demonstrate genuine agentic behavior by giving the AI controlled tools.

                     ┌─────────────────┐
                     │     AI AGENT    │
                     └────────┬────────┘
                              │
              ┌───────────────┼────────────────┐
              │               │                │
              ▼               ▼                ▼
       Sensor History     Device Status    Alert Tool
              │               │                │
              ▼               ▼                ▼
       Google Sheets      n8n Data       Telegram

For example:

Tool 1

get_recent_sensor_history()

Tool 2

get_device_status()

Tool 3

send_alert()

Tool 4

log_incident()

The AI can then decide which tool to invoke according to the workflow's fixed safety rules.


24. Google Sheets database

Create a spreadsheet:

Cardiac IoT Monitoring

Columns:

Timestamp
Device_ID
Heart_Rate
SpO2
ECG
Signal_Quality
Motion
Battery
Anomaly_Score
AI_State
AI_Confidence
Reason
Alert_Sent

Example:

Timestamp HR SpO₂ Quality Score State
10:00 78 98 96 0 NORMAL
10:01 84 97 95 0 NORMAL
10:02 141 95 93 30 REVIEW
10:03 148 91 94 65 HIGH_ATTENTION

n8n's Google integrations can be used to connect workflow data with Google Sheets; n8n also supports expression-based mapping between nodes. n8n Documentation+1


25. Telegram alert architecture

AI Agent
   │
   ├──────────────► Telegram text
   │
   └──────────────► Text-to-Speech
                         │
                         ▼
                     Audio file
                         │
                         ▼
                  Telegram voice

n8n provides a Telegram node with messaging and audio-related operations. n8n Documentation

Telegram's Bot API also supports sendVoice for voice messages. Telegram


26. Telegram text example

🚨 CARDIAC MONITORING ALERT

Device: CARDIO_001

Heart Rate: 148 BPM
SpO₂: 91%
Signal Quality: 94%

Status: HIGH ATTENTION

Multiple abnormal measurements were detected.

Please check the person immediately.
If symptoms are present or the situation appears
life-threatening, contact appropriate emergency
medical services.

This is an automated monitoring alert and is not
a medical diagnosis.

27. Telegram voice alert

The text-to-speech engine generates:

"Attention. A high-priority monitoring event has been detected.
Please check the person immediately and seek appropriate emergency
medical assistance if necessary."

Then n8n passes the resulting audio to Telegram.

Telegram's current Bot API documentation specifies sendVoice for playable voice messages and supports audio uploads/URLs subject to its file rules. Telegram


28. Voice-alert n8n workflow

             AI Agent
                 │
                 ▼
          voice_message
                 │
                 ▼
        ┌─────────────────┐
        │ Text-to-Speech  │
        └────────┬────────┘
                 │
                 ▼
          audio/OGG file
                 │
                 ▼
        ┌─────────────────┐
        │ Telegram Node   │
        │ Send Voice      │
        └────────┬────────┘
                 │
                 ▼
             Recipient

For a production deployment, use an authenticated TTS provider and avoid exposing its API key inside the ESP32 firmware.


29. Alert decision tree

This is one of the most important diagrams for your documentation.

                       Sensor Data
                           │
                           ▼
                  Is data valid?
                    /          \
                  NO            YES
                  │              │
                  ▼              ▼
             SENSOR ERROR   Signal quality?
                              /       \
                            BAD        GOOD
                            │           │
                            ▼           ▼
                     Recheck sensor   Analyze data
                                        │
                              ┌─────────┴─────────┐
                              │                   │
                           Normal             Abnormal
                              │                   │
                              ▼                   ▼
                         Log data          Persistent?
                                              /    \
                                            NO      YES
                                            │         │
                                            ▼         ▼
                                         REVIEW   HIGH ATTENTION
                                                      │
                                                      ▼
                                               Telegram Alert

30. Manual SOS button

You should also include a physical emergency button.

             SOS button
                  │
                  ▼
                ESP32
                  │
                  ▼
              n8n Webhook
                  │
                  ▼
              AI Agent
                  │
                  ▼
          HIGH_ATTENTION
             /        \
            ▼          ▼
        Telegram      Sheets
        Text/Voice    Log

This is actually an important feature because a person can request assistance even when sensor measurements appear normal.


31. Local ESP32 web page

The ESP32 can also host a basic webpage.

ESP32 can operate as a Wi-Fi station and can serve HTTP content; Espressif documents the Wi-Fi/AP functionality and networking APIs. Espressif Systems+1

Example UI:

┌──────────────────────────────────────────┐
│       CARDIO AI MONITOR                  │
├──────────────────────────────────────────┤
│                                          │
│  ❤️ Heart Rate        82 BPM             │
│                                          │
│  🫁 SpO₂              98 %               │
│                                          │
│  📈 ECG               █▂▃▆▇▅▃▂           │
│                                          │
│  📶 Signal            94 %               │
│                                          │
│  🔋 Battery           87 %               │
│                                          │
│  Status: 🟢 NORMAL                       │
│                                          │
│          [ EMERGENCY SOS ]               │
│                                          │
└──────────────────────────────────────────┘

32. Example ESP32 HTML

String createWebPage()
{
  String html = R"rawliteral(

<!DOCTYPE html>
<html>
<head>
<meta name="viewport"
      content="width=device-width,initial-scale=1">

<title>Cardio AI Monitor</title>

<style>

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

.card {
  background: #1d2b36;
  margin: 15px;
  padding: 20px;
  border-radius: 15px;
}

.value {
  font-size: 32px;
  color: #00e676;
}

button {
  background: #e53935;
  color: white;
  border: none;
  padding: 18px;
  border-radius: 10px;
  font-size: 20px;
}

</style>

</head>

<body>

<h1>❤️ Cardio AI Monitor</h1>

<div class="card">
<h2>Heart Rate</h2>
<div class="value">82 BPM</div>
</div>

<div class="card">
<h2>SpO₂</h2>
<div class="value">98 %</div>
</div>

<div class="card">
<h2>Signal Quality</h2>
<div class="value">94 %</div>
</div>

<div class="card">
<h2>Status</h2>
<div class="value">NORMAL</div>
</div>

<button onclick="location.href='/sos'">
EMERGENCY SOS
</button>

</body>
</html>

)rawliteral";

  return html;
}

33. Complete cloud architecture

                    INTERNET
                        │
             ┌──────────┴───────────┐
             │                      │
             ▼                      ▼
        ThingSpeak                 n8n
             │                      │
             │              ┌───────┴────────┐
             │              │                │
             │              ▼                ▼
             │         Google Sheets      AI Agent
             │                               │
             │                     ┌─────────┼──────────┐
             │                     │         │          │
             │                     ▼         ▼          ▼
             │                  Rules     History    Alert
             │                                │          │
             │                                │          ▼
             │                                │       Telegram
             │                                │
             ▼                                ▼
        IoT Dashboard                  Voice Notification

34. ThingSpeak dashboard

Configure widgets such as:

Chart 1

Heart Rate vs Time

Chart 2

SpO₂ vs Time

Chart 3

Signal Quality

Chart 4

Anomaly Score

Numeric display

Current HR: 82 BPM
Current SpO₂: 98%
Status: NORMAL

ThingSpeak supports reading channel feeds through its REST interface as well, allowing external dashboards or applications to retrieve historical channel data. MathWorks


35. AI anomaly scoring

You can create a simple first version without machine learning.

For example:

Anomaly Score =
    HR abnormality
  + SpO₂ abnormality
  + HR trend change
  + signal consistency
  + motion compensation
  + persistence
  + manual SOS

Example:

HR abnormality       = 30
SpO₂ abnormality     = 25
Trend                = 10
Signal quality       = 0
Persistence           = 15
SOS                   = 0
--------------------------------
Total                 = 80

Then:

0–19       NORMAL
20–39      REVIEW
40–69      HIGH ATTENTION
70–100     HIGH ATTENTION

Again, these are prototype engineering categories, not clinically validated risk scores.


36. Better approach: temporal analysis

Don't make an alert based on a single sample.

Instead:

Sample 1
   ↓
Sample 2
   ↓
Sample 3
   ↓
Sample 4
   ↓
Sample 5
   ↓
Persistent abnormality?

For example:

HR:
82
84
145
149
151
147

This is more meaningful for an anomaly detector than:

82
84
145
80
83
81

The second pattern may simply be a transient artifact or activity-related change.


37. Moving-average algorithm

A simple algorithm:

float movingAverage(float values[], int n)
{
  float total = 0;

  for (int i = 0; i < n; i++)
  {
    total += values[i];
  }

  return total / n;
}

Example:

Window = 5

HR:
140
143
147
145
149

Average:
144.8 BPM

38. Persistence detector

int abnormalCount = 0;

if (heartRate > 130)
{
  abnormalCount++;
}
else
{
  abnormalCount = 0;
}

if (abnormalCount >= 5)
{
  // Persistent abnormal condition
}

A real implementation should use elapsed time rather than simply assuming each loop iteration equals one physiological sample.


39. ECG processing pipeline

For the ECG signal:

Raw ECG
  │
  ▼
DC removal
  │
  ▼
Band-pass filtering
  │
  ▼
Noise suppression
  │
  ▼
R-peak detection
  │
  ▼
RR intervals
  │
  ▼
Heart rate
  │
  ▼
Irregularity features

A more advanced project can implement a Pan-Tompkins-like QRS detection pipeline.


40. ECG feature extraction

Potential features:

R-R interval
Mean RR
SDNN
RMSSD
Heart rate
QRS amplitude
Signal quality
Baseline wander
Peak-to-peak amplitude

For an academic prototype, focus initially on:

R-peak detection
       ↓
RR interval
       ↓
Heart rate
       ↓
variation analysis

Don't claim that these features alone diagnose a specific cardiac disease.


41. Machine-learning extension

After building the rule-based prototype, you can add ML.

Architecture:

ECG
 │
 ▼
Filtering
 │
 ▼
Segmentation
 │
 ▼
Feature extraction
 │
 ├── HR
 ├── RR
 ├── RR variability
 ├── ECG morphology features
 └── signal quality
       │
       ▼
   ML classifier
       │
       ▼
Normal / Anomalous

Possible models for research:

  • Logistic regression

  • Random Forest

  • XGBoost

  • SVM

  • 1-D CNN

  • LSTM

  • Autoencoder

For a first project, a Random Forest or anomaly-detection model is much easier to validate than a deep neural network.


42. Recommended AI architecture

Instead of putting a large model directly on the ESP32:

ESP32
 │
 │ raw/processed features
 ▼
n8n
 │
 ▼
AI service
 │
 ▼
structured decision
 │
 ├── Sheets
 ├── ThingSpeak
 └── Telegram

The ESP32 performs:

  • sensor acquisition

  • basic filtering

  • local threshold checks

  • connectivity

The cloud performs:

  • history analysis

  • AI interpretation

  • automation

  • notification


43. Edge + cloud AI

                EDGE AI
             ┌───────────┐
             │   ESP32   │
             │           │
             │ Fast      │
             │ checks    │
             └─────┬─────┘
                   │
                   ▼
              CLOUD AI
             ┌───────────┐
             │   n8n     │
             │ + AI      │
             │ + history │
             └─────┬─────┘
                   │
                   ▼
                ACTION

This gives the system a strong edge/cloud hybrid architecture.


44. Failure-handling design

A good final-year project should demonstrate that it handles failures.

Wi-Fi failure

Wi-Fi disconnected
       ↓
Store recent data locally
       ↓
Attempt reconnection
       ↓
Connection restored
       ↓
Upload buffered data

n8n unavailable

HTTP failure
     ↓
Retry
     ↓
Retry
     ↓
Local alert if required
     ↓
Log failure

Sensor disconnected

Sensor signal invalid
        ↓
SENSOR_ERROR
        ↓
No medical alert generated
        ↓
Notify user:
"Check sensor placement"

AI unavailable

AI API unavailable
       ↓
Fallback deterministic rules
       ↓
Continue monitoring
       ↓
Send basic alert if configured threshold

This fallback is very important.


45. Emergency-alert priority

Use three levels.

Level 0 — Normal

🟢 NORMAL

No notification.

Level 1 — Review

🟡 REVIEW

Potential abnormal measurement.
Continue monitoring.

Optional Telegram notification.

Level 2 — High attention

🔴 HIGH ATTENTION

Multiple abnormal indicators or manual SOS.

Trigger:

Telegram text
+
Telegram voice
+
Google Sheets incident log
+
ThingSpeak alert state
+
local buzzer

46. Anti-false-alarm mechanism

This is an excellent feature to mention during your project presentation.

Use:

Abnormal reading
       ↓
Check signal quality
       ↓
Check motion
       ↓
Check second sensor
       ↓
Check persistence
       ↓
Check previous history
       ↓
Generate alert

For example:

HR = 160
Signal quality = 20%

→ likely unreliable

No immediate high-priority alert.

Where:

HR = 160
Signal quality = 95%
PPG = 158
No movement
Persistent 30 seconds

→ high-attention event

This is a much better engineering architecture.


47. Security architecture

Do not hard-code everything publicly.

Bad:

const char* BOT_TOKEN =
"123456789:ABC...";

If the source code is published, the token is compromised.

Instead use:

ESP32
  │
  └── HTTPS
       │
       ▼
     n8n
       │
       ├── Telegram credentials
       ├── AI API credentials
       ├── Google credentials
       └── ThingSpeak credentials

The secrets remain on the server.

ESP32 should ideally use HTTPS rather than unencrypted HTTP when sending sensitive telemetry; Espressif documents HTTPS support in its HTTP client stack. Espressif Systems


48. Credential architecture

                    n8n Credentials
                         │
          ┌──────────────┼──────────────┐
          │              │              │
          ▼              ▼              ▼
      Telegram        Google          AI API
        Token         OAuth/API       Key

ESP32 only knows:

Wi-Fi credential
n8n endpoint
device authentication secret

Even better:

ESP32
  ↓
device_id
device_secret
timestamp
signature
sensor data

n8n verifies the request before accepting it.


49. Request authentication

A more secure packet:

{
  "device_id": "CARDIO_001",
  "timestamp": 1727890000,
  "heart_rate": 82,
  "spo2": 98,
  "signature": "..."
}

The signature could be calculated using HMAC.

Conceptually:

HMAC-SHA256(
    timestamp + device_id + sensor_data,
    DEVICE_SECRET
)

n8n verifies:

signature received
        ↓
calculate expected signature
        ↓
compare
        ↓
valid?

50. Full n8n workflow

A practical workflow could contain these nodes:

1. Webhook
      ↓
2. Validate Request
      ↓
3. Normalize Data
      ↓
4. Code – Feature Extraction
      ↓
5. Google Sheets – Log Raw Data
      ↓
6. ThingSpeak – Update Dashboard
      ↓
7. IF – Manual SOS?
      │
      ├── YES ────────────────┐
      │                       │
      ▼                       ▼
8. AI Agent              High Attention
                              │
                              ▼
                         Telegram Text
                              │
                              ▼
                         TTS Service
                              │
                              ▼
                         Telegram Voice
                              │
                              ▼
                         Incident Log

51. AI-agent workflow with historical data

An advanced version:

Current data
     │
     ▼
AI Agent
     │
     ├────────► Query recent Google Sheet data
     │
     ├────────► Check ThingSpeak history
     │
     ├────────► Analyze trend
     │
     └────────► Decide state
                    │
                    ▼
               Action Tool

Example:

Current HR = 125

By itself this may not be very meaningful.

But the agent sees:

10 minutes ago: 72
8 minutes ago: 80
6 minutes ago: 92
4 minutes ago: 108
2 minutes ago: 119
Now: 125

It can describe the trend without diagnosing the cause.


52. Dashboard architecture

You can create three dashboards.

Dashboard 1 — Device

ESP32 local web server

Shows:

  • live sensor status

  • current readings

  • Wi-Fi

  • battery

  • SOS

Dashboard 2 — ThingSpeak

Shows:

  • historical graphs

  • HR

  • SpO₂

  • anomaly score

  • device status

Dashboard 3 — Google Sheets

Shows:

  • event history

  • alert history

  • AI decisions

  • timestamps


53. End-to-end data flow

       PERSON
         │
         ▼
    ECG + PPG
         │
         ▼
       ESP32
         │
         ├──────────────► OLED
         │
         ▼
       HTTPS
         │
         ▼
       n8n
         │
         ├──────► Google Sheets
         │
         ├──────► ThingSpeak
         │
         ▼
      AI Agent
         │
         ▼
    Risk/State Engine
         │
    ┌────┴─────┐
    │          │
 NORMAL      ALERT
    │          │
    ▼          ▼
  Log       Telegram
             │
       ┌─────┴─────┐
       ▼           ▼
     Text        Voice

54. Sequence diagram

User        ESP32       n8n       AI       Sheets   ThingSpeak   Telegram
 │            │          │         │          │           │           │
 │            │ ECG      │         │          │           │           │
 │            │◄──────── │         │          │           │           │
 │            │          │         │          │           │           │
 │            │ POST     │         │          │           │           │
 │            ├─────────►│         │          │           │           │
 │            │          │         │          │           │           │
 │            │          │ Log     │          │           │           │
 │            │          ├──────────────────►│           │           │
 │            │          │         │          │           │           │
 │            │          │ Update  │          │           │           │
 │            │          ├──────────────────────────────►│           │
 │            │          │         │          │           │           │
 │            │          │ Analyze │          │           │           │
 │            │          ├────────►│          │           │           │
 │            │          │         │          │           │           │
 │            │          │         │ Decision │           │           │
 │            │          │◄────────┤          │           │           │
 │            │          │         │          │           │           │
 │            │          │ Alert   │          │           │           │
 │            │          ├──────────────────────────────────────────►│
 │            │          │         │          │           │           │
 │            │          │         │          │           │     Voice │
 │            │          ├──────────────────────────────────────────►│
 │            │          │         │          │           │           │
 │◄──────────────────────────────────────────────────────────────────│

55. User interaction sequence

Normal

User wears device
       ↓
Sensors acquire data
       ↓
ESP32 processes
       ↓
n8n receives
       ↓
Data logged
       ↓
Dashboard updated
       ↓
No alert

Abnormal

Abnormal pattern
       ↓
ESP32
       ↓
n8n
       ↓
Quality check
       ↓
AI/rules
       ↓
HIGH ATTENTION
       ↓
Telegram
       ↓
Text + Voice
       ↓
Caregiver checks person

56. SOS interaction

User presses SOS
       ↓
ESP32 detects button
       ↓
Immediate local buzzer
       ↓
HTTP request
       ↓
n8n
       ↓
HIGH ATTENTION
       ↓
Telegram
       ↓
Voice message

The SOS path should not depend on an AI model to decide whether the person deserves help. The AI can format/contextualize the event, but the explicit manual SOS should take priority.


57. Testing plan

You need systematic testing.

Test 1 — Wi-Fi

Expected:

ESP32 connects
IP displayed

Test 2 — ECG

Check:

ECG signal present
No electrode → poor signal
Electrode attached → waveform

Test 3 — PPG

Check:

Finger absent → invalid
Finger present → pulse waveform

Test 4 — ThingSpeak

Send:

HR = 80
SpO2 = 98

Verify graph.

Test 5 — n8n

Send sample JSON using Postman/curl.

curl -X POST \
-H "Content-Type: application/json" \
-d '{"device_id":"TEST01","heart_rate":82,"spo2":98,"signal_quality":95,"sos":false}' \
https://YOUR-N8N/webhook/cardiac-data

Test 6 — Telegram

Generate a test alert.

Test 7 — Voice

Verify:

AI message
   ↓
TTS
   ↓
Telegram voice

Test 8 — SOS

Press button.

Expected:

Buzzer
+
n8n event
+
Telegram text
+
Telegram voice
+
Google Sheets record

58. Test cases table

Test Input Expected
Normal HR 75 BPM NORMAL
Mildly abnormal 120 BPM REVIEW
Persistent high HR 145 BPM HIGH ATTENTION
Low signal Quality 15% SENSOR ERROR/RECHECK
SOS Button pressed HIGH ATTENTION
Wi-Fi loss Disconnect router Local operation/reconnect
n8n failure Server unavailable Retry/fallback
Sensor disconnected Invalid ECG SENSOR ERROR
Low battery <20% Battery warning
AI unavailable API failure Rule-based fallback

59. False-positive testing

Don't only test successful cases.

Test:

Hand movement
Walking
Running
Loose electrode
Sweating
Poor electrode contact
Sensor removed
Wi-Fi interruption
Battery low
Rapid movement

Your report should measure:

False alarms
Missed alerts
Sensor failures
Network failures
AI failures

60. Performance metrics

You can calculate:

Alert latency

Alert latency =
Telegram received time
-
sensor event time

Packet success rate

successful packets
------------------ × 100
sent packets

False alarm rate

false alerts
------------ × 100
total alerts

Sensor availability

valid readings
------------- × 100
total readings

61. Example project results table

Use actual measured values in your final report.

Metric Target
Sensor sampling 100–250 Hz ECG prototype
Cloud update 10–30 s
Dashboard update configurable
Alert delivery measure experimentally
Packet success >95% target
Signal-quality detection measure experimentally
Battery runtime measure experimentally

Do not present these as achieved results until you actually measure them.


62. Recommended project phases

Phase 1

ESP32 + ECG.

ESP32
 +
AD8232

Make sure the ECG waveform works.

Phase 2

Add:

MAX30102

Phase 3

Add OLED.

Phase 4

Add Wi-Fi.

Phase 5

Add n8n webhook.

Phase 6

Add ThingSpeak.

Phase 7

Add Google Sheets.

Phase 8

Add Telegram.

Phase 9

Add voice alert.

Phase 10

Add AI Agent.

Phase 11

Add historical/trend analysis.

Phase 12

Add security and fault handling.

This order prevents you from trying to debug the entire system simultaneously.


63. Suggested project folder

cardiac-ai-iot/
│
├── firmware/
│   ├── cardiac_monitor.ino
│   ├── sensors.h
│   ├── sensors.cpp
│   ├── wifi_manager.h
│   └── web_server.h
│
├── n8n/
│   ├── cardiac_monitor_workflow.json
│   └── ai_prompt.txt
│
├── dashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── docs/
│   ├── architecture.md
│   ├── hardware.md
│   ├── software.md
│   ├── testing.md
│   └── safety.md
│
└── README.md

64. Recommended final n8n workflow names

Create separate workflows rather than one enormous workflow.

Workflow 1

CARDIO_01_DATA_INGESTION

ESP32 → n8n → validation.

Workflow 2

CARDIO_02_ANALYSIS

Telemetry → anomaly analysis → AI.

Workflow 3

CARDIO_03_ALERT

AI decision → Telegram → voice.

Workflow 4

CARDIO_04_DATABASE

Data → Google Sheets.

Workflow 5

CARDIO_05_DASHBOARD

ThingSpeak updates.

This makes debugging much easier.


65. Advanced version: digital patient baseline

Instead of using the same thresholds for everyone:

User baseline
     │
     ├── resting HR
     ├── normal HR range
     ├── typical SpO₂
     ├── typical signal
     └── historical trend
              │
              ▼
       Personalized anomaly

For example:

Normal baseline:

HR = 65–85

Then:

Current = 110

The system considers the deviation from baseline rather than simply applying a generic threshold.

This should still be described as personalized anomaly detection, not individualized medical diagnosis.


66. Advanced agentic behavior

You can make the AI Agent perform:

1. Read current telemetry
2. Check sensor quality
3. Retrieve recent history
4. Compare with baseline
5. Identify trend
6. Determine state
7. Generate explanation
8. Log incident
9. Trigger notification
10. Wait for acknowledgement

Then:

Telegram
   │
   ▼
"Alert received?"
   │
   ├── YES → close incident
   │
   └── NO → escalation workflow

For a real safety-critical system, escalation should be based on explicit engineered rules rather than letting an LLM autonomously decide who to contact or whether emergency care is required.


67. Acknowledgement system

Telegram can have:

🚨 ALERT

[ACKNOWLEDGE]
[CHECK PERSON]
[FALSE ALARM]

Workflow:

Alert
 ↓
Telegram
 ↓
Wait
 ↓
Acknowledged?
 ├── YES → log acknowledgement
 └── NO  → escalation

This makes your project considerably more impressive as an agentic IoT automation system.


68. Complete system block diagram for your report

                         WEARABLE
┌─────────────────────────────────────────────────────┐
│                                                     │
│  ┌──────────┐      ┌───────────┐                   │
│  │ AD8232   │      │ MAX30102  │                   │
│  │ ECG      │      │ HR / SpO₂  │                   │
│  └────┬─────┘      └─────┬─────┘                   │
│       │                  │                          │
│       └──────────┬───────┘                          │
│                  ▼                                  │
│            ┌───────────┐                            │
│            │   ESP32   │                            │
│            │           │                            │
│            │ Filtering │                            │
│            │ Features  │                            │
│            │ Wi-Fi     │                            │
│            └─────┬─────┘                            │
│                  │                                  │
└──────────────────┼──────────────────────────────────┘
                   │ HTTPS
                   ▼
             ┌─────────────┐
             │ n8n Webhook │
             └──────┬──────┘
                    │
             ┌──────▼───────┐
             │ Data Quality │
             └──────┬───────┘
                    │
             ┌──────▼───────┐
             │ Feature      │
             │ Extraction   │
             └──────┬───────┘
                    │
             ┌──────▼───────┐
             │ AI Agent     │
             └──────┬───────┘
                    │
        ┌───────────┼────────────┐
        │           │            │
        ▼           ▼            ▼
   Google Sheets ThingSpeak  Decision
                                │
                       ┌────────┴─────────┐
                       │                  │
                       ▼                  ▼
                    NORMAL              ALERT
                                          │
                                  ┌───────┴───────┐
                                  │               │
                                  ▼               ▼
                              Telegram         TTS
                              Text             │
                                               ▼
                                            Telegram
                                             Voice

69. Schematic diagram for presentation

                         +----------------+
                         |    BATTERY     |
                         +-------+--------+
                                 |
                         +-------▼--------+
                         | POWER / CHARGE |
                         +-------+--------+
                                 |
                 +---------------▼----------------+
                 |              ESP32              |
                 |                                 |
                 | ADC <──── AD8232 ECG            |
                 |                                 |
                 | I2C <──── MAX30102              |
                 |                                 |
                 | I2C ────► OLED                  |
                 |                                 |
                 | GPIO ───► BUZZER                |
                 |                                 |
                 | GPIO <──── SOS                  |
                 |                                 |
                 | Wi-Fi ────────────────► Internet|
                 +---------------------------------+
                                             |
                                             ▼
                                           n8n
                                             |
                   +─────────────────────────┼──────────────────+
                   |                         |                  |
                   ▼                         ▼                  ▼
              Google Sheets            ThingSpeak          AI Agent
                                                               |
                                                               ▼
                                                           Telegram
                                                               |
                                                     +─────────┴────────┐
                                                     │                  │
                                                     ▼                  ▼
                                                    TEXT              VOICE

70. How to explain the project in a viva

Question: What is the main objective?

Answer:

The objective is to develop a wearable IoT prototype that continuously monitors physiological signals, identifies potentially abnormal patterns, and automatically communicates high-priority events through a cloud-based automation system.

Question: Why ESP32?

ESP32 provides integrated Wi-Fi, GPIO, ADC and I²C interfaces, making it suitable for a compact wearable IoT prototype. Espressif specifically documents ESP32 Wi-Fi support and networking capabilities. Espressif Systems+1

Question: Why n8n?

n8n acts as the orchestration layer connecting the device, AI processing, databases, dashboards and notification services.

Question: Why Telegram?

Telegram provides a convenient real-time notification channel, including text and voice messages through its Bot API. n8n Documentation+1

Question: Why ThingSpeak?

ThingSpeak provides a simple IoT-oriented cloud channel for storing and visualizing sensor telemetry through REST APIs. MathWorks+1

Question: Is the AI diagnosing heart disease?

No. The prototype identifies potentially abnormal telemetry and generates an alert for human verification. It is not intended to provide a clinical diagnosis.


71. Strong project novelty

Your project combines several technologies:

Wearable Sensors
      +
ESP32 Edge Computing
      +
IoT
      +
Cloud Automation
      +
AI Agent
      +
Historical Data
      +
ThingSpeak
      +
Google Sheets
      +
Telegram
      +
Voice Notification

The agentic automation is the key differentiator.

Instead of:

Sensor → Telegram

you have:

Sensor
  ↓
Edge processing
  ↓
Cloud
  ↓
Data validation
  ↓
Historical context
  ↓
AI reasoning
  ↓
Decision
  ↓
Automation
  ↓
Logging
  ↓
Notification
  ↓
Voice alert
  ↓
Acknowledgement

72. Suggested final project title variants

Academic

AI-Assisted Wearable Cardiac Monitoring and IoT Emergency Alert System Using ESP32 and n8n

More technical

Agentic IoT-Based Wearable Physiological Monitoring System Using ESP32, n8n, Telegram and ThingSpeak

More impressive

AI-Powered Edge-to-Cloud Wearable Cardiac Monitoring and Intelligent Emergency Notification System

Short

Agentic AI Cardiac IoT Wearable


73. Recommended final implementation

For the first working prototype, I recommend this exact stack:

HARDWARE
────────
ESP32 DevKit
AD8232 ECG
MAX30102
OLED
Buzzer
SOS button
Battery


FIRMWARE
────────
Arduino IDE
C/C++
ESP32 Wi-Fi
HTTPS
JSON


AUTOMATION
──────────
n8n
Webhook
Code nodes
AI Agent
Google Sheets
Telegram


CLOUD
─────
ThingSpeak


ALERT
─────
Telegram text
+
TTS
+
Telegram voice


WEB
───
ESP32 local dashboard
+
ThingSpeak dashboard

74. Development order

Don't build everything at once. Build it in this order:

STEP 1
ESP32 basic programming
        ↓
STEP 2
AD8232 ECG acquisition
        ↓
STEP 3
MAX30102 acquisition
        ↓
STEP 4
OLED display
        ↓
STEP 5
Local anomaly detection
        ↓
STEP 6
Wi-Fi
        ↓
STEP 7
ESP32 web page
        ↓
STEP 8
n8n webhook
        ↓
STEP 9
ThingSpeak
        ↓
STEP 10
Google Sheets
        ↓
STEP 11
Telegram text
        ↓
STEP 12
Telegram voice
        ↓
STEP 13
AI Agent
        ↓
STEP 14
Historical analysis
        ↓
STEP 15
SOS + acknowledgement
        ↓
STEP 16
Security
        ↓
STEP 17
Testing
        ↓
STEP 18
Final enclosure

75. Final architecture in one picture

                    ❤️ WEARABLE PERSON
                           │
              ┌────────────┴────────────┐
              │                         │
           AD8232                    MAX30102
              │                         │
              └────────────┬────────────┘
                           │
                      ┌────▼─────┐
                      │  ESP32   │
                      │ Edge AI  │
                      └────┬─────┘
                           │
                    HTTPS / JSON
                           │
                           ▼
                    ┌─────────────┐
                    │     n8n     │
                    │ Orchestrator│
                    └──────┬──────┘
                           │
                    Data validation
                           │
                    Feature extraction
                           │
                           ▼
                     ┌──────────┐
                     │ AI Agent │
                     └────┬─────┘
                          │
               ┌──────────┼───────────┐
               │          │           │
               ▼          ▼           ▼
           Sheets     ThingSpeak   Rule Engine
                                      │
                                      ▼
                                   ALERT?
                                  /      \
                                NO        YES
                                │          │
                                ▼          ▼
                              LOG      Telegram
                                        │
                                  ┌─────┴─────┐
                                  ▼           ▼
                                TEXT        VOICE
                                  │           │
                                  └─────┬─────┘
                                        ▼
                                  CAREGIVER
                                        │
                                        ▼
                                HUMAN VERIFICATION

This architecture gives you a complete edge IoT + cloud automation + AI-agent + dashboard + notification project while keeping the medical claims appropriately limited. Espressif's current documentation supports the ESP32 Wi-Fi/networking architecture used here, n8n documents its integration/automation model and Telegram node, and ThingSpeak documents the REST data-ingestion model. Espressif Systems+4

If this is for a final-year engineering project, the next practical deliverable would be to turn this architecture into a complete build package: exact ESP32 pin-by-pin wiring, library list, complete .ino firmware for AD8232 + MAX30102 + OLED, the n8n workflow node-by-node configuration, AI-agent JSON prompt, Google Sheets column mapping, ThingSpeak setup, Telegram Bot setup, TTS configuration, and a ready-to-import n8n workflow.

Project Summary

AI-Powered Wearable Cardiac Monitoring & Emergency Alert System is an experimental IoT prototype that combines ESP32 + ECG/PPG sensors + AI + n8n automation + Telegram + Google Sheets + ThingSpeak.

Core workflow

ECG + MAX30102
      ↓
     ESP32
      ↓
Signal processing
      ↓
Wi-Fi / HTTPS
      ↓
     n8n
      ↓
Data validation + anomaly analysis
      ↓
    AI Agent
      ↓
 ┌────┼──────────┐
 ↓    ↓          ↓
Sheets ThingSpeak Telegram
                  ↓
            Text + Voice Alert

Main hardware

  • ESP32 DevKit

  • AD8232 ECG sensor

  • MAX30102 heart-rate/SpO₂ sensor

  • OLED display

  • Buzzer

  • Emergency/SOS button

  • Battery and appropriate power circuitry

Main software

  • Arduino/C++ firmware

  • ESP32 Wi-Fi + HTTPS

  • n8n automation

  • AI Agent

  • Google Sheets

  • ThingSpeak

  • Telegram Bot

  • Text-to-Speech for voice alerts

  • ESP32 web dashboard

AI function

The AI should not diagnose heart disease. It evaluates sensor telemetry and historical trends to classify events such as:

NORMAL
REVIEW
HIGH ATTENTION
SENSOR ERROR

Poor signal quality, motion , sensor disagreement and persistence should be considered to reduce false alarms.

Emergency flow

Abnormal/persistent readings
          OR
      Manual SOS
          ↓
     ESP32 → n8n
          ↓
     Rule + AI analysis
          ↓
    HIGH ATTENTION
          ↓
 ┌────────┴────────┐
 ↓                 ↓
Telegram Text   Voice Alert
 ↓                 ↓
Caregiver checks the person

Data logging

Google Sheets stores:

  • Timestamp

  • Device ID

  • Heart rate

  • SpO₂

  • ECG information

  • Signal quality

  • Battery

  • Anomaly score

  • AI state

  • Alert status

ThingSpeak provides time-series IoT visualization.

Key project novelty

The important feature is the agentic IoT workflow:

Wearable sensing → edge processing → cloud automation → historical context → AI-assisted analysis → automated logging → Telegram text/voice notification.

Development order

  1. ESP32

  2. AD8232 ECG

  3. MAX30102

  4. OLED

  5. Local anomaly detection

  6. Wi-Fi/HTTPS

  7. ESP32 webpage

  8. n8n webhook

  9. ThingSpeak

  10. Google Sheets

  11. Telegram text

  12. Telegram voice

  13. AI Agent

  14. Historical analysis

  15. SOS/acknowledgement

  16. Security

  17. Testing

  18. Enclosure

Important: this is a research/educational prototype, not a clinically validated medical device. Alerts should prompt human verification and appropriate emergency care rather than claim a medical diagnosis.