Skip to content

pcamposu/plumet-esp8266

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Plumet Plumet ESP8266 Firmware

Build Status PlatformIO License C++

Screenshots

Captive Portal - WiFi Configuration

Captive Portal Login Captive Portal Success

Overview

Plumet ESP8266 Firmware is the embedded software component of the Plumet system. This firmware runs on the wearable belt device equipped with a NodeMCU ESP8266 and MPU6050 IMU sensor.

How It Works

  1. Sensor Monitoring: The MPU6050 accelerometer is polled at 100Hz to detect sudden acceleration changes
  2. Fall Detection Algorithm: Analyzes G-force patterns to identify free fall followed by impact
  3. Event Publishing: When a fall is detected, connects to WiFi and publishes an MQTT message
  4. Real-time Alerts: The backend forwards the alert to the mobile app via MQTT, showing a push notification

Communication Flow

ESP8266 (Firmware)                    Backend (NestJS)                     Mobile App
     |                                      |                                    |
     |-- Fall detected                     |                                    |
     |-- Connect to WiFi                  |                                    |
     |-- Publish to MQTT                   |                                    |
     |                                      |                                    |
     |------------------------------------->| Forward alert via MQTT             |
     |                                      |                                    |
     |                                      |------------------------------------->|
     |                                      |           Push notification shown
     |                                      |                                    |
     |-- Disconnect immediately             |                                    |
     |                                      |                                    |
     |-- Return to sleep mode              |                                    |

Key Design Decisions

  • Event-driven MQTT: The device only connects to MQTT when a fall is detected, then disconnects. This saves battery and reduces network traffic.
  • WiFi Provisioning via Captive Portal: Users can configure WiFi credentials through a browser-based interface without modifying code.
  • EEPROM Storage: WiFi credentials are persisted in non-volatile memory, surviving power cycles.

Key Features

  • Real-time Fall Detection - 100Hz accelerometer sampling with adaptive algorithm
  • WiFi Provisioning - Captive portal for easy network configuration
  • MQTT over WebSocket - Secure event-driven communication
  • LED Status Indicators - Visual feedback for device state
  • Event-Driven Architecture - Battery-efficient, sleeps until fall detected
  • Telemetry Data - G-force, timestamp, baseline calibration values

Table of Contents

Hardware Requirements

Components Needed

Component Specification Qty Notes
NodeMCU ESP8266 ESP-12E, 4MB Flash 1 Development board with USB
MPU6050 3-axis IMU (accel + gyro) 1 I2C interface
Belt/Strap Adjustable, 2-5cm width 1 For wearing the device
USB Cable Micro-USB, data-capable 1 For flashing
Jumper Wires Female-to-female 4 For I2C connection
Power Source 5V USB or 3.7V LiPo 1 Battery for portable use

Optional Components

  • 3.7V LiPo Battery - For portable operation
  • TP4056 Charger Module - For battery charging
  • Switch - On/off power control
  • Enclosure - 3D printed case

Software Prerequisites

Required Tools

pip install platformio

pio --version

Drivers

  • Windows: Install CH340 USB driver
  • macOS: Usually pre-installed, or install here
  • Linux: Usually pre-installed (sudo modprobe usbserial if needed)

Wiring Diagram

MPU6050 to NodeMCU ESP8266

flowchart TD
    subgraph NodeMCU["NodeMCU ESP8266"]
        D1["D1 (GPIO5)<br/>I2C SCL"]
        D2["D2 (GPIO4)<br/>I2C SDA"]
        VCC["3V3"]
        GND["GND"]
    end

    subgraph MPU6050["MPU6050 Sensor"]
        SCL["SCL"]
        SDA["SDA"]
        VCC2["VCC"]
        GND2["GND"]
        INT["INT (Optional)"]
    end

    D1 -->|"Jumper Wire"| SCL
    D2 -->|"Jumper Wire"| SDA
    VCC -->|"Jumper Wire"| VCC2
    GND -->|"Jumper Wire"| GND2

    style D1 fill:#EDD60A
    style D2 fill:#EDD60A
    style VCC fill:#ef4444
    style GND fill:#374151
    style SCL fill:#3b82f6
    style SDA fill:#3b82f6
    style VCC2 fill:#ef4444
    style GND2 fill:#374151
Loading

Pin Connections

NodeMCU MPU6050 Wire Color
D1 (GPIO5) SCL Yellow
D2 (GPIO4) SDA Green
3V3 VCC Red
GND GND Black

LED

Pin Description
Built-in LED (D4/GPIO2) Status indicator (active LOW)

