Skip to content

G15: Human stress support system

Ismaiel Sabet edited this page May 20, 2026 · 37 revisions

Project Title: Human stress support system

Name GitHub
Ismaiel Sabet IsmaielSemo
Islam Abdeen Islamauc
Shaza Ali ShazaAli

Initial Proposal Presentation

Progress Presentation

Final Presentation

1. The Proposal

Abstract / Elevator Pitch

Stress is one of the most pervasive health challenges in academic and professional environments, yet it remains entirely invisible to the surrounding system. Most people only recognize they are stressed after the fact that performance has already degraded or focus has slipped.

The system uses the sensor MAX30102 (a photoplethysmography sensor) to capture pulse waveforms from the fingertip or wrist. These signals are then processed on the STM32L432KC (an embedded microcontroller) to extract Heart rate variablity features that are correlated with stress. The system was built to demonstrate a low-power, low-cost embedded health-monitoring pipeline that bridges biosignal acquisition, real-time DSP, behavioral feedback, and wireless communication, all running on a single microcontroller with BLE event logging to a smartphone terminal.


Project Objectives & Scope

Minimum Viable Product (MVP)

  • Acquire a clean PPG signal using the MAX30102 sensor
  • Interface the sensor with STM32L432KC via I2C
  • Apply DSP signal processing to detect pulse peaks and compute inter-beat intervals
  • Implement system control logic: if stressed → enable Breathing Mode; else → Monitor
  • Drive a breathing guide on OLED and buzzer with breathing pattern and musical tone when stress is detected
  • Transmit event logs wirelessly via BLE Bluetooth Module over UART to a smartphone terminal
  • Power the full system from a regulated 3.7V LiPo battery with onboard LDO regulation to 3.3V
  • Implement adaptive thresholding for stress detection to personalize sensitivity per user
  • Add historical HRV trending and session summaries over BLE
  • Develop a dedicated mobile app (beyond a serial terminal) for data visualization

Stretch Goals

  • Implement low-power sleep modes between ADC samples to extend battery life
  • Add SD card or flash logging for offline session data storage

2. System Architecture

2.1 High-Level Block Diagram:

image

2.2 Subsystem Breakdown

1. MAX30102 PPG Sensor

The MAX30102 is a highly integrated, dual-wavelength optical sensor module designed for pulse oximetry and heart-rate monitoring applications. Manufactured by Maxim Integrated, the device embeds an unmodulated optical subsystem, digital conversion circuitry, and an automated communication interface within a single $5.6\text{ mm} \times 3.3\text{ mm} \times 1.55\text{ mm}$ 14-pin optical module.

A. Internal Physical Layout & Optical Subsystem

The internal architecture of the chip consists of two distinct silicon subsystems mounted on a shared substrate beneath an optically transparent glass window: the LED Transmitter Array and the Receiver/Digitizer Processing Core.

  • LED Transmitter Array: Contains two specialized semiconductor emitters. A Red LED with a dominant peak wavelength of $660\text{ nm}$ ($\pm 15\text{ nm}$ spectral bandwidth) for tracking deoxyhemoglobin ($Hb$), and an Infrared (IR) LED with a peak wavelength of $880\text{ nm}$ ($\pm 15\text{ nm}$ spectral bandwidth) for isolating oxyhemoglobin ($HbO_2$).
  • Receiver Front-End: Comprises a single integrated silicon photodiode tailored for maximum quantum efficiency across the $600\text{ nm} \text{ to } 950\text{ nm}$ band, protected by an ambient light rejection grid.
  • Analog-to-Digital Converter: Features an on-chip, low-noise $18$-bit Delta-Sigma ($\Delta\Sigma$) ADC designed specifically for processing weak biosignals.
  • Hardware FIFO Engine: A $32 \times 3$ byte deep hardware-managed circular data queue. It stores up to 32 data samples containing optical absorption info, preventing data loss if the host microcontroller experiences FreeRTOS thread scheduling delays.

B. Primary Control Registers & Bit Field Implementations

