
A State-of-the-Art Healthcare Companion Robot
Real-time biometric monitoring · Expressive face animation · Intelligent medical assessment
Dual Architecture Support: Monolithic (Raspberry Pi 5) & Distributed v2.0 (ESP32-S3 Node + Laptop C++/Python Brain)
Created by Gabriel Calderon
Requested by Elias Bautista
https://github.com/chele-s/BaymaxMini.git
- Overview
- System Architecture
- Hardware Layer
- Mathematical Foundations
- C++ Real-Time Core & Firmware
- Python Brain (
src/python_brain) - Communication & IPC Protocols
- Build & Deploy
- Configuration
- Project Structure
BaymaxMini is a healthcare companion robot inspired by the fictional nurse-bot Baymax from Disney's Big Hero 6. It implements a hard real-time control loop in C++17 running at 50 Hz, coupled with a high-level Python brain that handles natural language understanding, computer vision, medical reasoning, and emotional intelligence.
The system supports two deployment models:
- v2.0 Distributed Architecture (Recommended): An ESP32-S3 embedded node handles deterministically timed 50 Hz I²C sensor polling, servo control, overcurrent protection, and MJPEG video streaming. A Host Laptop runs native
pybind11C++ extensions for high-precision biomedical signal analysis (HRV, FFT, stress index) and Python for AI, vision, and voice processing. - v1.0 Monolithic Architecture: Runs entirely on a Raspberry Pi 5 communicating across processes via ZeroMQ PUB/SUB.
| Domain | Capability | Implementation |
|---|---|---|
| Biometrics | Heart rate, SpO₂, skin temperature | MAX30102 PPG + MLX90614 IR thermometry |
| Proximity | Time-of-Flight distance sensing | VL53L1X SPAD array (up to 4m) |
| Expression | 10 emotions, blinks, gaze, micro-movements | PCA9685 12-channel servo via spring dynamics |
| Power | Real-time energy monitoring & protection | INA219 current/voltage sensing with hysteresis FSM |
| Vision | Person detection, face analysis | YOLOv8n (FP16) + Single-Pass Geometric Deduction |
| Audio | Speech recognition, TTS, intent parsing | Whisper STT + edge TTS |
| Medical | Health assessment, medication reminders | Rule-based clinical heuristics + patient history DB |
| Intelligence | State machine, event bus, scheduling | Finite automaton with priority event dispatch |
┌─────────────────────────────────────────────────────────────┐
│ LAPTOP BRAIN │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Python Brain (AI / UI) │ │
│ │ Vision (YOLOv8) · Audio (Whisper/TTS) · StateMachine│ │
│ └───────────────────────────┬───────────────────────────┘ │
│ │ import baymax_native │
│ ┌───────────────────────────▼───────────────────────────┐ │
│ │ baymax_native (pybind11) │ │
│ │ SerialLink (Background RX) · AdvancedVitalsAnalyzer │ │
│ └───────────────────────────┬───────────────────────────┘ │
└──────────────────────────────┼──────────────────────────────┘
│ USB Serial @ 921600 Baud (Telemetry/Cmd)
│ Wi-Fi MJPEG Stream @ Port 81 (Video)
┌──────────────────────────────▼──────────────────────────────┐
│ ESP32-S3 NODE │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ Core 1 (50 Hz Real-Time Loop) │ │
│ │ ├─ PowerSystem.update() │ │
│ │ ├─ VitalsMonitor.update() │ │
│ │ ├─ FaceController.update() │ │
│ │ └─ VL53L1X Distance Read │ │
│ │ │ │
│ │ Core 0 (Comms & Camera Task) │ │
│ │ ├─ SerialProtocol RX/TX (Checksummed binary frames) │ │
│ │ └─ CamServer (HTTP MJPEG Streaming on port 81) │ │
│ └───────────────────────────┬───────────────────────────┘ │
│ │ I²C Bus (400 kHz) │
│ ┌───────────────────────────▼───────────────────────────┐ │
│ │ PCA9685 · VL53L1X · MAX30102 · MLX90614 · INA219 │ │
│ └───────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────┐
│ Python Brain (non-RT) │
│ ┌─────────┐ ┌──────────┐ ┌────────┐ ┌───────────────────┐ │
│ │ Vision │ │ Audio │ │Medical │ │ Core Logic │ │
│ │ YOLOv8 │ │STT / TTS │ │Assess. │ │ StateMachine │ │
│ │ FaceAn. │ │IntentPrs │ │History │ │ EventBus/Sched. │ │
│ └────┬────┘ └────┬─────┘ └───┬────┘ └────────┬──────────┘ │
│ └───────────┴────────────┴───────────────┘ │
│ │ ZMQ PUB/SUB │
│ tcp://127.0.0.1:5555 (CMD ↓) │
│ tcp://127.0.0.1:5556 (TELEM ↑) │
├─────────────────────────────────────────────────────────────┤
│ C++ Real-Time Core (50 Hz) │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Orchestrator │ │
│ │ tick() → readSensors → processCmd → logic → out │ │
│ └──────┬──────────┬──────────┬────────────────────────┘ │
│ ┌──────┴───┐ ┌────┴─────┐ ┌─┴──────────┐ │
│ │ Face │ │ Vitals │ │ Power │ Modules │
│ │Controller│ │ Monitor │ │ System │ │
│ └──────┬───┘ └────┬─────┘ └─┬──────────┘ │
│ ┌──────┴──────────┴─────────┴──────────────────────┐ │
│ │ I²C Bus (400 kHz) │ │
│ │ PCA9685 · VL53L1X · MAX30102 · MLX90614 · INA219│ │
│ └──────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
| Chip | Type | Address | Function | Key Specs |
|---|---|---|---|---|
| PCA9685 | PWM Driver | 0x40 |
12-channel servo control | 12-bit resolution, 50 Hz PWM |
| VL53L1X | ToF Sensor | 0x29 |
Proximity detection | 4m range, SPAD array, ±3% accuracy |
| MAX30102 | Pulse Oximeter | 0x57 |
Heart rate + SpO₂ | Dual LED (660nm red / 880nm IR), 18-bit ADC |
| MLX90614 | IR Thermometer | 0x5A |
Contactless body temp | ±0.5°C accuracy, 0.02°C resolution |
| INA219 | Power Monitor | 0x41 |
Battery voltage/current | 12-bit ADC, ±1% current accuracy |
- Chemistry: 3S LiPo (Lithium Polymer)
- Nominal: 11.1V · Full: 12.6V · Empty: 9.0V
- Capacity: 2200 mAh
- Protection: Overcurrent 3A trip / 2.5A clear, servo stall 2A / 1.2A, shutdown at 8.5V
The core DSP primitive is a Direct Form I biquad filter, implementing the general second-order transfer function:
The difference equation computed each sample:
Coefficients are derived from the analog prototype via the bilinear transform. For a lowpass Butterworth with cutoff frequency
All coefficients are normalized by
For steeper roll-off, biquad sections are cascaded to form higher-order Butterworth filters. An $N$th-order filter uses
This ensures maximally flat magnitude response in the passband — zero ripple by construction.
Used throughout for smoothing sensor data with minimal latency:
The smoothing constant
Removes DC offset from AC-coupled signals (critical for PPG processing):
The pole at
Non-linear filter for impulse noise rejection. For three samples
Implemented via a sorting network (3 conditional swaps) for branchless execution.
Constrains the rate of change to protect servo mechanisms:
To eliminate catastrophic cancellation and rounding drift in continuous real-time execution, vital trigonometry and constants strictly leverage boost::math. Phase calculations use exact boost::math::sin_pi() evaluating at the absolute bit-level limit of the hardware architecture.
Real-time PPG signal quality tracking utilizes boost::accumulators::accumulator_set, extracting the rolling mean and variance of human vitals in a strictly
The MAX30102 outputs raw photon count data from red (660nm) and infrared (880nm) LEDs. The full signal processing chain:
Raw IR/Red → Median₃ → DC Removal → Butterworth LPF (5 Hz) → Peak Detection → BPM
A composite quality score determines reading validity:
Where:
The ratio score validates adequate perfusion (AC/DC > 0.02), while the stability score penalizes high coefficient of variation.
Heart beats are detected via zero-crossing of the signal slope with a refractory period and adaptive threshold:
- Refractory guard: Ignore peaks within 300ms of the last detection
-
Slope analysis: detect sign change
$\text{slope}_{n-1} > 0 \land \text{slope}_n \leq 0$ -
Adaptive threshold:
$\tau[n] = 0.7 \cdot \tau[n-1] + 0.3 \cdot \text{peak amplitude}$ -
Threshold decay:
$\tau[n] \leftarrow 0.998 \cdot \tau[n]$ (adapts to signal loss) -
BPM computation:
$\text{BPM} = \frac{60 \cdot f_s}{\Delta_{\text{samples}}}$ , smoothed with EMA ($\alpha = 0.3$ )
All servo channels (eyelids, gaze, brows, cheeks) are driven by critically damped spring dynamics, ensuring smooth, natural motion without overshoot:
The exact closed-form solution for each timestep
This provides:
-
Zero overshoot (critically damped:
$\zeta = 1$ ) -
Exponential convergence at rate
$\omega$ (default$\omega = 12$ rad/s) - Exact integration — no numerical drift regardless of timestep
The SpringAnimator further extends this with configurable damping ratios for underdamped (
A procedural animation system providing frequency-controlled, stability-guaranteed smoothing with anticipation:
Where the constants derive from desired natural frequency
The
Cubic Hermite interpolation between two points
With basis functions:
A special case of Hermite interpolation with auto-computed tangents:
Hermite-basis polynomial interpolation with clamped input:
| Family | Mathematical Form |
|---|---|
| Sine | |
| Quadratic | |
| Cubic | |
| Quartic | |
| Quintic | |
| Exponential | |
| Circular | |
| Back | |
| Elastic | |
| Bounce | Piecewise parabolic with |
Each family provides in, out, and inOut variants (30 total), plus smoothstep and smootherstep.
CSS-style timing functions via parametric cubic Bézier
Given a target
Pre-built presets: easeInOut, snappy, organic, overshoot, rubberBand, anticipate, heavyLanding.
Estimated via a piecewise-linear lookup table against cell voltage, derived from empirical Li-ion discharge curves:
| Cell V | 3.00 | 3.30 | 3.50 | 3.60 | 3.70 | 3.75 | 3.80 | 3.85 | 3.95 | 4.10 | 4.20 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| SoC % | 0 | 5 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 90 | 100 |
Cell voltage derived from bus voltage:
All protection thresholds use Schmitt-trigger hysteresis to prevent chattering:
┌─────────────────┐
│ INACTIVE │
│ │ value > trip_threshold
│ ────────────► │──────────────────────►┐
│ │ │
└─────────────────┘ ▼
▲ ┌──────┴─────┐
│ value < clear_threshold│ ACTIVE │
└─────────────────────────│ │
└─────────────┘
Blood oxygen saturation is derived from the ratio of ratios (R) of the red and infrared PPG signals:
SpO₂ is then estimated via the empirically calibrated linear approximation:
This derives from the Beer-Lambert law of optical absorption:
Where
The INA219 current sense amplifier requires precise register calibration:
With the configured
Servo angle
Default range:
At $f_{\text{PWM}} = 50$Hz:
Built with PlatformIO for ESP32-S3 (Dual-Core LX7 @ 240MHz, 8MB PSRAM, 16MB Flash):
- Core 1: Dedicated real-time 50 Hz FreeRTOS tick loop for I²C sensor reading, spring-damper facial servo kinematics, power hysteresis FSM, and overcurrent protection.
- Core 0: Asynchronous serial communication handling binary
TelemetryFrame/CommandFramepackets at 921600 baud, plus an HTTP MJPEG camera server on port 81 (CamServer.h). - Autonomous Mode: Automatic fallback when the host brain disconnects or times out (> 2s), executing organic blinks, eye jitter, and low-battery sleep routines.
SerialLink: Multi-platform serial port driver (Win32 COM API & Linuxtermios) running a background thread for zero-latency frame reception at 921600 baud.AdvancedVitalsAnalyzer: High-performance biomedical signal processing using Boost (HRV analysis: SDNN, RMSSD, pNN50, LF/HF ratio, Stress Index).baymax_native: Exposes C++ classes directly to Python usingpybind11.
The core runs a fixed-timestep loop at 50 Hz ($\Delta t = 20$ms) with overrun detection:
while (running) {
nextTick += 20ms
readSensors() ─► I²C reads from all 5 chips
processCommands() ─► Serial RX / ZMQ SUB (non-blocking)
updateLogic() ─► FSM + spring dynamics + animation
writeOutputs() ─► Telemetry TX / ZMQ PUB + servo PWM
sleep_until(nextTick)
if (overrun > 3 ticks) { resync; overrun_count++ }
}
BOOT ──(Connected)──────► CONNECTED ──(brain timeout 2s)──► AUTONOMOUS
▲ ▲ │
│ └──────(CMD received)──────────────┘
│
└──────────────────── SHUTDOWN ◄──(SIGINT/SIGTERM or critical battery)
Manages 12 servo channels mapped to facial features via spring-damped dynamics:
| Channel | Servo | Feature | Spring ω |
|---|---|---|---|
| 0-1 | Left eyelids | Upper/Lower lid | 12 rad/s |
| 2-3 | Right eyelids | Upper/Lower lid | 12 rad/s |
| 4-5 | Left gaze | Horizontal/Vertical | 12 rad/s |
| 6-7 | Right gaze | Horizontal/Vertical | 12 rad/s |
| 8-9 | Cheeks | Left/Right raise | 12 rad/s |
| 10-11 | Brows | Left/Right position | 12 rad/s |
10 Expression Poses: Neutral, Happy, Sad, Surprised, Angry, Sleepy, Concerned, Curious, Love, Thinking — each defined as a target pose for all 12 channels with smooth spring-interpolated transitions.
Blink System: Asymmetric timing modeled after human physiology — close: 75ms, hold: 35ms, open: 130ms, ratio 1.73:1 (close:open speed). Auto-blinks at 2-6s intervals with 18% variance.
Micro-Movements: Continuous subtle animation to avoid the uncanny valley:
- Gaze jitter: 0.02 amplitude, 0.3 Hz
- Gaze drift: 0.05 amplitude, 0.08 Hz
- Lid twitch: 0.015 amplitude, 0.15 Hz
- Brow drift: 0.01 amplitude, 0.06 Hz
State machine for clinical-grade vital sign acquisition:
IDLE → DETECTING_FINGER → STABILIZING (2s) → MEASURING (5-10s) → COMPLETE
↓
ERROR_NO_FINGER / ERROR_POOR_SIGNAL
Health assessment heuristics:
| Condition | Threshold | Assessment |
|---|---|---|
| Normal HR | 50-110 BPM | NORMAL |
| Tachycardia | > 110 BPM | ELEVATED_HR |
| Bradycardia | < 50 BPM | LOW_HR |
| Hypoxemia | SpO₂ < 95% | LOW_SPO2 |
| Fever | > 38.0°C | FEVER |
| Hypothermia | < 36.0°C | HYPOTHERMIA |
| Critical | HR < 40 or > 180, SpO₂ < 90% | CRITICAL |
Real-time energy management with multi-layered protection:
- EMA-filtered voltage, current, power readings
-
Coulomb counting for energy accumulation:
$E += P \cdot \Delta t$ - 7-state FSM: NOMINAL → LOW_BATTERY → CRITICAL → OVERCURRENT → SERVO_STALL → OVERTEMP → SHUTDOWN
- Callbacks for face alert mode and emergency shutdown
| Subsystem | Modules | Purpose |
|---|---|---|
| core | brain.py, event_bus.py, logger.py |
Central coordinator, pub/sub events, structured logging |
| vision | camera.py, detector.py, face_analyzer.py, object_detector.py |
Single YOLOv8n FP16 orchestrator, HTTP MJPEG stream + USB webcam fallback |
| audio | stt_engine.py, tts_engine.py, intent_parser.py, sound_fx.py, audio_alerts.py |
Speech-to-text, text-to-speech, NLU intent extraction, sound effects |
| medical | patient_history.py, pharmacist.py, scheduler.py |
Patient records, medication database, reminder scheduling |
| communication | esp32_link.py, zmq_link.py, telemetry.py |
baymax_native bridge to ESP32 node / ZeroMQ bridge to Pi 5 core |
| logic | state_machine.py, scheduler.py |
Behavioral FSM, task scheduling |
| config | settings.py, db_migrate.py |
YAML config loader, database migrations |
| utils | time_utils.py |
Timezone-aware time helpers |
High-speed packed binary protocol aligned to 4-byte boundaries with additive checksum validation:
| Frame Type | Magic Number | Size | Direction | Frequency |
|---|---|---|---|---|
| TelemetryFrame | 0xBABE0001 |
96 bytes | ESP32 → Laptop | 50 Hz |
| CommandFrame | 0xBABE0002 |
44 bytes | Laptop → ESP32 | On Command |
| SystemStatus | 0xBABE0003 |
32 bytes | ESP32 → Laptop | 1 Hz |
| Heartbeat | 0xBABE0004 |
16 bytes | Bidirectional | 2 Hz |
For the Raspberry Pi 5 monolithic deployment, inter-process communication uses ZeroMQ sockets:
tcp://127.0.0.1:5555: Python → C++ commandstcp://127.0.0.1:5556: C++ → Python 50 Hz telemetry frame publishing
cd firmware/esp32_baymax_node
pio run -t uploadmkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Releasepython -m src.python_brain.mainsudo apt-get install build-essential cmake libzmq3-dev nlohmann-json3-dev
pip install pyzmq pyyaml numpy opencv-python-headless tflite-runtimemkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
make -j$(nproc)
# Run C++ Core and Python Brain
./build/baymax_core &
python3 src/python_brain/main.py| File | Purpose |
|---|---|
configs/system.yaml |
v2.0 global settings (Serial COM port, baud rate, Wi-Fi MJPEG URL) |
configs/sensors_config.yaml |
I²C addresses, sample rates, filter parameters |
configs/vision_params.yaml |
YOLO confidence thresholds, camera resolution |
configs/reminders.json |
Medication and appointment schedule |
BaymaxMini/
├── CMakeLists.txt
├── README.md
├── SCHEMATIC_ESP32.md
├── requirements.txt
├── configs/
│ ├── system.yaml v2.0 System configuration
│ ├── sensors_config.yaml I²C addresses & sensor tuning
│ ├── vision_params.yaml YOLO & camera thresholds
│ └── reminders.json Medication schedule
├── models/
│ └── yolo_nano_int8.tflite YOLO model
├── firmware/ v2.0 ESP32-S3 Firmware Node
│ └── esp32_baymax_node/
│ ├── platformio.ini PlatformIO config
│ ├── include/
│ │ ├── Config.h Hardware constants & pinouts
│ │ ├── SerialProtocol.h 921600 baud serial protocol
│ │ └── CamServer.h HTTP MJPEG camera server
│ ├── lib/ Ported hardware & logic libraries
│ │ ├── FaceController/
│ │ ├── I2CBus/
│ │ ├── INA219/
│ │ ├── MAX30102/
│ │ ├── MLX90614/
│ │ ├── MathUtils/
│ │ ├── PCA9685/
│ │ ├── PowerSystem/
│ │ ├── SharedData/
│ │ ├── VL53L1X/
│ │ └── VitalsMonitor/
│ └── src/
│ └── main.cpp Dual-Core FreeRTOS orchestrator
└── src/ Laptop Source Code
├── cpp_core/ Native C++ Core & PyBind11
│ ├── analysis/ HRV & Biomedical analysis
│ │ ├── AdvancedVitalsAnalyzer.h
│ │ └── AdvancedVitalsAnalyzer.cpp
│ ├── bindings/ pybind11 Python extension
│ │ └── baymax_native.cpp
│ ├── serial/ Cross-platform Serial link
│ │ ├── SerialLink.h
│ │ └── SerialLink.cpp
│ ├── interfaces/ Abstract I_Sensor interface
│ ├── ipc/ Binary SharedData structures
│ └── utils/ MathUtils, DigitalFilter, Easing
└── python_brain/ Python AI & Reasoning Layer
├── main.py Brain entry point
├── core/ Event bus, state, logging
├── vision/ Camera, YOLO, face analysis
├── audio/ STT, TTS, intent parsing
├── medical/ Patient history, meds
├── communication/ esp32_link.py
├── logic/ Behavioral state machine
├── config/ Settings, DB migration
└── utils/ Time utilities
"Hello. I am Baymax, your personal healthcare companion."