ESP32 Rehabilitation Hand Exoskeleton; From University Project to Streamlined BLE System

A journey of engineering evolution, optimization, and modern IoT integration with comprehensive analytics

[Project Overview]

What started as a simple Arduino-based servo controller has evolved into a sophisticated ESP32-powered rehabilitation device with wireless mobile control, real-time data logging, and comprehensive clinical analytics. This project demonstrates the complete transformation from a breadboard prototype to a professional IoT system using modern embedded technologies with enterprise-level data infrastructure. This has been an evolution of my honors stage project for my 3rd year of university.

Product so far.

The Evolution Journey

[Phase 1: The Humble Beginning]

The original system was built around an Arduino Uno with a traditional embedded approach:

Hardware Components:

  1. Arduino Uno microcontroller
  2. Large breadboard with extensive wiring
  3. Physical push button for state control
  4. Two LED indicators (pins 8 & 13)
  5. 3x servo motors (SG90 micro servos)
  6. Jumper wires creating a complex web of connections

Original Arduino Code Architecture:

// Simple state machine with button debouncing
byte currentState = 0;
void loop() {
  // Button polling with debounce logic
  // LED state management
  // Sequential servo control with delays
}

Limitations of the Original Design:

  • Physical Constraints: Large breadboard made the system bulky and fragile
  • User Interface: Single button required multiple presses to cycle through states
  • Feedback: Limited to two LEDs for status indication
  • Portability: Good but battery pack is rather heavy
  • Scalability: Adding features required more physical components
  • Reliability: Breadboard connections prone to loosening
  • No Data Logging: No way to track therapy sessions or progress
This is the device in each state.

[Phase 2: The Great Migration]

Why ESP32? The transition to ESP32 wasn’t just a hardware upgrade—it was a complete paradigm shift that unlocked modern IoT capabilities:

Technical Advantages:

  1. Dual-core architecture (240MHz) vs Arduino’s single 16MHz core

  2. Built-in WiFi and Bluetooth eliminating need for external modules

  3. FreeRTOS integration enabling true multitasking

  4. More GPIO pins with advanced peripheral support

  5. Lower power consumption with multiple sleep modes

  6. Real-time data logging capabilities via WiFi/MQTT

FreeRTOS: The Game Changer Yes, I absolutely leverage FreeRTOS throughout the system! This real-time operating system transformed my simple loop-based Arduino code into a sophisticated multitasking system:

FreeRTOS Implementation:

// Dedicated servo task running on Core 1
void servoTask(void *pvParameters) {
    for (;;) {
        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
        // Execute movement patterns with analytics tracking
        // Handle interruptions
        // Manage power optimization
        // Record movement metrics for clinical analysis
    }
}

// Main loop handles BLE communication on Core 0
void loop() {
    // BLE server management
    // Connection handling
    // Command processing
    // MQTT data publishing
}

Benefits Achieved:

  • True Multitasking: BLE communication and servo control run independently

  • Real-time Response: Immediate command processing without blocking operations

  • Task Prioritization: Critical servo movements get dedicated CPU core

  • Resource Management: Efficient memory and CPU utilization

  • Interrupt Safety: Proper synchronization between tasks

  • Data Collection: Continuous analytics and performance monitoring


[Phase 3: Mobile Revolution]

Eliminating Physical Constraints The most dramatic transformation came with the introduction of Bluetooth Low Energy (BLE) and a custom React Native mobile application:

What Was Replaced:

❌ Physical push button → ✅ Intuitive mobile interface with session management

❌ Limited LED feedback → ✅ Rich status displays and real-time updates

❌ Breadboard complexity → ✅ Clean, minimal wiring with 3D printed mounting

❌ Single-state cycling → ✅ Direct access to any movement pattern

❌ No data tracking → ✅ Comprehensive session logging and analytics

This device is not limited cyclable states.

BLE Protocol Implementation I implemented a custom BLE service using the NimBLE stack:

  • // Custom BLE service for servo control
  • Service UUID: 4fafc201-1fb5-459e-8fcc-c5c9c331914b
  • Characteristic UUID: beb5483e-36e1-4688-b7f5-ea07361b26a8

    Commands:

    • “TEST” → Individual servo testing
    • “1” → Sequential movement pattern
    • “2” → Simultaneous movement pattern
    • “0” → Stop/idle state
    • Session management with automatic start/manual end

Mobile App Architecture (React Native + TypeScript):

  • BLE Scanner: Automatic ESP32 device discovery
  • Connection Management: Robust reconnection handling
  • Real-time Control: Instant command transmission
  • Session Management: Automatic session creation, manual termination
  • Status Monitoring: Live feedback and error reporting
  • Debug Tools: Comprehensive troubleshooting interface

[Phase 4: Professional Data Infrastructure]

Complete Backend Transformation The latest evolution introduces enterprise-level data infrastructure with comprehensive analytics:

Docker Infrastructure Components:

🦟 Mosquitto MQTT Broker: Real-time ESP32 communication with WebSocket support

🗄️ MariaDB Database: Session tracking, movement data, and system logs

📊 Enhanced Analytics: Individual movement tracking and performance monitoring

🌐 Web Dashboard: Browser-based interface with live updates

📈 Grafana Integration: Professional clinical analytics dashboards

🔧 phpMyAdmin: Database management interface

MQTT Bridge: Real-time data processing with WebSocket integration

Webapp and Grafana.

Enhanced Analytics Implementation:

// Individual movement tracking with clinical metrics
struct MovementMetrics {
    unsigned long startTime;
    unsigned long duration;
    bool successful;
    int servoIndex;
    int startAngle;
    int targetAngle;
    int actualAngle;
    float smoothness;
    String movementType;
    String sessionId;
};

// Real-time MQTT publishing for analytics
void publishMovementAnalytics(const MovementMetrics& metrics) {
    // Publish detailed movement data
    // Clinical progress tracking
    // Performance monitoring
    // Session quality assessment
}

New MQTT Topics for Comprehensive Analytics:

rehab_exo/ESP32_001/movement/individual    # Per-servo movement data
rehab_exo/ESP32_001/movement/quality       # Movement quality metrics
rehab_exo/ESP32_001/performance/timing     # System performance data
rehab_exo/ESP32_001/performance/memory     # Memory usage analytics
rehab_exo/ESP32_001/clinical/progress      # Therapy progress tracking
rehab_exo/ESP32_001/clinical/quality       # Session quality scores

Grafana Dashboard Features:

Row 1: Overview Stats

  • Active Sessions, Today’s Sessions, Success Rate, System Status

Row 2: Session Analytics

  • Session Activity Over Time, Session Types Distribution

Row 3: Performance Metrics

  • Success Rate Trends, Response Times

Row 4: System Health

  • Memory Usage Trends, Connection Status Timeline

Row 5: Clinical Data

  • Therapy Progress, Movement Commands Distribution

[Phase 5: 3D Printing & Hardware Integration]

Professional Hardware Design The system now includes custom 3D printed components for professional deployment:

STL Files & Components:

  • 📁 STLs Directory: Complete 3D printable component library
  • 🦾 Hand Exoskeleton: Modified design optimized for miuzei ms18 servos
  • 🔧 ESP32 Base: Custom mounting base that attaches ESP32 to splint for wearable use
  • ⚙️ Servo Mounts: Precision-fitted mounting hardware

Print Specifications:

  • Material: PLA (standard), flexible filament for finger contact points
  • Layer Height: 0.2mm recommended
  • Infill: 20-30% for structural components
  • Supports: Required for overhangs

Hardware Integration:

  • 3x miuzei ms18 micro servos (9g)
  • ESP32 development board with custom mounting
  • M2/M3 screws for servo mounting
  • Wearable splint integration for patient comfort

[Future Sensor Integration Pipeline]

Advanced Sensor Ecosystem The system architecture is designed for comprehensive sensor integration:

Incoming Hardware Enhancements:

🔬 Pressure Sensors: 20g~2kg High Resistance Type Thin Film Pressure Sensor

  • Force measurement and safety limits
  • Real-time pressure feedback
  • Grip strength assessment

📐 Motion Tracking: GY-521 MPU-6050 (3-axis gyroscope + 3-axis accelerometer)

  • Precise movement analysis
  • Range of motion tracking
  • Movement quality assessment

❤️ Biometric Monitoring: GY-MAX30102 Heart Rate Pulse Oximetry Sensor

  • Patient vital sign monitoring
  • Therapy intensity optimization
  • Safety monitoring during sessions

InfluxDB Integration for High-Frequency Data:

// Future sensor data structure
sensor_readings,device=ESP32_001,sensor=heart_rate value=72,quality=0.95
sensor_readings,device=ESP32_001,sensor=motion_x value=0.15,quality=1.0
sensor_readings,device=ESP32_001,sensor=pressure value=150.5,quality=0.88

Enhanced Analytics Pipeline:

  • Real-time sensor fusion
  • Machine learning integration for adaptive therapy
  • Predictive analytics for therapy optimization
  • Advanced safety monitoring with automatic intervention

[Major Project Challenges Overcome]

Challenge 1: BLE Connection Reliability

The Problem: Initial BLE connections were unstable, with frequent disconnections and pairing issues.

The Solution:

  • Implemented proper connection state management
  • Added automatic reconnection logic
  • Created a streamlined pairing process (forget → scan → connect)
  • Enhanced error handling with user-friendly feedback

Code Evolution:

// Before: Basic connection attempt
await device.connect();

// After: Robust connection with state management
const connectToDevice = async (device) => {
try {
    await device.connect();
    await new Promise(resolve => setTimeout(resolve, 1000)); // Stabilization delay
    await device.discoverAllServicesAndCharacteristics();
    // Connection monitoring and error recovery
} catch (error) {
    // Comprehensive error handling and retry logic
}    };

Challenge 2: Power Management & Servo Control

The Problem: Simultaneous servo operation caused power instability and ESP32 resets.

The Solution:

  • Implemented staggered movement patterns to reduce peak current draw

  • Added power-optimized timing with configurable delays

  • Created interruptible sequences for immediate response

  • Used FreeRTOS task notifications for efficient coordination

  • Enhanced with individual servo performance tracking

Challenge 3: Real-time Data Architecture

The Problem: Designing a scalable data pipeline for clinical-grade analytics.

The Solution:

  • Docker containerization for reliable deployment

  • MQTT protocol for real-time communication

  • MariaDB for session management and historical data

  • Grafana for professional clinical visualization

  • WebSocket integration for live dashboard updates

  • Modular architecture supporting future InfluxDB integration

Challenge 4: Session Management Complexity

The Problem: Implementing automatic session tracking with manual control.

The Solution:

// Automatic session creation on BLE connection
void onBLEConnect() {
    sessionManager.startSession("BLE_CONNECTED");
    // Automatic data logging begins
}

// Manual session termination via mobile app
void handleEndSessionCommand() {
    sessionManager.endSession("USER_REQUESTED");
    // Comprehensive session analytics generated
}

Challenge 5: Cross-Platform Development Complexity

The Problem: Managing ESP32 firmware, mobile app, and backend infrastructure simultaneously.

The Solution:

  • PlatformIO for ESP32 development with proper dependency management
  • Expo for React Native with streamlined Android builds
  • Docker Compose for one-command backend deployment
  • Comprehensive documentation with DATABASE_QUERIES.md reference
  • Modular architecture allowing independent development and testing

Technical Achievements & Metrics


Performance Improvements

| Metric | Arduino Original | ESP32 Current | Improvement |

|——————|————————–|—————————————–|————-

Response Time ~500ms (button debounce) <100ms (BLE command) 5x faster
Control Range 0m (wired) ~10m (BLE) Infinite improvement
Power Efficiency Basic on/off Optimized patterns 40% reduction
Code Complexity 160 lines 2000+ lines Structured & maintainable
User Interface 1 button, 2 LEDs Full mobile app + web dashboard Revolutionary
Physical Size Large breadboard Minimal wiring + 3D printed 60% size reduction
Data Logging None Real-time MQTT + analytics Professional grade
Session Tracking Manual counting Automatic with clinical metrics Clinical ready
Comparison Chart. The chart formats strangely from time to time between updates.

Modern Development Practices Implemented

Version Control: Git with comprehensive commit history
Documentation: README, SERVER_SETUP.md, DATABASE_QUERIES.md
Testing: Hardware validation, mobile app testing, Docker deployment
Error Handling: Comprehensive debugging and recovery across all systems
Code Quality: Modular C++ architecture, TypeScript for mobile development
Infrastructure: Professional Docker deployment with analytics
Clinical Standards: Grafana dashboards suitable for medical documentation

Real-World Impact & Applications

Rehabilitation Technology This evolution demonstrates key principles applicable to medical device development:

Miniaturization: 3D printed components for patient comfort
Wireless Control: Enabling therapist control from optimal positions
Real-time Analytics: Comprehensive movement tracking for clinical assessment
Session Management: Professional therapy session documentation
Scalability: Architecture supports additional sensors and actuators
Clinical Integration: Grafana dashboards for medical documentation
Safety Monitoring: Real-time system health and performance tracking

IoT Integration Achievements

The ESP32 platform delivers advanced IoT capabilities:

  • Real-time Data Pipeline: MQTT → MariaDB → Grafana analytics
  • Professional Dashboards: Clinical-grade visualization and reporting
  • Sensor Ecosystem: Architecture ready for pressure, motion, and biometric sensors
  • Cloud Connectivity: Scalable infrastructure for remote monitoring
  • Machine Learning Ready: Data pipeline supports AI integration
  • Multi-device Support: Architecture supports coordinated bilateral therapy

Development Process & Methodology

Iterative Engineering Approach

  • Requirements Analysis: Understanding limitations of Arduino approach
  • Technology Research: Evaluating ESP32 capabilities and BLE protocols
  • Proof of Concept: Basic ESP32 servo control validation
  • Mobile Development: React Native app with BLE integration
  • Infrastructure Development: Docker analytics pipeline implementation
  • Integration Testing: End-to-end system validation with real-time data
  • Clinical Optimization: Grafana dashboard development for therapy assessment
  • Hardware Integration: 3D printing and wearable system design
  • Documentation: Comprehensive guides for reproducibility

Tools & Technologies Learned

Embedded Development: PlatformIO: Modern embedded development environment NimBLE: Lightweight Bluetooth Low Energy stack FreeRTOS: Real-time operating system integration ESP32 SDK: Advanced peripheral control with analytics

Mobile Development: React Native: Cross-platform mobile development TypeScript: Type-safe JavaScript development Expo: Streamlined mobile app deployment BLE Integration: react-native-ble-plx library

Backend Infrastructure: Docker: Containerized deployment and orchestration MQTT: Real-time IoT communication protocol MariaDB: Relational database for session management Grafana: Professional analytics and visualization Node.js: Web dashboard and API development

Development Tools: VS Code: Unified development environment Git: Version control and collaboration Serial Monitoring: Real-time debugging Android Studio: Mobile app testing and deployment 3D Printing: Custom hardware design and fabrication


Future Roadmap & Scalability

Immediate Enhancements

iOS Support: Expanding mobile app compatibility
Advanced Sensors: Pressure, motion, and biometric integration
InfluxDB Migration: High-frequency sensor data storage
Machine Learning: Adaptive therapy pattern optimization
Multi-language Support: Internationalization for global deployment

Advanced Features

AI Integration: Machine learning for personalized therapy protocols
Cloud Platform: Remote monitoring and multi-clinic analytics
Sensor Fusion: Comprehensive movement and biometric analysis
Safety Systems: Advanced emergency stop and limit detection
Bilateral Coordination: Multi-device synchronized therapy

Production Considerations

Medical Certification: FDA/CE compliance pathway development
Manufacturing: PCB design and professional enclosure development
Quality Assurance: Automated testing and validation protocols
Clinical Trials: Evidence-based therapy effectiveness validation
User Training: Comprehensive documentation and certification programs

Key Takeaways & Learning Outcomes

Technical Skills Developed

Advanced Embedded Systems: ESP32 with FreeRTOS multitasking
IoT Architecture: Complete data pipeline from device to analytics
Wireless Communication: BLE protocol implementation and optimization
Mobile Development: Cross-platform app creation with real-time features
Infrastructure Management: Docker containerization and deployment
Data Analytics: Clinical-grade visualization and reporting systems
3D Design: Custom hardware components and wearable integration

Engineering Principles Applied

Iterative Development: Continuous improvement methodology
User-Centered Design: Focusing on end-user experience and clinical needs
Performance Optimization: Balancing features with efficiency and power management
Scalable Architecture: Building for future expansion and sensor integration
Documentation: Ensuring reproducibility and maintenance with comprehensive guides
Clinical Standards: Meeting medical device development requirements

Problem-Solving Approach

Root Cause Analysis**: Understanding fundamental limitations and requirements
Technology Evaluation**: Selecting appropriate tools and platforms for each component
Systematic Testing**: Validating each component and integration thoroughly
User Feedback**: Incorporating real-world usage insights and clinical requirements
Continuous Learning**: Adapting to new technologies and evolving requirements

Conclusion: From Prototype to Production

This project represents more than just a hardware upgrade—it’s a complete transformation that demonstrates modern embedded systems development principles with clinical-grade analytics. By migrating from Arduino to ESP32 with FreeRTOS, implementing BLE communication, creating a sophisticated mobile interface, and building comprehensive data infrastructure, we’ve created a system that’s not only more capable but also more maintainable, scalable, and clinically relevant.

The journey from a breadboard prototype to a professional IoT rehabilitation device showcases the power of modern development tools, methodologies, and data-driven approaches. Every challenge overcome—from BLE connection stability to real-time analytics implementation—has resulted in a more robust and professional solution suitable for clinical environments.

This evolution serves as a blueprint for transforming any embedded prototype into a production-ready system with comprehensive analytics, demonstrating the value of continuous learning, modern tooling, user-focused design, and data-driven insights in engineering excellence.

For technical details, source code, setup instructions, and complete analytics reference, visit the GitHub repository.

Technologies Used: ESP32, FreeRTOS, NimBLE, React Native, TypeScript, PlatformIO, Expo, BLE Protocol, Servo Control, Mobile Development, IoT Integration, Docker, MQTT, MariaDB, Grafana, Real-time Analytics, 3D Printing, Clinical Data Visualization