Saturday, 22 August 2026

AI Posture Detection & Muscle Strain Monitoring System

AI Posture Detection & Muscle Strain Monitoring System

This project combines ESP32 + posture sensors + AI analysis + n8n automation + Telegram voice alerts + Google Sheets + ThingSpeak + an IoT webpage/dashboard into one agentic IoT system.

The system continuously monitors posture-related parameters, detects prolonged poor posture or abnormal movement patterns, sends the sensor data to an AI/automation layer, records the data in the cloud, and alerts the user through Telegram.

Important: This is a posture/ergonomics monitoring prototype, not a medical diagnostic device. “Muscle strain risk” should be interpreted as an estimated ergonomic-risk score, not a diagnosis.


1. Project Title

AI-Powered Posture Detection & Muscle Strain Risk Monitoring Using ESP32, n8n, AI Agent, Telegram Voice Alerts, Google Sheets and ThingSpeak

Short title

Agentic IoT Posture & Muscle Strain Monitoring System


2. Project Objective

The main objective is to develop a wearable/desk-mounted IoT system capable of:

  • Monitoring body posture in real time.
  • Measuring body inclination using an IMU.
  • Detecting prolonged forward bending/slouching.
  • Detecting sudden or abnormal movements.
  • Calculating a posture-risk score.
  • Sending sensor data through Wi-Fi.
  • Processing data using an n8n automation workflow.
  • Using an AI Agent to interpret the sensor information.
  • Sending Telegram notifications.
  • Generating Telegram voice/audio alerts for severe conditions.
  • Storing historical data in Google Sheets.
  • Publishing measurements to ThingSpeak.
  • Displaying information on an IoT web dashboard.
  • Maintaining a history of posture and risk events.
  • Automatically deciding whether an alert is necessary.

3. Overall System Architecture

                  ┌─────────────────────────┐
                  │       HUMAN USER        │
                  │                         │
                  │  Sitting / Standing     │
                  │  Working / Studying     │
                  └────────────┬────────────┘
                               │
                               ▼
                 ┌──────────────────────────┐
                 │       WEARABLE UNIT      │
                 │                          │
                 │ ESP32                    │
                 │ MPU6050 / MPU9250        │
                 │ Optional Flex Sensors    │
                 │ Optional Vibration Motor │
                 │ Buzzer / LED              │
                 └────────────┬─────────────┘
                              │
                        Wi-Fi / HTTP
                              │
                              ▼
                 ┌──────────────────────────┐
                 │        n8n SERVER        │
                 │                          │
                 │ Webhook                  │
                 │ Data Validation          │
                 │ Posture Calculation      │
                 │ AI Agent                 │
                 │ Decision Logic            │
                 └───────┬───────────┬──────┘
                         │           │
             ┌───────────┘           └────────────┐
             ▼                                    ▼
   ┌─────────────────┐                  ┌─────────────────┐
   │ Google Sheets   │                  │   ThingSpeak    │
   │                 │                  │                 │
   │ Historical Data │                  │ IoT Graphs      │
   │ Events          │                  │ Cloud Data      │
   └─────────────────┘                  └─────────────────┘
                         │
                         ▼
                 ┌──────────────────┐
                 │  Telegram Bot    │
                 │                  │
                 │ Text Alert       │
                 │ Voice Alert      │
                 └────────┬─────────┘
                          │
                          ▼
                 ┌──────────────────┐
                 │      USER        │
                 │                  │
                 │ 📱 Notification  │
                 │ 🔊 Voice Alert   │
                 └──────────────────┘

4. Core Concept

The ESP32 collects posture information.

For example:

Back angle = 27°
Head angle = 31°
Movement = Low
Duration = 18 minutes

The system converts this into something like:

Posture:
POOR

Risk:
HIGH

Reason:
Forward bending detected continuously for 18 minutes.

Recommendation:
Straighten your back and take a short movement break.

The AI agent can then decide:

Should I alert the user?

YES

The n8n workflow sends:

Telegram Text Alert
+
Telegram Voice Alert
+
Google Sheets Log
+
ThingSpeak Update

5. Hardware Requirements

Essential hardware

  • ESP32 development board
  • MPU6050 6-axis IMU
  • Jumper wires
  • Breadboard
  • USB cable
  • 5 V USB power supply or Li-ion battery
  • LED
  • 220 Ω resistor

Optional hardware

For a more advanced version:

  • MPU6050 #2
  • Flex sensor
  • Force sensor
  • Vibration motor
  • Buzzer
  • OLED display
  • MAX30102
  • GPS module
  • Battery management circuit

A two-IMU version is especially useful.

For example:

IMU 1 → Upper back / shoulder
IMU 2 → Head / neck

Then:

Back angle
     +
Neck angle
     +
Movement
     +
Duration
     ↓
Posture Risk

6. Recommended Hardware Placement

A simple prototype can use one MPU6050.

Place it approximately on the upper back:

              HEAD
               O
              /|\
             / |
               |
        ┌─────────────┐
        │   MPU6050   │
        │             │
        └─────────────┘
              BACK
               |
               |
              / \
             /   \

The sensor should be firmly attached to the body or chair/back support.

For a more advanced wearable:

       HEAD
        O
       /|\
      [IMU2] ← neck/head orientation
        |
        |
     [IMU1] ← upper-back orientation
        |
        |
       / \

7. MPU6050 to ESP32 Wiring

Typical I²C connection:

MPU6050 ESP32
VCC 3.3 V
GND GND
SDA GPIO 21
SCL GPIO 22

Optional interrupt:

MPU6050 ESP32
INT GPIO 19

Wiring diagram

             ESP32
        ┌──────────────┐
        │              │
3.3V ───┤ 3V3          │
GND ────┤ GND          │
        │              │
GPIO21 ─┤ SDA          │
GPIO22 ─┤ SCL          │
        │              │
GPIO2 ──┤ LED          │
        │              │
        └──────┬───────┘
               │
               │ I²C
               │
       ┌───────▼────────┐
       │    MPU6050     │
       │                │
       │ VCC ── 3.3V   │
       │ GND ── GND    │
       │ SDA ── GPIO21 │
       │ SCL ── GPIO22 │
       └────────────────┘

8. Optional Vibration Motor

A vibration motor should not be driven directly from an ESP32 GPIO.

Use a transistor/MOSFET driver.

ESP32 GPIO
    │
    R
    │
    ▼
  MOSFET
    │
    ├──────── Vibration Motor
    │
   GND

Motor supply
    │
    ▼
  Motor
    │
  MOSFET
    │
   GND

Add a flyback diode where appropriate for the motor configuration.

The vibration motor can provide a local warning:

Poor posture detected
        ↓
ESP32
        ↓
Vibration
        ↓
User corrects posture

9. Software Architecture

The software consists of five major layers.

┌──────────────────────────────┐
│  Layer 1 – Sensor            │
│  MPU6050 / ESP32              │
└──────────────┬───────────────┘
               ↓
┌──────────────────────────────┐
│  Layer 2 – Edge Processing   │
│  ESP32                       │
│  angle / motion calculation  │
└──────────────┬───────────────┘
               ↓
┌──────────────────────────────┐
│  Layer 3 – Automation        │
│  n8n                         │
└──────────────┬───────────────┘
               ↓
┌──────────────────────────────┐
│  Layer 4 – AI Agent          │
│  posture interpretation      │
└──────────────┬───────────────┘
               ↓
┌──────────────────────────────┐
│  Layer 5 – Cloud & Alerts    │
│ Telegram / Sheets /          │
│ ThingSpeak / Web dashboard   │
└──────────────────────────────┘

10. Data Flow

The complete data flow is:

MPU6050
   │
   ▼
ESP32
   │
   │ JSON over HTTP
   ▼
n8n Webhook
   │
   ▼
Data Validation
   │
   ▼
Posture/Risk Calculation
   │
   ▼
AI Agent
   │
   ├──────────────► Google Sheets
   │
   ├──────────────► ThingSpeak
   │
   └──────────────► Telegram
                           │
                           ├── Text
                           │
                           └── Voice

11. ESP32 Data Format

The ESP32 can send JSON like:

{
  "device_id": "POSTURE_ESP32_01",
  "timestamp": 1724350000,
  "back_angle": 28.5,
  "accel_x": 0.15,
  "accel_y": 0.32,
  "accel_z": 9.62,
  "gyro_x": 1.2,
  "gyro_y": 0.8,
  "gyro_z": 0.5,
  "movement": 0.42,
  "posture": "poor"
}

n8n receives this information.


12. Posture Detection Logic

A simple prototype can use thresholds.

Example:

Back angle < 10°
       ↓
Good posture

10°–20°
       ↓
Moderate

20°–30°
       ↓
Poor

>30°
       ↓
Severe forward bending

These values are only example engineering thresholds and should be calibrated for the sensor placement and use case.


13. Time-Based Risk

Angle alone is not enough.

For example:

Forward bend = 25°
Duration = 10 seconds

may not be particularly concerning.

But:

Forward bend = 25°
Duration = 45 minutes

is a different ergonomic situation.

Therefore:

Risk = Posture + Duration + Movement

A conceptual score:

Risk Score =
    Angle Risk
  + Duration Risk
  + Movement Risk

Example:

Angle Risk       = 45
Duration Risk    = 30
Movement Risk    = 10
                   ----
Total            = 85

Then:

0–30   LOW
31–60  MODERATE
61–80  HIGH
81–100 VERY HIGH

Again, these are prototype engineering values, not medical thresholds.


14. Example AI Agent Input

n8n can provide the AI agent with:

Device: POSTURE_ESP32_01

Back angle: 31 degrees
Duration in poor posture: 22 minutes
Movement score: 0.18
Previous alerts: 2
Current posture: POOR

The AI Agent could return:

{
  "risk_level": "HIGH",
  "should_alert": true,
  "message": "Poor posture has continued for 22 minutes.",
  "recommendation": "Straighten your back and take a short movement break.",
  "voice_alert": true
}

15. AI Agent Role

The AI Agent should not directly control everything without constraints.

Use deterministic rules for safety-critical decisions.

A good architecture is:

Raw sensor
    ↓
Rule-based validation
    ↓
Risk calculation
    ↓
AI interpretation
    ↓
Automation policy
    ↓
Notification

The AI is useful for:

  • Explaining the condition.
  • Generating natural-language recommendations.
  • Summarizing repeated events.
  • Identifying patterns.
  • Producing human-friendly notifications.

The threshold/risk engine should remain deterministic.


16. n8n Workflow

The n8n workflow can be designed like this:

             ┌──────────────┐
             │ Webhook       │
             │ ESP32 Input   │
             └──────┬───────┘
                    │
                    ▼
             ┌──────────────┐
             │ Validate JSON │
             └──────┬───────┘
                    │
                    ▼
             ┌──────────────┐
             │ Calculate     │
             │ Risk Score    │
             └──────┬───────┘
                    │
                    ▼
             ┌──────────────┐
             │ AI Agent      │
             └──────┬───────┘
                    │
            ┌───────┴─────────┐
            │                 │
            ▼                 ▼
      ┌──────────┐      ┌─────────────┐
      │ Sheets   │      │ ThingSpeak  │
      └──────────┘      └─────────────┘
            │
            ▼
       ┌──────────┐
       │ IF       │
       │ Alert?   │
       └────┬─────┘
            │
        YES │
            ▼
       ┌────────────┐
       │ Telegram   │
       │ Text       │
       └─────┬──────┘
             │
             ▼
       ┌────────────┐
       │ TTS        │
       │ Voice      │
       └─────┬──────┘
             │
             ▼
       ┌────────────┐
       │ Telegram   │
       │ Audio      │
       └────────────┘

17. n8n Webhook

Create an n8n workflow.

First node:

Webhook

Method:

POST

Example endpoint:

/webhook/posture

The ESP32 sends:

POST /webhook/posture
Content-Type: application/json

with the JSON data.


18. n8n Code Node

A Code node can calculate the initial risk.

Example JavaScript:

const data = $json;

const angle = Number(data.back_angle || 0);
const movement = Number(data.movement || 0);

let posture = "GOOD";
let angleRisk = 0;

if (angle < 10) {
  posture = "GOOD";
  angleRisk = 10;
} else if (angle < 20) {
  posture = "MODERATE";
  angleRisk = 30;
} else if (angle < 30) {
  posture = "POOR";
  angleRisk = 60;
} else {
  posture = "SEVERE";
  angleRisk = 85;
}

let movementRisk = 0;

if (movement < 0.2) {
  movementRisk = 10;
} else if (movement < 0.5) {
  movementRisk = 5;
}

const duration = Number(data.bad_posture_duration || 0);

let durationRisk = 0;

if (duration > 30 * 60) {
  durationRisk = 20;
} else if (duration > 15 * 60) {
  durationRisk = 10;
}

let riskScore = angleRisk + movementRisk + durationRisk;

if (riskScore > 100) {
  riskScore = 100;
}

let riskLevel = "LOW";

if (riskScore >= 80) {
  riskLevel = "VERY_HIGH";
} else if (riskScore >= 60) {
  riskLevel = "HIGH";
} else if (riskScore >= 30) {
  riskLevel = "MODERATE";
}

return [
  {
    json: {
      ...data,
      posture,
      angle_risk: angleRisk,
      duration_risk: durationRisk,
      movement_risk: movementRisk,
      risk_score: riskScore,
      risk_level: riskLevel
    }
  }
];

19. AI Agent Prompt

Use an AI Agent after the risk calculation.

A suitable system instruction is:

You are an ergonomic posture monitoring assistant.

Analyze the sensor data supplied by the IoT system.

Do not diagnose diseases or medical conditions.

Use the provided posture classification and risk score as the primary
decision inputs.

Your responsibilities:

1. Explain the current posture condition.
2. Determine whether an ergonomic reminder is appropriate.
3. Provide a short practical recommendation.
4. Avoid alarming medical claims.
5. If the risk is HIGH or VERY_HIGH, recommend taking a short break,
   changing posture, and reducing prolonged static positioning.

Return JSON only:

{
  "risk_level": "",
  "should_alert": true,
  "message": "",
  "recommendation": "",
  "voice_alert": true
}

20. Example AI Response

{
  "risk_level": "HIGH",
  "should_alert": true,
  "message": "You have remained in a forward-bent posture for an extended period.",
  "recommendation": "Straighten your back, adjust your sitting position, and take a short movement break.",
  "voice_alert": true
}

21. Telegram Alert

The text message could look like:

⚠️ POSTURE ALERT

Posture: POOR
Back angle: 31°
Duration: 22 min
Risk score: 82/100

Recommendation:
Straighten your back and take a short movement break.

22. Telegram Voice Alert

The workflow can generate:

"Posture alert. You have been leaning forward for an extended period.
Please straighten your back and take a short movement break."

The process is:

AI Agent
   ↓
Alert text
   ↓
Text-to-Speech service
   ↓
MP3/OGG audio
   ↓
Telegram Bot
   ↓
User's phone

The exact TTS service can be changed without modifying the ESP32 firmware.


23. Google Sheets Database

Create a sheet with columns such as:

Timestamp Device Back Angle Movement Posture Duration Risk Score Risk Level Alert
22:10 ESP32_01 8 0.7 GOOD 0 10 LOW NO
22:15 ESP32_01 23 0.3 POOR 300 65 HIGH YES

This gives you historical data for:

  • Daily analysis
  • Weekly analysis
  • User behavior
  • Posture trends
  • AI analysis
  • Project demonstrations

24. ThingSpeak Integration

ThingSpeak can be used as the IoT visualization layer.

Possible fields:

Field 1 = Back Angle
Field 2 = Movement
Field 3 = Risk Score
Field 4 = Posture State
Field 5 = Duration
Field 6 = Alert Status

Conceptually:

ESP32
  ↓
n8n
  ↓
ThingSpeak
  ↓
Cloud graphs

Example graph:

Risk
100 |                *
 80 |           *    *
 60 |       *   *
 40 |    *
 20 | *
  0 +-----------------------
       Time →

25. IoT Webpage

The web dashboard can display:

┌─────────────────────────────────────────┐
│       AI POSTURE MONITOR                │
├─────────────────────────────────────────┤
│                                         │
│ Current Posture       POOR ⚠️           │
│                                         │
│ Back Angle            28.5°             │
│ Risk Score            72/100            │
│                                         │
│ Poor Posture Duration  18 min           │
│                                         │
│ Movement              LOW               │
│                                         │
├─────────────────────────────────────────┤
│              RISK METER                 │
│                                         │
│ LOW       MODERATE     HIGH             │
│ ├────────────┼────────────┼─────────┤   │
│                         ▲               │
│                        72               │
├─────────────────────────────────────────┤
│ AI Recommendation                       │
│                                         │
│ "Adjust your sitting position and       │
│ take a short movement break."           │
└─────────────────────────────────────────┘

26. Simple Webpage

A basic HTML dashboard can be built with:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>AI Posture Monitor</title>

    <style>
        body {
            font-family: Arial, sans-serif;
            background: #101827;
            color: white;
            margin: 0;
            padding: 20px;
        }

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

        h1 {
            text-align: center;
        }

        .grid {
            display: grid;
            grid-template-columns:
                repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
        }

        .card {
            background: #1e293b;
            padding: 20px;
            border-radius: 15px;
            box-shadow:
                0 5px 20px rgba(0,0,0,0.3);
        }

        .value {
            font-size: 32px;
            font-weight: bold;
        }

        .good {
            color: #22c55e;
        }

        .warning {
            color: #f59e0b;
        }

        .danger {
            color: #ef4444;
        }

        .bar {
            width: 100%;
            height: 25px;
            background: #334155;
            border-radius: 20px;
            overflow: hidden;
        }

        #riskBar {
            height: 100%;
            width: 0%;
            background: #22c55e;
        }
    </style>
</head>

<body>

<div class="container">

    <h1>🤖 AI Posture Monitoring System</h1>

    <div class="grid">

        <div class="card">
            <h3>Posture</h3>
            <div id="posture"
                 class="value good">
                GOOD
            </div>
        </div>

        <div class="card">
            <h3>Back Angle</h3>
            <div class="value">
                <span id="angle">0</span
            </div>
        </div>

        <div class="card">
            <h3>Risk Score</h3>
            <div class="value">
                <span id="risk">0</span>/100
            </div>
        </div>

        <div class="card">
            <h3>Duration</h3>
            <div class="value">
                <span id="duration">0</span> min
            </div>
        </div>

    </div>

    <br>

    <div class="card">

        <h3>Risk Level</h3>

        <div class="bar">
            <div id="riskBar"></div>
        </div>

    </div>

    <br>

    <div class="card">

        <h3>AI Recommendation</h3>

        <p id="recommendation">
            Waiting for sensor data...
        </p>

    </div>

</div>

<script>

function updateDashboard(data) {

    document.getElementById("posture")
        .innerText = data.posture;

    document.getElementById("angle")
        .innerText = data.back_angle;

    document.getElementById("risk")
        .innerText = data.risk_score;

    document.getElementById("duration")
        .innerText =
        Math.round(
            data.bad_posture_duration / 60
        );

    document.getElementById("riskBar")
        .style.width =
        data.risk_score + "%";

    document.getElementById("recommendation")
        .innerText =
        data.recommendation ||
        "Maintain a comfortable posture.";
}

</script>

</body>
</html>

This frontend can later be connected to an API endpoint, WebSocket, ThingSpeak data or another backend.


27. ESP32 Firmware

Below is a basic Arduino-style ESP32 implementation.

Required libraries:

Wire
WiFi
HTTPClient
Adafruit MPU6050
Adafruit Unified Sensor
ArduinoJson

Example firmware:

#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>

Adafruit_MPU6050 mpu;

// -----------------------------
// WiFi
// -----------------------------

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

// n8n webhook
const char* N8N_WEBHOOK =
    "https://YOUR_N8N_SERVER/webhook/posture";

// Device
const char* DEVICE_ID =
    "POSTURE_ESP32_01";

// LED
const int LED_PIN = 2;

// Timing
unsigned long lastSend = 0;

const unsigned long SEND_INTERVAL =
    5000;

// Poor posture tracking
unsigned long poorStart = 0;

bool poorPostureActive = false;


// -----------------------------
// Setup
// -----------------------------

void setup() {

    Serial.begin(115200);

    pinMode(LED_PIN, OUTPUT);

    Wire.begin(21, 22);

    if (!mpu.begin()) {

        Serial.println(
            "MPU6050 not found!"
        );

        while (1) {
            delay(1000);
        }
    }

    Serial.println(
        "MPU6050 initialized."
    );

    connectWiFi();
}


// -----------------------------
// WiFi
// -----------------------------

void connectWiFi() {

    WiFi.begin(
        WIFI_SSID,
        WIFI_PASSWORD
    );

    Serial.print(
        "Connecting to WiFi"
    );

    while (
        WiFi.status() != WL_CONNECTED
    ) {

        delay(500);

        Serial.print(".");
    }

    Serial.println();

    Serial.println(
        "WiFi connected."
    );

    Serial.print(
        "IP: "
    );

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


// -----------------------------
// Loop
// -----------------------------

void loop() {

    sensors_event_t accel;
    sensors_event_t gyro;
    sensors_event_t temp;

    mpu.getEvent(
        &accel,
        &gyro,
        &temp
    );

    float ax = accel.acceleration.x;
    float ay = accel.acceleration.y;
    float az = accel.acceleration.z;

    float gx = gyro.gyro.x;
    float gy = gyro.gyro.y;
    float gz = gyro.gyro.z;


    // Calculate approximate tilt.
    float angle =
        atan2(
            ay,
            sqrt(
                ax * ax +
                az * az
            )
        ) *
        180.0 /
        PI;

    float backAngle =
        abs(angle);


    // Simple movement estimate
    float movement =
        sqrt(
            gx * gx +
            gy * gy +
            gz * gz
        );


    // Determine posture
    String posture;

    if (backAngle < 10) {

        posture = "GOOD";

    } else if (backAngle < 20) {

        posture = "MODERATE";

    } else if (backAngle < 30) {

        posture = "POOR";

    } else {

        posture = "SEVERE";
    }


    // Duration tracking
    if (
        posture == "POOR" ||
        posture == "SEVERE"
    ) {

        if (!poorPostureActive) {

            poorStart = millis();

            poorPostureActive = true;
        }

    } else {

        poorPostureActive = false;

        poorStart = 0;
    }


    unsigned long duration = 0;

    if (poorPostureActive) {

        duration =
            (millis() - poorStart)
            / 1000;
    }


    // LED warning
    if (
        posture == "POOR" ||
        posture == "SEVERE"
    ) {

        digitalWrite(
            LED_PIN,
            HIGH
        );

    } else {

        digitalWrite(
            LED_PIN,
            LOW
        );
    }


    // Send periodically
    if (
        millis() - lastSend
        >= SEND_INTERVAL
    ) {

        lastSend = millis();

        sendData(
            ax,
            ay,
            az,
            gx,
            gy,
            gz,
            backAngle,
            movement,
            posture,
            duration
        );
    }

    delay(100);
}


// -----------------------------
// Send data to n8n
// -----------------------------

void sendData(
    float ax,
    float ay,
    float az,
    float gx,
    float gy,
    float gz,
    float backAngle,
    float movement,
    String posture,
    unsigned long duration
) {

    if (
        WiFi.status()
        != WL_CONNECTED
    ) {

        connectWiFi();
    }


    HTTPClient http;

    http.begin(
        N8N_WEBHOOK
    );

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


    JsonDocument doc;

    doc["device_id"] =
        DEVICE_ID;

    doc["back_angle"] =
        backAngle;

    doc["accel_x"] =
        ax;

    doc["accel_y"] =
        ay;

    doc["accel_z"] =
        az;

    doc["gyro_x"] =
        gx;

    doc["gyro_y"] =
        gy;

    doc["gyro_z"] =
        gz;

    doc["movement"] =
        movement;

    doc["posture"] =
        posture;

    doc["bad_posture_duration"] =
        duration;


    String payload;

    serializeJson(
        doc,
        payload
    );


    Serial.println(
        payload
    );


    int responseCode =
        http.POST(payload);


    Serial.print(
        "HTTP response: "
    );

    Serial.println(
        responseCode
    );


    if (
        responseCode > 0
    ) {

        Serial.println(
            http.getString()
        );
    }


    http.end();
}

28. Important ESP32 Improvement

The simple atan2() approach is useful for a prototype, but a production-quality posture system should use:

  • Accelerometer calibration
  • Gyroscope calibration
  • Sensor fusion
  • Complementary filter
  • Kalman filter or equivalent
  • Moving average
  • Orientation quaternion
  • Automatic baseline calibration

For example:

Raw Accelerometer
        +
Raw Gyroscope
        ↓
Calibration
        ↓
Low-pass filtering
        ↓
Sensor fusion
        ↓
Orientation
        ↓
Posture angle

29. Complementary Filter

A complementary filter can combine gyro and accelerometer information.

Conceptually:

Angle =
    0.98 × Gyroscope angle
    +
    0.02 × Accelerometer angle

Example:

float accelAngle;

float gyroAngle;

float filteredAngle;

float alpha = 0.98;

filteredAngle =
    alpha * gyroAngle +
    (1.0 - alpha) * accelAngle;

This generally produces a more stable orientation than relying solely on the accelerometer.


30. Better Muscle-Strain Risk Model

Instead of calling a sensor measurement “muscle strain,” use:

Estimated Muscle-Strain / Ergonomic Risk

because the system cannot directly measure muscle tissue damage using an MPU6050.

A better model is:

                    ┌─────────────┐
                    │ Back Angle  │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │ Duration    │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │ Movement    │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │ Repetition  │
                    └──────┬──────┘
                           │
                    ┌──────▼──────┐
                    │ Risk Engine │
                    └──────┬──────┘
                           │
                           ▼
                  Ergonomic Risk Score

31. Example Risk Formula

You could implement:

Risk =
    0.40 × Posture Score
  + 0.25 × Duration Score
  + 0.20 × Movement Score
  + 0.15 × Repetition Score

For example:

Posture Score      = 80
Duration Score     = 70
Movement Score     = 50
Repetition Score   = 60

Then:

Risk =
0.40(80)
+ 0.25(70)
+ 0.20(50)
+ 0.15(60)

= 32 + 17.5 + 10 + 9

= 68.5

Therefore:

Risk = 69/100

Classification:

0–30     LOW
31–60    MODERATE
61–80    HIGH
81–100   VERY HIGH

32. Alert Logic

Avoid sending Telegram notifications every five seconds.

Otherwise:

ESP32
 ↓
n8n
 ↓
Telegram
 ↓
Telegram
 ↓
Telegram
 ↓
Telegram

The user will receive hundreds of notifications.

Instead use an alert cooldown.

Example:

Poor posture detected
       ↓
Wait 5 minutes
       ↓
Still poor?
       ↓
Send alert
       ↓
Cooldown 15 minutes
       ↓
Check again

33. Alert State Machine

             ┌───────────┐
             │   GOOD    │
             └─────┬─────┘
                   │
             poor posture
                   │
                   ▼
             ┌───────────┐
             │ MONITORING│
             └─────┬─────┘
                   │
             persists
                   │
                   ▼
             ┌───────────┐
             │  WARNING  │
             └─────┬─────┘
                   │
             high risk
                   │
                   ▼
             ┌───────────┐
             │   ALERT   │
             └─────┬─────┘
                   │
             cooldown
                   │
                   ▼
             ┌───────────┐
             │ MONITORING│
             └───────────┘

34. n8n Full Workflow

A practical workflow can contain these nodes:

[Webhook]
     |
     ▼
[Set / Validate Data]
     |
     ▼
[Code: Risk Calculation]
     |
     ▼
[AI Agent]
     |
     ├──────────────► [Google Sheets]
     │
     ├──────────────► [ThingSpeak HTTP Request]
     │
     ▼
[IF: should_alert]
     |
    YES
     |
     ▼
[Telegram Message]
     |
     ▼
[Text-to-Speech]
     |
     ▼
[Telegram Send Audio]

35. Google Sheets Node

Map:

Timestamp
Device ID
Back Angle
Movement
Posture
Duration
Risk Score
Risk Level
AI Message
Recommendation
Alert

Example:

{{$now}}
{{$json.device_id}}
{{$json.back_angle}}
{{$json.movement}}
{{$json.posture}}
{{$json.bad_posture_duration}}
{{$json.risk_score}}
{{$json.risk_level}}
{{$json.message}}
{{$json.recommendation}}
{{$json.should_alert}}

36. ThingSpeak Node

Use an HTTP Request node.

Conceptually:

ThingSpeak Update
        ↓
field1 = back angle
field2 = movement
field3 = risk
field4 = posture
field5 = duration

The API key should be stored securely as an n8n credential/environment secret rather than hard-coded into ESP32 firmware or public frontend JavaScript.


37. Telegram Bot Architecture

             n8n
              │
      ┌───────┴────────┐
      │                │
      ▼                ▼
Telegram Text      TTS Service
      │                │
      │                ▼
      │             Audio
      │                │
      └───────┬────────┘
              ▼
       Telegram Bot
              │
              ▼
           Phone

38. Telegram Message Examples

Moderate

ℹ️ Posture Reminder

Your posture has been slightly forward for several minutes.

Please adjust your sitting position.

High

⚠️ HIGH POSTURE RISK

Back angle: 28°
Duration: 21 minutes
Risk score: 74/100

Recommendation:
Change your posture and take a short movement break.

Very high

🚨 POSTURE ALERT

A high-risk posture pattern has persisted.

Risk score: 89/100.

Please stop the prolonged static posture,
reposition yourself and take a short movement break.

39. Voice Notification

The spoken message should be short.

Example:

"Posture alert. Please straighten your back
and take a short movement break."

Do not make the voice alert overly long.


40. Local ESP32 Alert

You can also implement immediate local feedback:

Posture GOOD
     ↓
Green LED

Posture MODERATE
     ↓
Yellow LED

Posture POOR
     ↓
Red LED

Posture SEVERE
     ↓
Red LED + vibration

Example:

              ESP32
                │
       ┌────────┼────────┐
       │        │        │
       ▼        ▼        ▼
      LED    Vibration  OLED

This means the system remains useful even if the internet connection temporarily fails.


41. Complete Communication Architecture

                   INTERNET
                      │
        ┌─────────────┴─────────────┐
        │                           │
        ▼                           ▼
      n8n                        ThingSpeak
        │
        │
   ┌────┼──────────┐
   │    │          │
   ▼    ▼          ▼
 AI   Sheets    Telegram
Agent
   │                 │
   │                 ├── Text
   │                 │
   │                 └── Voice
   │
   ▼
 Recommendation

42. Agentic IoT Concept

The system becomes more “agentic” when it doesn't merely transmit sensor values.

Instead:

Observe
   ↓
Analyze
   ↓
Reason
   ↓
Decide
   ↓
Act
   ↓
Observe again

For example:

ESP32 observes:
Back angle = 27°

       ↓

n8n analyzes:
Poor posture for 18 minutes

       ↓

AI Agent reasons:
Risk is elevated

       ↓

Decision:
Alert user

       ↓

Action:
Telegram text + voice

       ↓

User changes posture

       ↓

ESP32 observes improvement

That is the core Agentic IoT feedback loop.


43. Closed-Loop Architecture

       ┌──────────────────────┐
       │        USER          │
       └──────────┬───────────┘
                  │
             Body posture
                  │
                  ▼
       ┌──────────────────────┐
       │       ESP32          │
       │     Sensors          │
       └──────────┬───────────┘
                  │
                  ▼
       ┌──────────────────────┐
       │        n8n           │
       │   Automation Engine  │
       └──────────┬───────────┘
                  │
                  ▼
       ┌──────────────────────┐
       │       AI Agent       │
       │  Interpretation      │
       └──────────┬───────────┘
                  │
                  ▼
       ┌──────────────────────┐
       │   Decision Engine    │
       └──────────┬───────────┘
                  │
                  ▼
       ┌──────────────────────┐
       │ Telegram / Vibration │
       └──────────┬───────────┘
                  │
                  ▼
                USER
                  │
                  └───────────────┐
                                  │
                                  ▼
                               ESP32

44. Project Folder Structure

A clean implementation could use:

AI_Posture_Monitor/
│
├── ESP32/
│   ├── posture_monitor.ino
│   ├── config.h
│   └── sensor_calibration.h
│
├── n8n/
│   ├── workflow.json
│   └── ai_prompt.txt
│
├── WebDashboard/
│   ├── index.html
│   ├── style.css
│   └── app.js
│
├── Documentation/
│   ├── architecture.md
│   ├── wiring.md
│   └── testing.md
│
└── README.md

45. Development Procedure

Phase 1 — Sensor Test

First connect:

ESP32 + MPU6050

Verify:

Accelerometer
Gyroscope
Temperature

in Serial Monitor.


Phase 2 — Angle Calculation

Move the sensor:

0°
10°
20°
30°
45°

Record the calculated values.

Create a calibration table.


Phase 3 — Posture Classification

Implement:

GOOD
MODERATE
POOR
SEVERE

and verify manually.


Phase 4 — Wi-Fi

Connect ESP32 to Wi-Fi.

Test:

ESP32 → Internet

Phase 5 — n8n

Create:

ESP32 → n8n Webhook

Confirm JSON reception.


Phase 6 — Risk Engine

Add:

Angle
+
Duration
+
Movement

to generate the risk score.


Phase 7 — AI Agent

Connect the calculated data to the AI Agent.

Test AI responses.


Phase 8 — Google Sheets

Store every measurement/event.


Phase 9 — ThingSpeak

Display real-time graphs.


Phase 10 — Telegram

Implement:

Text notification

Then:

Voice notification

Phase 11 — Web Dashboard

Display:

Posture
Angle
Risk
Duration
Recommendation

Phase 12 — Full System Test

Test:

Sensor
 ↓
ESP32
 ↓
Wi-Fi
 ↓
n8n
 ↓
AI
 ↓
Sheets
 ↓
ThingSpeak
 ↓
Telegram
 ↓
User

46. Testing Table

Test Expected Result
Normal upright posture GOOD
Slight forward bend MODERATE
Prolonged forward bend POOR/HIGH
Severe tilt SEVERE
Movement resumes Risk decreases
Wi-Fi disconnected ESP32 continues local monitoring
Wi-Fi restored Data transmission resumes
High risk Telegram alert
Voice enabled Telegram audio received
Sensor disconnected Error condition detected
n8n unavailable ESP32 doesn't crash

47. Fault-Tolerance Design

The system should not assume that the internet is always available.

Use:

             ESP32
               │
        ┌──────┴──────┐
        │             │
        ▼             ▼
 Local monitoring   Wi-Fi
        │             │
        │             ▼
        │            n8n
        │
        ▼
 Vibration / LED

If Wi-Fi fails:

ESP32
 ↓
Local posture detection
 ↓
Local vibration

When Wi-Fi returns:

ESP32
 ↓
n8n
 ↓
Cloud services

48. Security

Do not expose these directly in public firmware:

Telegram Bot Token
AI API Key
Google credentials
ThingSpeak write key
n8n authentication credentials

Instead:

ESP32
  │
  └── n8n webhook authentication

n8n
  │
  ├── AI credentials
  ├── Telegram credentials
  ├── Google credentials
  └── ThingSpeak credentials

Also use HTTPS whenever possible.


49. Authentication

A stronger ESP32 → n8n request can include an API token:

Authorization: Bearer YOUR_DEVICE_TOKEN

n8n checks:

Token valid?
   │
   ├── YES → process
   │
   └── NO → reject

50. Data Privacy

Because posture data can reveal user behavior, consider:

  • Device authentication.
  • HTTPS.
  • Restricted Google Sheet access.
  • Private ThingSpeak channels.
  • Secure Telegram bot credentials.
  • Minimal personal information.
  • Data retention policies.

Do not store unnecessary personally identifying information.


51. Improved Two-Sensor Design

For a stronger project, use two MPU6050/IMU sensors.

             HEAD
               O
              /|\
             [IMU2]
               |
               |
             [IMU1]
               |
              BACK

Calculate:

Neck angle
+
Back angle

For example:

Neck = 25°
Back = 28°

This is more informative than using only one orientation measurement.


52. Advanced Sensor Configuration

For multiple I²C MPU6050 devices, both normally use the same I²C address unless configured differently.

A common solution is an I²C multiplexer such as:

ESP32
  │
  ▼
I²C Multiplexer
  ├──── MPU6050 #1
  └──── MPU6050 #2

This makes it easier to use multiple identical I²C sensors.


53. Advanced AI Analytics

After collecting enough historical data, you can introduce:

Daily posture report

Example:

Daily AI Report

Total monitoring time: 7h 12m

Good posture:       61%
Moderate posture:   23%
Poor posture:       12%
Severe posture:      4%

Longest poor-posture period:
31 minutes

Most frequent time:
14:00–16:00

Recommendation:
Schedule short movement breaks during long work periods.

54. Weekly AI Agent

The AI Agent can analyze Google Sheets data:

Google Sheets
      ↓
Weekly aggregation
      ↓
AI Agent
      ↓
Weekly report
      ↓
Telegram

Example:

📊 Weekly Posture Report

Average risk: 48/100

Best day: Wednesday
Highest risk period: 2 PM–4 PM

You had 17 prolonged poor-posture events.

Suggestion:
Consider adding short movement breaks during afternoon work sessions.

55. Dashboard Pages

A complete web application could contain:

Dashboard
│
├── Live Monitoring
│
├── Posture History
│
├── Risk Analytics
│
├── AI Recommendations
│
├── Alert History
│
├── Device Status
│
└── Settings

56. Live Dashboard Architecture

                    ESP32
                      │
                      ▼
                    n8n
                      │
              ┌───────┴────────┐
              │                │
              ▼                ▼
          ThingSpeak        Web API
                               │
                               ▼
                         Web Dashboard

For a more real-time implementation:

ESP32
 ↓
MQTT/WebSocket
 ↓
Backend
 ↓
WebSocket
 ↓
Browser

For a student project, however, HTTP + n8n + ThingSpeak is simpler.


57. Suggested Final Hardware Block Diagram

                    ┌───────────────┐
                    │     USER      │
                    └───────┬───────┘
                            │
                    Body movement
                            │
                            ▼
                ┌────────────────────┐
                │      MPU6050       │
                │ Accelerometer/Gyro  │
                └──────────┬─────────┘
                           I²C
                            │
                            ▼
                ┌────────────────────┐
                │       ESP32        │
                │                    │
                │ Sensor Processing  │
                │ Posture Detection  │
                │ Local Alerts       │
                │ Wi-Fi              │
                └──────────┬─────────┘
                           │
                         HTTPS
                           │
                           ▼
                ┌────────────────────┐
                │       n8n          │
                │                    │
                │ Webhook             │
                │ Automation          │
                │ Risk Engine         │
                │ AI Agent            │
                └──────┬─────┬───────┘
                       │     │
              ┌────────┘     └─────────┐
              ▼                        ▼
       ┌─────────────┐          ┌─────────────┐
       │Google Sheets│          │ ThingSpeak  │
       └─────────────┘          └─────────────┘
                       │
                       ▼
                ┌─────────────┐
                │  Telegram   │
                │             │
                │ Text        │
                │ Voice       │
                └──────┬──────┘
                       │
                       ▼
                     USER

58. Complete Project Workflow

The final working sequence is:

STEP 1
User wears/uses the posture sensor
        ↓
STEP 2
MPU6050 measures acceleration and rotation
        ↓
STEP 3
ESP32 calculates orientation
        ↓
STEP 4
ESP32 determines posture state
        ↓
STEP 5
ESP32 measures poor-posture duration
        ↓
STEP 6
ESP32 sends JSON to n8n
        ↓
STEP 7
n8n validates sensor data
        ↓
STEP 8
n8n calculates ergonomic risk
        ↓
STEP 9
AI Agent interprets the situation
        ↓
STEP 10
Google Sheets stores the event
        ↓
STEP 11
ThingSpeak updates cloud graphs
        ↓
STEP 12
n8n checks alert conditions
        ↓
STEP 13
Telegram text alert is generated
        ↓
STEP 14
TTS generates voice notification
        ↓
STEP 15
Telegram sends audio
        ↓
STEP 16
User corrects posture
        ↓
STEP 17
ESP32 detects improvement
        ↓
STEP 18
Risk score decreases

59. What Makes This Project Innovative

The project isn't simply:

ESP32 → Telegram

It combines:

Edge AI/processing
       +
IoT sensing
       +
Cloud automation
       +
AI Agent
       +
Decision engine
       +
Voice notification
       +
Historical analytics
       +
Cloud visualization

The strongest project description is therefore:

An agentic IoT-based ergonomic monitoring system that uses an ESP32 and inertial sensors to continuously estimate posture and prolonged static-position risk, sends telemetry to an n8n automation platform, applies rule-based risk analysis and an AI agent for contextual interpretation, records historical measurements in Google Sheets, visualizes telemetry through ThingSpeak, and delivers intelligent Telegram text and voice alerts when sustained poor-posture patterns are detected.


60. Recommended Final Technology Stack

Layer Technology
Microcontroller ESP32
Motion sensor MPU6050 / MPU9250
Firmware Arduino/C++
Communication Wi-Fi + HTTPS
Automation n8n
AI AI Agent/LLM
Database/logging Google Sheets
IoT visualization ThingSpeak
Notification Telegram Bot
Voice TTS + Telegram audio
Dashboard HTML/CSS/JavaScript
Local feedback LED/Vibration
Data format JSON
API style REST/HTTP

61. Recommended Project Demonstration

For a college/project presentation, demonstrate it in this order:

1. Show ESP32 hardware
        ↓
2. Show MPU6050
        ↓
3. Sit upright
        ↓
4. Dashboard shows GOOD
        ↓
5. Lean forward
        ↓
6. Dashboard changes to POOR
        ↓
7. Maintain posture
        ↓
8. Duration increases
        ↓
9. Risk increases
        ↓
10. n8n receives data
        ↓
11. AI Agent analyzes it
        ↓
12. Google Sheets receives record
        ↓
13. ThingSpeak graph changes
        ↓
14. Telegram text arrives
        ↓
15. Telegram voice alert arrives
        ↓
16. Correct posture
        ↓
17. Risk decreases

That gives you a very strong end-to-end demonstration.


62. Final System Summary

             AI POSTURE MONITOR
                    │
        ┌───────────┴───────────┐
        │                       │
      ESP32                   Sensors
        │
        ▼
   Local Processing
        │
        ▼
     Wi-Fi/HTTPS
        │
        ▼
       n8n
        │
   ┌────┼─────────┐
   │    │         │
   ▼    ▼         ▼
  AI  Sheets  ThingSpeak
   │
   ▼
Decision Engine
   │
   ▼
Telegram
 ┌─┴─────┐
 ▼       ▼
Text    Voice
 │       │
 └───┬───┘
     ▼
    USER

The best implementation strategy is to build it incrementally: ESP32 + MPU6050 first → posture calculation → n8n webhook → risk engine → AI Agent → Google Sheets → ThingSpeak → Telegram text → TTS voice → dashboard → fault tolerance/security. This avoids debugging the entire system simultaneously and makes each stage independently testable.

No comments:

Post a Comment