Operational behavior is strictly managed by modifying the following internal 8-bit memory-mapped registers:

  • Interrupt Status 1 (0x00) & Interrupt Enable 1 (0x02):

    • A_FULL: Asserted when the internal hardware FIFO hits a designated threshold level (configured via the FIFO_A_FULL[3:0] bits in register 0x06).
    • PPG_RDY: Asserted as soon as a new data sample pair finishes converting in the ADC core, triggering a read event.
  • FIFO Pointers (0x04 - 0x06):

    • FIFO_WR_PTR[4:0]: Points to the specific GDDRAM index where the internal ADC will write the next sample pair.
    • FIFO_RD_PTR[4:0]: Points to the index where the host MCU (I2C1) will extract the next packet.
    • OVF_COUNTER[4:0]: Tracks dropped bytes if the FIFO queue completely fills up before a host read event occurs.
  • Mode Configuration Register (0x09):

    • SHDN (Bit 7): Setting to 1 terminates all internal biasing networks and LED driver clocks, putting the chip into an ultra-low-leakage sleep mode ($0.7\ \mu\text{A}$ typical).
    • MODE[2:0] (Bits 2–0): Programmed to 0x02 for Heart Rate Mode (active IR LED execution only) or 0x03 for SpO2 Mode (interleaved Red and IR flashing execution).

C. Electrical Operating Specifications & Limits

  • Core Analog Supply Voltage ($V_{DD}$): $1.70\text{ V}$ Minimum to $2.00\text{ V}$ Maximum (Nominal: $1.8\text{ V}$).
  • LED Anode Driver Voltage ($V_{LED}$): $3.10\text{ V}$ Minimum to $5.25\text{ V}$ Maximum (Nominal: $3.3\text{ V}$ or $5.0\text{ V}$ to achieve the required LED forward voltage).
  • Operating Current Profiles:
    • Active Sensor Loop: ~ $600\ \mu\text{A}$ nominal runtime current.
    • Deep Shutdown State: $0.7\ \mu\text{A}$ typical ($10\ \mu\text{A}$ maximum absolute ceiling).
  • Ambient Light Cancellation Capability: Rejects up to $85.6\ \mu\text{A}$ of continuous, non-pulsatile direct ambient current before input amplifier saturation limits are reached.

If the raw 18-bit IR channel intensity drops below this hardware threshold baseline, the firmware instantly flags finger_detected = 0. This clears the dynamic DSP pipeline and resets the adaptive peak-detection thresholds to prevent ambient electrical noise or background static from feeding false positive inputs into the HRV analysis loop.


2. I²C Interface

The I2C module of the STM32L432KC microcontroller fetches the PPG signal samples from the MAX30102 sensor at the appropriate frequency (usually 100 to 200 Hz, to reliably extract HRV).

3. DSP: PPG Signal Processing

The processing flow of PPG data in this software component is done in a systematic manner; starting from bandpass filtering for extracting the pulse wave, followed by peak detection for identifying every heart beat, inter-beat interval calculation, and HRV feature analysis.

4. System Control Logic

Acting as the system's central state machine, this module interprets the stress classification output and routes behavior accordingly:

  • If Stressed → activates Breathing Guide mode (OLED animation pattern via PB3 and buzzer sound)
  • Else → remains in passive Monitor mode It also packages event data and dispatches them over UART (PA2) to the BLE module.

5. Bluetooth Module

Wireless telemetry transmission is handled by a HM10 Bluetooth module connected to the microcontroller's hardware USART2 peripheral interface via pin PA2 (TX) and PA3 (RX). Operating at a configuration profile of 9600 bps (or scalable up to 115200 bps), the module accepts structured telemetry frames pushed from Task_HRV every calculation cycle.

The payload data packets follow a comma-separated format detailing current physiological performance characteristics:

"STRESS: [Index], BPM: [Live_BPM], STATE: [Mode]"

This allows remote BLE terminal applications to intercept, graph, and parse the data without adding processing overhead to the microcontroller core.


6. Breathing Guide OLED

The visual biofeedback channel uses a 1.3-inch monochrome dot-matrix OLED panel driven by the SSD1306 controller chip. Unlike traditional thin-film transistor liquid crystal matrices (TFT LCDs) that rely on a continuous CCFL or LED white backlight panel, an organic light-emitting diode structure features self-illuminating pixels. This results in an infinite contrast ratio and zero static power dissipation for black pixels.

A. Graphical Display Data RAM (GDDRAM) Memory Layout

