G12: Body Composition Analyzer - shalan/CSCE4301-WiKi GitHub Wiki

Body Composition Analyzer

Name GitHub
Mostafa Elshamy MoShamy
Ahmed Elkhodary aae121
Kareem Sayed kareems394

Github Repo: https://github.com/MoShamy/Body-Composition

Presentations

1. The Proposal

Abstract / Elevator Pitch:

Knowing the composition of your body is essential to understanding your health, and achieving your fitness goals. Most people's home scales do nothing more than telling you your weight, were trying to take this to the next level. Our Body Composition Analyzer seeks to give users a more complete understanding of their body, by determining their Body Fat percentage, Total Body Water, Skeletal Muscle Mass, and other vital metrics for physical health.

Based on the ESP32 Microcontroller, our system will utilise an AC current modulator and sensor (combined with an instrumentation amplifier) to measure bodily impedence, a load cell (and subsequent ADC) to measure weight, and an ultrasonic sensor to measure height. Via a mobile app, using bluetooth, the user will be able to input their age and sex, and will be displayed the derived metrics, obtained from the measured sensory data points. The program will be running on the ESP32's built in RTOS: FreeRTOS.

To initiate the process, the user will enter the required information into the laptop, then stand on the scale. Metal electrodes will then be attached to their hands, and the ultrasonic sensor at a distance above. Once measurments are taken, and metrics generated, the GUI will present the values to the user.

Project Objectives & Scope:

Minimum Viable Product

  • Calibrated weight acquisition subsystem utilizing a load cell interfaced through an ADC, ensuring stable and repeatable mass measurements

  • Bioelectrical impedance measurement module based on controlled AC excitation and differential voltage sensing via an instrumentation amplifier, enabling extraction of raw impedance values

  • Host-assisted user input interface (via laptop) for acquisition of static parameters (age, sex, and manually entered height), reducing on-device sensing complexity

  • Embedded computation of Body Fat Percentage using established empirical models, integrating sensor data with user-provided parameters

  • Real-time data handling and communication implemented on the ESP32 using FreeRTOS, with task-level separation for sensing, processing, and UART-based data transmission to a host display interface

Stretch Goals

  • Automated height estimation subsystem using an ultrasonic sensor, enabling full on-device anthropometric data acquisition

  • Extended body composition analysis including metrics such as Total Body Water, Skeletal Muscle Mass, and BMI through enhanced modeling

  • Advanced user interface and data management, including a graphical dashboard and potential logging of historical measurements for trend analysis

2. System Architecture

2.1 High-Level Block Diagram:

Block Diagram

Subsystem Breakdown:

Subsystem Connection Protocol Description
Ultrasonic Sensor GPIO: TRIG, ECHO Height measurment module, that measures height by emmiting a high frequency sound, recieving it's echo, and using the intermediate time to determine distance travelled
Load Cell Bit Banging Measures weight of user
Body Impedence Circuit GPIO: Goertzel's DFT Measures the bodily impedence by using the MCUs built in ADC and DAC. A low current signal is sent into the body, and the echo measured, filtered and transformed, then used to calculate bodily impedence.
Mobile App Bluetooth Acts as the user interface for the system. Users enter their Age and Sex, sends a start signal to the MCU (begins measurments), recieves progress/status feedback for a progress bar loading screen, then recieves measurments and metrics, and displays them to the user.

3. Hardware Design

Component Selection:

Blank diagram

Schematics & Wiring:

Circuit diagrams, pinout tables, and breadboard layouts. Circuit diagram BIA Circuit:

BIA Circuit Diagram

Bill of Materials (BOM)

Component Part Number / Model Quantity Estimated Cost (2026) Local Store Link Datasheet
ESP32 Development Board ESP32 30-pin WiFi + Bluetooth Dev Board 1 260 EGP Future Electronics Egypt ESP32-WROOM-32 Datasheet
Operational Amplifier LM358P (Original) Dual Operational Amplifier 1 10 EGP RAM Electronics LM358P Datasheet
Load Cell 100kg Strain Gauge Load Cell 1 750 EGP RAM Electronics 100kg Load Cell Datasheet
HX711 Load Cell ADC HX711 24-bit ADC Module 1 75 EGP RAM Electronics HX711 Datasheet
Instrumentation Amplifier AD620AN 1 160 EGP Future Electronics Egypt AD620AN Datasheet
Ultrasonic Sensor HC-SR04 Ultrasonic Sensor Module 1 55 EGP Future Electronics Egypt HC-SR04 Datasheet
ECG Electrodes Ag/AgCl Disposable ECG Electrodes 3 30 EGP total Future Electronics Egypt
Breadboard 840-pin Breadboard 1 35 EGP RAM Electronics
Resistors Carbon Resistors of a variety of resistances Several 10 EGP Future Electronics Egypt
Capacitors 100nF Ceramic/electrolytic capacitors 2 1 EGP RAM Electronics 100nF Ceramic Capacitor Datasheet

Estimated Total ≃ 2,000 EGP

Power Budget:

Peak Current required per part:

Part Est. Peak Current Drawn (mA)
ESP32 Dev Board 240
LM358P 1.5
100kg Load Cell 3
HX711 1.5
AD620AN 1.3
HC-SR04 15
Total 262.3

Considering possible fluctuations, it would be sensible to round up to 300mA.

At an input of 5v, this would require 1.5 Watts of instantaneous power.

4. Software Implementation

Software Architecture:

This project runs on FreeRTOS (native to ESP).

Task structure:

  • app_main() initializes the sensors, BLE stack, and measurement manager
  • ble_service_init() brings up NimBLE, configures the GATT service, and starts advertising
  • ble_host_task() runs the NimBLE event loop
  • measurement_manager waits for a BLE start command and runs the weight, height, and BIA cycle

BLE control plane:

  • Device name: BodyComp
  • Primary service UUID: 12345678-1234-5678-1234-567812345678
  • Characteristics:
    • User Profile: read/write age and sex
    • Measurement Start: write 0x01 to trigger a measurement
    • Status: read/notify state, error code, and progress
    • Result: read/notify weight, height, impedance, body fat percentage, and FFM

User Flowcharts:

User_Flowchart

Key Algorithms:

Goertzel Algorithm (Single-Bin DFT)

The core measurement algorithm for bioelectrical impedance analysis. It extracts the amplitude of a specific frequency component (50 kHz) from digitally sampled ADC data with minimal computational overhead.

Purpose: Isolate the 50 kHz AC current response signal from the body impedance measurement, rejecting noise at other frequencies.

How it works:

  • Uses a recursive feedback resonator with three state variables (q0, q1, q2)
  • For each ADC sample, applies: q0 = coeff·q1 - q2 + x[i], then updates q2 and q1
  • After processing all samples, computes magnitude: amplitude = √(real² + imag²) where:
    • real = q1 - q2·cos(ω)
    • imag = q2·sin(ω)
    • ω = 2π·f_target·n / f_sample

Why we used it in our Embedded System:

  • O(n) complexity instead of O(n log n) for FFT
  • Single-frequency focus eliminates unnecessary computation
  • Minimal memory footprint ideal for ESP32 constraints
  • Real-time capable with FreeRTOS task timing

Implementation in project:

  • Processes 1024 ADC samples at 200 kHz sample rate (5.12 ms window)
  • Measures impedance at injection frequency (50 kHz)
  • Output amplitude directly converts to body impedance via Ohm's law and AD620 instrumentation amplifier gain

Body Composition Equations

Deurenberg Single-Frequency BIA Model:

FFM (kg) = -12.44 + 0.34·(H²/Z) + 0.1534·H + 0.273·W - 0.127·A + 4.56·S

Where:

  • H = height (cm)
  • Z = impedance (Ω)
  • W = weight (kg)
  • A = age (years)
  • S = sex (1=male, 0=female)

Body Fat Percentage:

BF% = (W - FFM) / W × 100

Skeletal Muscle Mass (SMM):

SMM (kg) = ((height² / R) × 0.401) + (sex × 3.825) - (age × 0.071) + 5.102

Total Body Water (TBW) — Watson Formula:

Male:   TBW = 2.447 - (0.09516 × age) + (0.1074 × height) + (0.3362 × weight)

Female: TBW = -2.097 + (0.1069 × height) + (0.2466 × weight)

Watson PE, Watson ID, Batt RD. Total body water volumes for adult males and females estimated from simple anthropometric measurements. American Journal of Clinical Nutrition, 1980.

Basal Metabolic Rate (BMR) — Mifflin-St Jeor Equation:

Male:   BMR = (10 × weight) + (6.25 × height) - (5 × age) + 5

Female: BMR = (10 × weight) + (6.25 × height) - (5 × age) - 161

Janssen I, Heymsfield SB, Baumgartner RN, Ross R. Estimation of skeletal muscle mass by bioelectrical impedance analysis. Journal of Applied Physiology, 2000.

Used for converting raw impedance measurement into clinically relevant body composition metrics.

Development Environment:

ESP-IDF 6.1.0, ESP32 toolchain, FreeRTOS, and NimBLE BLE stack. Development and validation were done from VS Code with the ESP-IDF extension, and iPhone-side testing used nRF Connect as the BLE client. Mobile app development using Flutter & Dart.

5. Testing, Validation & Debugging

Unit Testing:

How individual hardware components and software functions were tested in isolation.

Load Cell + HX711

  • Connected load cell to HX711 and HX711 to ESP32 (DT → D19, SCK → D22)
  • Placed known weights (1kg, 2kg) on the load cell
  • Verified raw ADC counts scaled linearly with weight
  • Applied tare() function to confirm zero offset on empty scale
  • Pass criteria: reading within ±0.5kg of actual weight after calibration

HC-SR04 Ultrasonic Sensor

  • Connected HC-SR04 to ESP32 (TRIG → D18, ECHO → D21)
  • Held a flat surface at known distances (30cm, 50cm, 100cm, 150cm, 170cm)
  • Verified distance formula: distance = (duration × 0.034) / 2
  • Pass criteria: reading within ±1cm of actual distance

BIA Circuit

  • Tested DAC output on GPIO25 with oscilloscope
  • Tested AD620AN amplifier in isolation using a known resistor (1kΩ) instead of body
  • Replaced body with known resistors (200Ω, 500Ω, 1kΩ) and confirmed impedance calculation matched
  • Pass criteria: impedance reading within ±10% of known resistor value

Virtual GND (2.5V Rail)

  • Measured voltage at the R4/R5 divider node with a multimeter
  • Confirmed stable 2.5V ± 0.1V under load
  • Verified AD620 REF pin (pin 5) sits at 2.5V

Goertzel Algorithm

  • Processes 1024 samples at 200 kHz = 5.12 ms window
  • Verified amplitude extraction at 50 kHz matches expected value
  • Confirmed rejection of off-frequency noise components
  • Pass criteria: amplitude error < 5% on clean signal, stable under 10% added noise

BLE Communication

  • Confirmed device advertises as BodyComp via nRF Connect
  • Wrote age/sex to User Profile characteristic, verified readback
  • Triggered measurement via 0x01 write, confirmed task unblocked
  • Verified Result characteristic contains all expected metrics
  • Pass criteria: all characteristics R/W, notifications received

Integration Testing:

How the system was tested as a whole.

Test 1: BLE Connection + User Input

  • Connected iPhone to BodyComp via nRF Connect
  • Wrote age and sex to User Profile characteristic and verified readback
  • Pass criteria: profile characteristic readable/writable with correct values

Test 2: Weight + BIA Combined

  • Stood on load cell with electrodes attached, triggered via BLE 0x01
  • Verified both HX711 and BIA task ran concurrently without interference
  • Pass criteria: both readings present in Result characteristic

Test 3: Full Sensing Cycle

  • Triggered full cycle with user under HC-SR04, on scale, with electrodes
  • Verified measurement manager correctly sequenced all three tasks
  • Pass criteria: weight (kg), height (cm), impedance (Ω) all non-zero

Test 4: Body Composition Computation

  • Fed real sensor readings into Deurenberg model with user profile
  • Cross-checked BF% against an online BIA reference calculator
  • Pass criteria: BF% within reasonable range for test subject

Test 5: BLE End-to-End Data Flow

  • Triggered full cycle from iPhone and monitored Status notifications
  • Verified Result characteristic auto-updated via BLE notify on completion
  • Pass criteria: all metrics delivered via notify, connection stable

Challenges & Solutions:

Challenge Solution
To have the height module placed above the user, and the load cell on the ground, would require at least 2.15 meters between them. This would require lengthening the hypersonic sensors connection to the MCU significantly, risking a reduction in accuracy, as the connection protocol was only designed to be used in <20cm ranges. We place the hypersonic sensor on a table next to the user, facing upwards. The sensor measures the distance from its position to the top of the users head (by placing a plastic sheet above the user). This decreases the distance between the sensors and the MCU, thereby maintaining legitimacy of the communication protocols. The Sensor is placed on a table rather than on the ground with the load cell, as it allows for measurements to occur at a lower total distance, increasing accuracy of measurement.
AD5933 Unavailable in local market. This IC is designed to measure bodily impedance very accurately, and was initially part of our design. When it came to purchasing chips, it was sold out/unavailable across Cairo. We designed our own impedance measurement circuit (detailed above). It utilizes the ESP32’s built in ADC and DAC to produce low frequency current, and measure the echo receives. It is far less accurate, but with significant calibration, we managed to achieve stable, accurate results.

6. Results & Demonstration

Final Prototype:

Build Photo 1 Build Photo 2 Build Photo 3

Video Demonstration:

Final.Demo.mp4

Performance Metrics:

6.3 Performance Metrics


Weight Measurement

Metric Target Measured Status
Accuracy ±500g ±500g Good
Tare response Instant Instant Good

Tested with 1kg reference load. Offset corrected via calibration factor.

Height Measurement

Metric Target Measured Status
Accuracy ±2 cm ±0.5 cm Good
Tested at 50 cm 49.5 cm Good

BIA / Impedance

Metric Target Measured Status
Injection frequency 50 kHz 50 kHz Good
Measurement window 5.12 ms 5.12 ms Good
Impedance accuracy (1kΩ ref) ±10% ±8%* Good

BLE Communication

Metric Target Measured Status
Connection time < 10s ~3–5s Good
Result notify latency < 5s ~2–4s Good
Stability (10 cycles) 0 dropouts 0 dropouts Good

Full Measurement Cycle

Metric Target Measured Status
BIA window 5.12 ms 5.12 ms Good
Total cycle (trigger → result) < 10s ~5–7s Good
FreeRTOS crashes (10 cycles) 0 0 Good

7.1 Division of Labor:

Mostafa: Height Measurement Bluetooth Service Weight Measurement Integration

Kareem: Body Impedence Circuit Mobile App Weight Measurment Calibration & Testing

Ahmed: Initial System Architecture GUI Design & Literature Review (Component Selection, BIA Calculations) & Ideation

7.2 Timeline:

gantt
    title Body Composition System — Planned vs Actual Timeline
    dateFormat YYYY-MM-DD
    axisFormat %b %d
    excludes weekends


    section Planned Timeline

    Weight Measurement Module (HX711 + Load Cell) :done, p1, 2026-04-15, 5d
    Height Measurement Module (Ultrasonic) :done, p2, 2026-04-18, 7d
    BIA Integration & Validation                  :done, p3, 2026-04-28, 8d
    RTOS System Integration                       :done, crit, p4, 2026-05-04, 6d

    BLE Communication Layer                       :done, crit, p5, 2026-05-08, 5d
    Mobile App Development                        :done, crit, p6, 2026-05-10, 7d
    App ↔ ESP32 Integration & Testing             :done, crit, p7, 2026-05-14, 5d

    Final Calibration, Polish & Documentation     :done, crit, p8, 2026-05-18, 4d

    Final Project Delivery                        :milestone, m1, 2026-05-22, 0d


    section Actual Execution Timeline

    Initial Project Setup & Repository Structure  :done, a1, 2026-04-20, 3d

    Weight Measurement Module (HX711 + Load Cell) :done, a2, 2026-05-01, 3d
    Height Measurement Module (Ultrasonic) :done, a3, 2026-05-03, 4d
    BIA Circuit Integration                       :done, crit, a4, 2026-05-11, 5d

    Measurement Manager & RTOS Coordination       :done, crit, a5, 2026-05-16, 2d
    NimBLE GATT Service Integration               :done, crit, a6, 2026-05-16, 2d

    Mobile App Development & BLE Integration      :done, crit, a7, 2026-05-17, 3d

    Final Calibration, Debugging & Polish         :done, a8, 2026-05-18, 5d
    Documentation & System Finalization           :done, a9, 2026-05-21, 2d

    Final Working System                          :milestone, crit, m2, 2026-05-22, 0d
Loading

8. Appendices & References

8.1 Source Code Repository:

Repo Link

8.2 References:

Iber, D. de P. (2017). Sistema de bioimpedância para a avaliação da composição corporal [Bachelor’s thesis, Centro Universitário SOCIESC – UNISOCIESC]

⚠️ **GitHub.com Fallback** ⚠️