Connection Steps

  1. Power Off: Disconnect USB before wiring
  2. Connect I2C:
    • SCL (D1) to MPU6050 SCL
    • SDA (D2) to MPU6050 SDA
  3. Connect Power:
    • 3V3 to MPU6050 VCC
    • GND to MPU6050 GND
  4. Verify: Check connections against diagram above
  5. Power On: Connect USB cable

Warning:

  • VCC of MPU6050 is 3.3V only - Do NOT connect to 5V (Vin)
  • Ensure correct polarity (VCC to VCC, GND to GND)

Quick Start

Clone Repository

git clone https://github.com/plumet/plumet-esp8266.git
cd plumet-esp8266

Build Firmware

# Build for ESP8266
pio run

Output will be in .pio/build/esp8266/firmware.bin

Flash Firmware

Using PlatformIO

# Upload to connected device
pio run --target upload

# Monitor serial output (optional)
pio device monitor

# Upload and monitor in one command
pio run --target upload && pio device monitor

Using Pre-built Firmware from Releases

  1. Download firmware:

    • Go to Releases
    • Download plumet-esp8266-vX.X.X.bin
  2. Install esptool:

    pip install esptool
  3. Find your serial port:

    # Linux
    ls /dev/ttyUSB*
    
    # macOS
    ls /dev/tty.usbserial*
    
    # Windows
    # Look in Device Manager for COM port
  4. Flash firmware:

    esptool.py --chip esp8266 \
      --port /dev/ttyUSB0 \
      --baud 460800 \
      write_flash \
      -fm dio \
      -fs 4MB \
      0x00000 firmware.bin

    Replace /dev/ttyUSB0 with your serial port.

Using NodeMCU Flasher (Windows)

  1. Download NodeMCU Flasher
  2. Extract and run nodemcu-flasher.exe
  3. Select firmware .bin file
  4. Select COM port
  5. Click "Flash" button

Verify Flash

After flashing, open serial monitor:

pio device monitor -b 115200

You should see:

[INFO] Attempting to connect to WiFi...

Or if no WiFi configured:

[INFO] AP mode active. Connect to configure WiFi

WiFi Configuration

Captive Portal Setup

The device features a captive portal for WiFi provisioning:

  1. First Boot - Device creates AP: Plumet_<CHIPID>
  2. Connect - Join the AP with your phone/laptop (no password needed)
  3. Configure - Browser opens automatically (captive portal)
  4. Enter Credentials - SSID and password
  5. Connect - Device saves credentials and restarts
  6. Ready - Device connects to WiFi and starts monitoring

Reset WiFi Credentials

There are three ways to reset WiFi credentials and force AP mode:

Method 1: Config Flag (Recommended - No Code Modification)

Edit src/config/config.h and temporarily set the persistence flag to false:

#define PERSIST_WIFI_CREDENTIALS false
  1. Flash the firmware with PERSIST_WIFI_CREDENTIALS = false
  2. Device will clear credentials on boot and enter AP mode
  3. Reconfigure WiFi via captive portal
  4. Change flag back to true and reflash for normal operation

Method 2: Automatic Reset on Connection Failure

If WiFi connection fails (after 60 second timeout), the device will:

  1. Automatically clear credentials from EEPROM
  2. Restart and enter AP mode
  3. Allow you to reconfigure WiFi via captive portal

Method 3: Manual Reset via Code

Temporarily add to setup() in src/main.ino:

WiFiManager.clearCredentials();
ESP.restart();

Flash the firmware, then remove these lines and reflash after reconfiguration.

LED Status Patterns

Pattern Meaning Description
Fast Blink (100ms) AP Mode Waiting for WiFi configuration
Slow Blink (500ms) Ready WiFi connected, monitoring active
Medium Blink (250ms) Connecting Attempting WiFi connection
Solid Off Device Ready Device is connected and ready
10 Rapid Blinks Fall Alert Fall detected, publishing event

Fall Detection Algorithm

┌─────────────────────────────────────────────────────────────┐
│                    FALL DETECTION FLOW                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. SAMPLE @ 100Hz                                          │
│     ├── Read MPU6050 (accel + gyro)                         │
│     ├── Convert raw to G-force (16384 LSB/g)               │
│     └── Calculate magnitude |a| = √(ax² + ay² + az²)        │
│                                                             │
│  2. UPDATE HISTORY (Circular Buffer - 50 samples)          │
│     └── Push magnitude, pop oldest if full                 │
│                                                             │
│  3. DETECT FALL                                            │
│     ├── Check: current G > IMPACT_THRESHOLD (3.0G)         │
│     └── Verify: >50% samples < FALL_THRESHOLD (2.5G)      │
│                                                             │
│  4. TRIGGER ALERT                                          │
│     ├── LED: 3 rapid blinks                                │
│     ├── MQTT: Publish JSON payload                         │
│     └── Return to monitoring                               │
│                                                             │
└─────────────────────────────────────────────────────────────┘