The SSD1306 features an on-chip 1024×8-bit static memory map structured into a distinct coordinate grid:

  • Page Structures: The 64 vertical display lines are partitioned into 8 structural pages indexed from Page 0 to Page 7. Each individual page describes an 8-pixel tall horizontal row block spanning 128 vertical columns wide.
  • Data Word Configuration: When a byte is written to the GDDRAM over the system bus, it is mapped as a vertical 8-pixel array. Bit $D_0$ controls the top-most pixel status of that specific page-column intersection, while bit $D_7$ controls the bottom-most pixel. A value of 1 indicates pixel illumination; a value of 0 turns the pixel off.

B. Driving Protocols & Initialization Commands

To bring the display panel up from a cold-start state, the host controller must stream a sequence of specialized command packets over the active peripheral interface:

  • Memory Addressing Mode Command (0x20): Preceded by an execution mode selection byte:

    • 0x00 (Horizontal Addressing Mode): After data is written into a page column, the internal column address pointer automatically increments. When it reaches column 127, the pointer resets to column 0 on the succeeding page row. This allows the host microcontroller to flush its local 1024-byte RAM buffer using a single, high-speed continuous streaming sequence.
  • Charge Pump Regulator Command (0x8D): Followed by an activation byte (0x14). The internal organic layers cannot illuminate using basic 3.3 V logic currents; they require a driving voltage ($V_{CC}$) between 7.0 V and 9.0 V. Sending command 0x14 engages an on-chip switched-capacitor charge pump circuit. This circuit dynamically steps up the low-voltage 3.3 V input logic supply line to the 9 V potential required to drive the matrix, eliminating the need for an external step-up converter.

  • Set Contrast Control (0x81): Accompanied by a value from 0x00 to 0xFF. This register directly adjusts the reference current sourced from the segment driver circuits, allowing fine-grained control over panel brightness and power draw.

C. Electrical Characteristics

  • Logic Interface Voltage ($V_{DD}$): 1.65 V to 3.3 V.
  • Operating Panel Voltage ($V_{CC}$): 7.0 V Minimum to 15.0 V Maximum (Nominal: 9.0 V generated by the on-chip charge pump booster).
  • Active Current Consumption: Displays draw power proportionally to the number of active pixels:
    • All Pixels Extinguished: ~ 10 μA standby state.
    • Typical Graphic Content (30% Illumination Profile): ~ 9.0 mA to 12.0 mA.
    • Full Matrix Illumination (100% White Sheet State): ~ 22.0 mA to 28.0 mA maximum draw.

To prevent high-frequency sampling collisions on the primary I2C1 bus where the MAX30102 operates, the display panel is isolated on an independent peripheral bus using the I2C3 controller (mapped to data line PC9/SDA and clock line PA8/SCL). Hardware communications are abstracted using the u8g2 graphics engine library.

When a high-stress classification event shifts the master state machine into Breathing Mode, Task_Display stops rendering the live scrolling waveform and branches into the respiratory pacing loop. The layout engine renders text variables centered on row 12 based on the active BreathState_t status. Concurrently, a geometric circle drawing block executes:

u8g2_DrawCircle(u8g2, 64, 40, breath_radius, U8G2_DRAW_ALL);

The variable breath_radius is updated asynchronously by the pacing loop, scaling smoothly between a baseline minimum of 8 pixels and a full-scale radius of 24 pixels. This expansion and contraction mimics a physical lung volume profile, providing the user with a real-time visual target for respiratory pacing.


7. Smartphone Terminal

A generic BLE serial terminal app on the smartphone displays event logs streamed from the system, including stress detection events, mode transitions, and session metadata — providing human-readable visibility into system state.

8. Power Supply Subsystem

• MCP73831: A charge controller IC that handles one cell Lithium Polymer batteries using a 5V input from USB connections. The battery is charged safely with temperature control and overcharge prevention features, thus enabling convenient charging from any available USB port.

• 3.7V LiPo Cell: Provides the energy for the circuit. A small-sized 500-1000 mAh LiPo battery provides many hours of usage time, depending on the overall power consumption of the system.

• MCP1700 Voltage Regulator: Converts the LiPo battery voltage (between 3.0V to 4.2V) to 3.3V DC power. This DC power rail supplies all devices in the system, from microcontrollers, sensors, Bluetooth module, and OLEDs. Voltage regulation is essential to ensure accurate measurements using ADC and I2C communication between devices.

Component Selection:

  • MAX30102 PPG Sensor: Chosen for its integrated 18-bit ADC, low-noise optical design, and hardware FIFO which enables reliable, continuous sample capture without loading the MCU CPU.
  • 1.3" SSD1306 OLED Display: Uses a $128 \times 64$ high-contrast pixel format. Selected because it operates over standard I2C, features no backlight matrix (saving battery power), and interfaces easily with light-weight graphics frameworks like u8g2.
  • Active Electro-Magnetic Buzzer: A simple, low-power tone transducer running on a 3.3V rail. It is driven via PWM from TIM16 to dynamically adjust sound pitch in response to the user's breathing state machine.
  • HM10 Bluetooth Module: Provides an affordable, robust Serial Port Profile (SPP) UART-to-BLE transparent wireless pass-through, broadcasting real-time ASCII metadata packets directly to terminal devices.
  • MCP1700 LDO Voltage Regulator: Features a ultra-low quiescent standby current ($1.6\ \mu\text{A}$), protecting battery capacity while keeping a fixed 3.3V reference level necessary for accurate sensor readings.

Schematics & Wiring:

The system interconnects all parts using a central 3.3V power and ground distribution tree powered by the MCP1700 regulator. Communication lines are isolated into distinct hardware modules to avoid communication bottlenecks on a single bus.

Hardware Pin Connection Map

Peripheral Module Pin Name STM32 Pin Assignment Interface Protocol Role / Description
MAX30102 Sensor SDA
SCL
PB7
PB6
I2C1 (Data)
I2C1 (Clock)
Fetches continuous raw PPG infrared/red sample streams.
SSD1306 OLED SDA
SCL
PB9
PB8
I2C1 (Data)
I2C1 (Clock)
Renders the real-time waveform array and breathing guide.
Active Buzzer Positive (+) PB3 TIM16 / CH1 (PWM) Generates matching musical tone shifts during inhale/exhale cycles.
HM10 BLE RXD
TXD
PA2
PA3
USART2 (TX)
USART2 (RX)
Streams event logs and HRV metrics to the mobile app.

Bill of Materials (BOM):

Component Name Part Number Qty Cost (EGP)
OLED 1.3 Inch I2C IIC 4-pin Display Module (Blue) N/A 1 325.00
Heart Rate Sensor – Pulse Oximeter (Not Soldered) MAX30102 1 220.00
Li-Po Battery 3.7V 500mAh (2-Wire Lead, 30405mm) 503040 1 135.00
Lithium Battery Charger Module (Micro USB & Protection) TP4056 1 17.50

Total: 697.50 EGP

Power Budget:

To guarantee continuous operations from a 3.7V 500mAh LiPo battery without tripping safety bounds, current draw targets have been mapped across system states:

$$I_{\text{Total}} = I_{\text{MCU}} + I_{\text{Sensor}} + I_{\text{OLED}} + I_{\text{BLE}} + I_{\text{Buzzer}}$$

Sub-Component Matrix Nominal Idle Current (mA) Peak Active Current (mA) Duty Cycle (%) Average Current Contribution (mA)
STM32L432KC Nucleo 8.00 26.00 100% 26.00
MAX30102 Sensor 0.60 5.00 100% 5.00
SSD1306 OLED Panel 0.00 22.00 45% 9.90
HM10 BLE Module 15.00 40.00 20% 23.00
Active Buzzer 0.00 30.00 10% 3.00
MCP1700 Regulator 0.01 0.01 100% 0.01
SYSTEM TOTALS 23.61 mA 128.01 mA 66.91 mA

Calculated Battery Lifespan

Using an industry-standard 15% discharge loss factor, operational longevity ($T$) is calculated as follows:

$$T = \frac{\text{Battery Capacity (mAh)}}{\text{Average Current Draw (mA)}} \times 0.85$$

$$T = \frac{500\text{ mAh}}{66.91\text{ mAh}} \times 0.85 \approx 6.35\ \text{Hours}$$

The maximum peak draw ($128.01\text{ mA}$) stays well within the max discharge limits ($1\text{C} = 500\text{ mA}$) of the LiPo cell, preventing sudden voltage drops during buzzer alerts or wireless data bursts.

4. Software Implementation

4.1 Software Architecture:

The software for our system is built on a real-time, preemptive multitasking architecture utilizing FreeRTOS. This design decouples time-critical sensor acquisition and signal processing from computationally expensive algorithmic analysis and slower user interface updates.

4.1.1 System Layer Architecture

The firmware follows a modular, four-tier embedded architecture to separate hardware-specific interactions from high-level application logic:

  • Application Layer: Contains the core FreeRTOS threads (Task_FIFO, Task_HRV, Task_Display), the non-blocking audio/UI state machines, and the primary application logic.
  • Middleware/Library Layer:
    • FreeRTOS: Manages task scheduling, prioritization, and execution.
    • u8g2: Handles graphical rendering and buffer management for the OLED display.
    • DSP & HRV Modules: Custom libraries (hrv.h, display.h) handling the mathematical computation of R-R intervals and stress indexing.
  • Hardware Abstraction Layer (HAL): Utilizes the STM32 HAL to manage peripheral interfaces (I2C, UART, TIM, DMA) without exposing raw register manipulation to the upper layers.
  • Hardware Layer: The physical STM32 microcontroller interacting directly with the MAX30102 sensor, SSD1306 OLED, PWM buzzer, and external BLE module.

4.1.2 Task Concurrency Model

The application leverages three primary RTOS threads, prioritized based on their strict timing requirements:

  1. Data Acquisition Thread (Task_FIFO)

    • Priority: Above Normal
    • Role: Acts as the time-critical producer in the system. It continuously polls the MAX30102 via I2C for raw photoplethysmography (PPG) data.
    • Execution: Processes incoming signals through a digital filter (process_ppg_signal), dynamically recalculates peak-detection envelopes, and logs precise microsecond timestamps (via TIM2) when a systolic peak (heartbeat) is detected.
    • Ancillary Duties: Manages the non-blocking state machine for audio feedback (Music_Update) to ensure tone generation does not interrupt I2C reads.
  2. Biometric Analysis Thread (Task_HRV)

    • Priority: Normal
    • Role: Handles the heavy mathematical computation decoupled from the fast sensor loop.
    • Execution: Wakes periodically to evaluate the buffer of R-R intervals collected by the FIFO task. It calculates time-domain Heart Rate Variability (HRV) metrics such as SDNN and RMSSD, translating them into a normalized stress_index (0-100 scale).
    • Telemetry: Formats the computed biometric data and transmits it over UART (to a BLE module) within a protected critical section.
  3. User Interface Thread (Task_Display)

    • Priority: Below Normal
    • Role: Manages the OLED screen updates and user feedback.
    • Execution: Operates as a state machine monitoring global system flags (finger_detected, hrv.valid, hrv.stress_index). Depending on the state, it renders a live scrolling waveform, displays static status messages ("PLACE FINGER", "ANALYZING..."), or triggers a guided breathing exercise animation if high stress is detected.

4.2 Flowcharts & State Machines:

4.2.1 Data Acquisition & Peak Detection Pipeline (Task_FIFO)

Data Acquisition & Peak Detection Pipeline


4.2.2 User Interface Mode Selection (Task_Display)

User Interface Mode Selection


4.2.3 Guided Breathing Feedback State Machine

Guided Breathing Feedback State Machine

4.3 Complex Logic Explanations

The accuracy of this biometric monitoring system relies on real-time Digital Signal Processing (DSP), adaptive threshold algorithms, and statistical analysis of heart rhythms. Below is a detailed breakdown of the mathematical and algorithmic logic implemented within the firmware.


4.3.1 Photoplethysmography (PPG) Signal Inversion & Filtering

The raw data emitted by the MAX30102 integrated photodiode contains a massive DC offset generated by constant light reflection off bone, muscle, and steady tissue, superimposed with a small AC component representing arterial pulse waves.

Signal Conditioning

The raw IR value (i_v) is first parsed through process_ppg_signal(), which eliminates low-frequency baseline drift (DC tracking) and high-frequency ambient noise using a digital bandpass structure.

Phase Correction (Inversion)

In the physical world, an influx of oxygenated blood during cardiac systole absorbs more infrared light, causing a sharp drop in the raw photodiode output voltage. To align this with standard medical visualization, the filtered output is inverted:

 flt = -flt;

This converts negative-going absorption drops into standard positive-going systolic peaks, facilitating traditional peak-detection processing.


4.3.2 Adaptive Envelope Tracking and Dynamic Slicing

The amplitude of a user's PPG waveform varies dynamically based on finger pressure, skin perfusion, peripheral vascular resistance, and sweat layer changes. A fixed detection threshold would result in severe under-sensing or over-sensing. To combat this, the system calculates an adaptive threshold using a decaying envelope.

Envelope Acquisition

The system constantly tracks global extremes (ppg_max and ppg_min) from the inverted filtered data stream.

Exponential Decay Muting

To ensure that a single massive motion artifact or cough does not permanently lock the threshold limits out of range, an automatic exponential decay contraction executes every 100 samples. The boundaries are compressed towards the waveform centre line ($mid$):

$$mid = \frac{ppg_{max} + ppg_{min}}{2}$$

$$ppg_{max_new} = mid + \frac{15 \cdot (ppg_{max} - mid)}{16}$$

$$ppg_{min_new} = mid + \frac{15 \cdot (ppg_{min} - mid)}{16}$$

This mathematical leak ensures the envelope naturally adapts back to nominal physiological levels within roughly one second of a transient noise burst.

Dynamic Slicing Level

The detection threshold is fixed at a 70% slicing level relative to the dynamic peak-to-peak amplitude range, optimised to clear baseline dicrotic notches while catching true beats:

$$Threshold = ppg_{min} + (Range \times 0.7)$$


4.3.3 First-Derivative Peak Detection & Jitter Rejection

Isolating the precise millisecond of a heartbeat is done via multi-stage verification to filter out false signals caused by small movements.

Stage 1 — Slope Zero-Crossing Check

The algorithm tracks the current sample (flt), the previous sample (ppg_prev), and the sample before that (ppg_prev2). A potential peak is identified when the local slope switches from positive to negative:

$$\text{Condition:} \quad ppg_{prev2} < ppg_{prev} \quad \text{AND} \quad ppg_{prev} > flt$$

Stage 2 — Amplitude & Range Validation

The potential peak must prove it is a major cardiac event by surpassing both:

  • The dynamic 70% threshold boundary
  • A minimum baseline peak-to-peak amplitude window: $Range &gt; 200$ units

Stage 3 — Physiological Time-Gating Window

When a peak clears the amplitude rules, the time gap ($\Delta t$) since the last valid heartbeat is assessed against a strict brick-wall physiological bandpass constraint:

$$550\ \text{ms} \leq \Delta t \leq 2000\ \text{ms}$$

Condition Classification Action
$\Delta t &lt; 550\ \text{ms}$ (> 109 BPM) High-frequency noise, muscle twitch, or double-count Discarded
$\Delta t &gt; 2000\ \text{ms}$ (< 30 BPM) Lost signal or finger lifted Anchor reset — re-locks on next real pulse
$550\ \text{ms} \leq \Delta t \leq 2000\ \text{ms}$ Valid cardiac event Accepted — timestamp logged

4.4 Development Environment:

The system firmware was developed using STM32CubeIDE with the GNU Arm Embedded Toolchain, utilizing an ST-LINK/V2 over Serial Wire Debug (SWD) for real-time hardware profiling. The companion mobile application was built using the Flutter framework and Dart to provide a seamless, cross-platform user interface. This application connects wirelessly to the microcontroller's USART1 peripheral via an external Bluetooth Low Energy (BLE) transceiver to decode, log, and visualize the streamed biometric telemetry in real time.

5. Testing, Validation & Debugging

5.1 Unit Testing

Before integrating the entire embedded pipeline, individual hardware sub-circuits and driver components were isolated and tested to ensure standalone functional integrity.

  • MAX30102 PPG Sensor Unit Test:
    • Objective: Verify basic register accessibility, correct I2C addressing, and optical data transmission.
    • Method: The sensor was wired independently to the STM32 I2C1 bus. The firmware was stripped down to a basic initialization routine that configured the sensor's register maps. Raw sample bytes from the optical FIFO array were printed directly to a PC using a serial terminal (e.g., TeraTerm).
    • Success Criteria: The microcontroller successfully established communication with the sensor, and raw, responsive numerical streams fluctuated consistently based on physical contact with the photodiode.
  • SSD1306 OLED Display Unit Test:
    • Objective: Validate display driver configuration and graphical rendering logic.
    • Method: The 1.3" display panel was tested standalone using the u8g2 graphics framework. Basic rendering commands were dispatched over the I2C bus to construct sample coordinate graphs, text boxes, and primitive geometric shapes.
    • Success Criteria: The panel rendered crisp, high-contrast visual blocks without display artifacts, screen tearing, or I2C communication timeouts.
  • Active Buzzer Unit Test:
    • Objective: Confirm independent PWM frequency modulation via the hardware timer.
    • Method: The active electromagnetic buzzer was connected directly to pin PB3. The TIM16 peripheral was initialized in PWM mode to loop through a basic sequence of frequencies, sweeping across standard audio musical scales.
    • Success Criteria: The buzzer output clear, audible tones at varying pitch steps that matched the programmed timer register frequencies.
  • JDY-31 BLE Module Unit Test:
    • Objective: Ensure proper Bluetooth pairing and transparent UART passthrough.
    • Method: The BLE module was mounted on a test bench with its TX/RX lines cross-connected to a USB-to-UART hardware converter bridge. AT commands were transmitted to verify baseline baud-rate parameters, and basic string patterns were broadcast wirelessly.
    • Success Criteria: The module established a stable wireless link with a smartphone and reliably mirrored serial characters to a mobile serial terminal app without byte dropping.

5.2 Integration Testing

To validate the reliability, responsiveness, and accuracy of the multi-threaded system, an incremental integration testing protocol was performed across 5 progressive implementation stages:

  • Stage 1: Optical Acquisition & Graphics Synchronization Validation
    • Description: We verified that the MAX30102 sensor safely captures the incoming pulse waveform array over the I2C1 bus without causing data frame overruns. The raw signal conditioning parameters were tracked using an ST-Link debugger, confirming that the dynamic 70% threshold tracks changing envelope states. The computed real-time heart rate data was then successfully dispatched over the secondary I2C bus to confirm it displays properly on the SSD1306 OLED interface as a clean, scrolling real-time plot without display lag.
  • Stage 2: Forced Biofeedback Animation Verification
    • Description: We evaluated the visual performance of the breathing assistant state machine under high-stress conditions. To test this before completing the full automated HRV parsing script, the global trigger threshold parameter was manually bypassed to simulate high stress. We confirmed that Task_Display shifts out of the passive monitor graph and begins rendering the geometric breathing animation, expanding and contracting the bounding box radius smoothly within the targeted 4-second inhale, 2-second hold, and 6-second exhale structural windows.
  • Stage 3: Forced PWM Audio-Drive Pacing Verification
    • Description: Using the same manual low-stress bypass configuration, we verified the functionality of the auditory breathing assistant. We monitored the output pin PB3 using an oscilloscope to ensure that the TIM16 hardware timer reloads its compare registers smoothly when switching audio frequencies (BUZZER_FREQ). The active buzzer correctly translated the program's frequency sweeps into clear, non-blocking musical scales without freezing the concurrent I2C sensor reading thread.
  • Stage 4: Isolated Wireless Telemetry Link Verification
    • Description: We tested the Bluetooth communication pipeline by evaluating the mobile application on an isolated test bench. The JDY-31 module was supplied with mock ASCII data packets over a standard USB-to-UART bridge to verify that the mobile application detects, accepts, and parses incoming comma-separated data streams correctly without losing data packets.
  • Stage 5: End-to-End System Validation Under Dynamic Loading
    • Description: A final end-to-end integration test was conducted across various simulated user states. We verified that when the user is at rest, the system remains in passive monitoring mode. When physical stressors or paced hyperventilation were introduced to alter heart rate variability parameters, the system correctly captured the change, raised the internal stress index, initiated the BLE warning transmissions, and turned on the coordinated OLED graphics and buzzer audio feedback.

5.3 Challenges & Solutions:

  • Physical Sensor Connection Stability: The structural connection between the sensor breakouts and prototyping modules was highly sensitive to contact force variance.
    • Solution: We resolved this issue by soldering solid core header wires directly to the pad connections with support from the CSCE workshop, removing mechanical contact resistance.
  • Ground Reference Noise Corrupting I2C Transfers: High peak switching currents from the active buzzer PWM frequencies caused voltage reference fluctuations on the ground line. This regularly corrupted I2C data transfers.
    • Solution: We isolated the buzzer return line path directly back to the primary decoupling ground pin, bypassing the sensor signal references.
  • Buzzer Blocking Delay Lockups: Early testing versions used blocking logic loops (HAL_Delay()), which stalled execution, missed sensor FIFO reads, and broke FreeRTOS task scheduling.
    • Solution: We refactored code components to run an asynchronous tracking loop (Music_Update()) centered entirely on non-blocking delta measurements via HAL_GetTick().
  • Hardware Availability Constraints: Overcoming the unavailability of the CC1101 RF modules by transitioning from a wireless watch-based display to an integrated OLED interface.

6. Results & Demonstration

6.1 Final Prototype:

image image image

6.2 Video Demonstration:

Our progress presentation video

Final presentation video

6.3 Performance Metrics:

The integrated embedded pipeline was extensively profiled using hardware debug tools to confirm processing efficiency targets:

  • I2C Signal Read Periodicity: The time-critical polling loop (Task_FIFO) checks sample registers at a steady period of $10\text{ ms} \pm 0.2\text{ ms}$ ($100\text{ Hz}$ throughput profile), preventing data loss.
  • Processing Latency Index: The elapsed delay between an actual systolic contraction peak and valid slope classification measures just $6.5\text{ ms}$, beating our $50\text{ ms}$ timing target.
  • FreeRTOS Execution Task Load Allocation:
    • Task_FIFO Processing Burden: $44.2%$ runtime usage window.
    • Task_HRV Processing Burden: $16.8%$ runtime usage window.
    • Task_Display Processing Burden: $32.5%$ runtime usage window.
    • Kernel IDLE Standby Overhead: $6.5%$ processing margin.

7. Project Management:

7.1 Division of Labor

Team Member Responsibilities
Ismaiel Sabet Physical connections, Breathing Assistant “OLED” and “Buzzer” parts
Shaza Ali BPM processing, HRV calculation, freeRTOS implementation
Islam Abdeen Analytics app, Physical connections, Breathing Assistant Buzzer

7.2 Timeline

Milestone List

Milestone Planned Date
M1 — component procurement Week 1
M2 — Hardware assembly: MAX30102 + STM32 wiring Week 2
M3 — DSP module implmentation Week 2
M4 — Stress classification logic tested Week 3
M5 — OLED breathing pattern implemented (PB3 PWM) Week 3
M6 — BLE UART event logging to smartphone terminal Week 4
M7 — Full system integration & end-to-end test Week 4
M8 — Final demo & documentation submission Week 5

8. Appendices & References

8.1 Source Code Repository:

https://github.com/Islamauc/Human_stress_control

8.2 References:

The MAX30102 FIFO reading and register map: https://github.com/sparkfun/SparkFun_MAX3010x_Sensor_Library

The DC removal high-pass IIR filter (x - xprev + yprev * 0.995) is a standard single-pole high-pass used in many PPG implementations: https://github.com/aromring/MAX30102_by_RF

Peak detection, and HRV calculation targeting STM32, the RMSSD and SDNN calculations: https://github.com/pscholl/etherhrv

3-point peak detector logic (prev2 < prev && prev > current) is described in: https://github.com/blakeMilner/real_time_HRV

https://www.researchgate.net/publication/395273001_Real_Time_Heart_Rate_And_Oxygen_Value_Monitoring_Using_Arduino_Uno_Based_MAX30102_Sensor_ModuleReal_Time_Heart_Rate_And_Oxygen_Value_Monitoring_Using_Arduino_Uno_Based_MAX30102_Sensor_Module

https://www.who.int/news-room/questions-and-answers/item/stress

https://www.garmin.com/en-US/blog/health/top-10-features-to-monitor-your-health/

Clone this wiki locally