Algorithm Explanation

  1. Calibration Phase (5 seconds):

    • Collects baseline acceleration values
    • Averages samples to determine resting orientation
  2. Monitoring Phase (continuous):

    • Reads accelerometer at 100Hz
    • Maintains circular buffer of last 50 samples
    • Calculates magnitude of acceleration vector
  3. Detection Logic:

    • Impact Detection: Current G-force > 3.0G
    • Fall Confirmation: >50% of recent samples < 2.5G
    • Combined indicates free fall followed by impact

MQTT Protocol

Topic: device/{MAC_ADDRESS}/fall

Method: MQTT over WebSocket Port: 443 (WSS) QoS: 1 (At least once)

Payload Format

{
  "macAddress": "AA:BB:CC:DD:EE:FF",
  "timestamp": 1234567890,
  "gForce": 3.2,
  "baselineX": 0.1,
  "baselineY": -0.2,
  "baselineZ": 9.8
}
Field Type Description
macAddress string Device MAC address (uppercase, colon-separated)
timestamp number Uptime in milliseconds since boot
gForce float Peak G-force at impact (1.0 = normal gravity)
baselineX/Y/Z float Calibration baseline values (G-force)

Configuration

Edit src/config/config.h to customize behavior:

WiFi Persistence

#define PERSIST_WIFI_CREDENTIALS false

Note: Currently set to false for development. WiFi credentials are not persisted between reboots.

MQTT and Sensor Configuration

#define MQTT_BROKER "broker-plumet.pcamposu.com"
#define MQTT_PORT 443
#define PLUMET_MQTT_TIMEOUT 15000

#define FALL_THRESHOLD 2.5
#define IMPACT_THRESHOLD 3.0

#define SAMPLE_RATE 100
#define CALIBRATION_SAMPLES 100

#define WIFI_CONNECTION_TIMEOUT 60000
#define SENSOR_READ_DELAY 10

Build Flags

-D DEBUG=1

Troubleshooting

Device Not Connecting to WiFi

Symptoms: LED keeps blinking fast, can't find device on network

Solutions:

  1. Check credentials - Press reset button twice quickly to clear EEPROM
  2. Verify SSID - Ensure SSID is visible and 2.4GHz (not 5GHz)
  3. Check password - Re-enter credentials via captive portal
  4. Restart router - Sometimes router has connection issues

Fall Detection Not Working

Symptoms: Device doesn't detect falls when tested

Solutions:

  1. Calibrate sensor - Place belt on flat surface during calibration
  2. Check MPU6050 - Verify I2C connections (SCL: D1, SDA: D2)
  3. Adjust thresholds - Lower IMPACT_THRESHOLD in config.h
  4. Serial monitor - Check for [Sensor] Fall detected! messages
  5. Test firmly - Drop device from ~30cm onto soft surface

MQTT Not Publishing

Symptoms: Fall detected but no MQTT message received

Solutions:

  1. Verify broker - Check MQTT_BROKER and MQTT_PORT in config.h
  2. Check WiFi - Ensure device has IP address
  3. Test manually - Use MQTT explorer to connect to broker
  4. View logs - Serial monitor shows MQTT connection attempts
  5. Check firewall - Ensure outbound connections on port 443 are allowed

Device Won't Flash

Symptoms: Upload fails, timeout errors

Solutions:

  1. Hold FLASH button - Press and hold GPIO0 button while powering on
  2. Check driver - Install CH340 driver (Windows)
  3. Try different cable - Use a data-capable USB cable
  4. Lower baud rate - Change upload_speed to 57600 in platformio.ini
  5. Reset board - Press reset button before uploading

Serial Monitor Shows Garbage

Symptoms: Random characters, unreadable text

Solutions:

  1. Check baud rate - Must be 115200
  2. Try different terminal - Use PlatformIO monitor instead of Arduino Serial Monitor
  3. Check USB cable - Some cables only work for power, not data

Development

Running Tests

pio test

pio test -v

pio test -e esp8266

Debug Build

pio run --target upload DEBUG=1

Memory Profiling

pio run --target size

# Expected output:
# Sketch uses 245KB (23% of storage)
# Global variables use 32KB (39% of dynamic memory)

Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

Development Setup

git clone https://github.com/your-username/plumet-esp8266.git
cd plumet-esp8266

git remote add upstream https://github.com/plumet/plumet-esp8266.git

git fetch upstream
git merge upstream/main

License

This project is licensed under the GNU General Public License v3.0 - see the COPYING file for details.

About

ESP8266 firmware for fall detection belt using MPU6050 accelerometer, WiFi provisioning, and MQTT over WebSocket.

Topics

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors