This issue is often caused by poor exercise form, or what gym-goers usually call bad form. It’s an invisible enemy in the fitness world. A small mistake in posture or movement angle can make an exercise much less effective because the load shifts to the wrong muscles.
More importantly, the consequences can be serious. Repeatedly lifting weights with improper form puts uneven stress on the body and increases the risk of long-term injuries, ranging from ligament tears to more severe conditions such as a herniated disc (HNP) and pinched nerves.
The Data Behind Improper TechniqueThis concern is backed by solid scientific evidence. Research in sports science and public health highlights just how significant the impact of poor exercise technique can be:
- High Injury Rates: According to studies published by the U.S. National Institutes of Health (NIH), more than 50% of gym-related injuries are linked to overexertion and improper lifting technique.
- Reduced Training Efficiency: Biomechanical studies show that even a small deviation of 10 to 15 degrees during isolation exercises like the lateral raise can shift up to 40% of the mechanical load away from the target muscle (the deltoids) and onto compensating muscles such as the upper trapezius.
- Limited Access to Professional Guidance: Data from ABC Fitness and Insurance Canopy suggests that around 70% to 80% of gym members choose to train without a personal trainer, mainly because of the additional cost.
To avoid the risks of injury and ineffective training, the ideal solution would be to work with a professional Personal Trainer (PT). In reality, however, not everyone can afford the cost of regular coaching sessions each month.
On the other hand, camera-based motion analysis systems built with computer vision introduce a different set of challenges. Setting up a tripod and recording videos in a public gym can feel awkward and uncomfortable for many people. It may also disrupt other gym members and raise privacy concerns, especially for women who may not want to be captured on camera.
Seeing this gap between the need for safer training, the financial limitations faced by many gym-goers, and the growing importance of privacy, I was motivated to develop a new solution.
Motion tracking devices are not entirely new. Several developers have already explored this idea, but many existing solutions still fall short of solving the real problem. Some systems only provide feedback after the entire workout session is finished, rather than at the exact moment an incorrect movement occurs. Others still depend on a smartphone connection or internet access to function.
In this project, I adopted a continuous improvement approach: taking an existing concept and refining it to better address real-world needs. The goal is to develop a standalone smart assistant that does not rely on cameras or internet connectivity. The main focus of this prototype is to evaluate the system’s ability to detect improper movement patterns and deliver corrective feedback in real time.
By combining the efficiency of TinyML with a Targeted Precision Monitoring approach, this project serves as a Proof of Concept (PoC). It demonstrates that lightweight artificial intelligence can be embedded into a compact, affordable, and privacy-friendly device—opening the door to safer and more accessible self-guided training for everyone.
As an early-stage prototype developed as a Proof of Concept (PoC), VibeCoach was designed around several key feature objectives:
1. On-Device Edge Inference (TinyML Framework)- Testing Objective: The system is designed to analyze movement data directly on the device, without relying on external computing resources.
- Technical Approach: A lightweight neural network model, trained and compiled using Edge Impulse, is deployed to the STM32 microcontroller. At this stage, the main goal is to validate the model’s ability to distinguish between correct and incorrect movement patterns locally.
- Testing Objective: The prototype uses a small vibration motor to provide immediate feedback to the user, eliminating the need for an external display.
- Planned Vibration Patterns: The firmware is designed to support two response scenarios:
- Short Intermittent Vibrations: Intended to indicate tempo-related issues, such as performing repetitions too quickly.
- Long Continuous Vibrations: Intended to signal critical posture deviations detected by the sensor.
- Validated Feature: This is the most mature aspect of the project and represents a fully realized design decision rather than an overstatement.
- Technical Basis: The device relies exclusively on the MPU-9250, which captures only numerical orientation and motion data. Because no camera or imaging component is used, the system is fundamentally privacy-friendly and well suited for use in public spaces such as gyms.
- Testing Objective: The firmware runs entirely within the microcontroller’s main loop, without requiring Wi-Fi, internet access, or cloud services.
- Expected Benefit: By removing network dependencies, the system minimizes latency and allows performance to depend solely on the optimization of the microcontroller’s internal resources.
- Practical Design: The device is designed to be compact and portable so it can be attached to an elastic wearable strap.
- Usage Scenarios: Depending on the exercise being monitored, the prototype can be placed on different body segments. For example:
- On the chest to monitor torso inclination during squats.
- On the upper arm to monitor shoulder positioning during lateral raises.
Let's have a sneak peek at the system architecture of the VibeCoach ecosystem.
Project OverviewProject Scope & Focus (Current Phase): In this prototyping and development phase, the TinyML movement classification model is explicitly trained and optimized for tracking the Lateral Raise exercise, targeting form execution of the deltoid muscles. Focusing on this specific compound movement serves as a robust proof-of-concept for the VibeCoach framework, ensuring high-precision error detection before expanding the training dataset to other workout routines in future iterations.
Hardware Selection RationaleThe hardware used in VibeCoach was carefully selected to balance processing performance, motion-sensing accuracy, portability, and user comfort. Each component plays a specific role in supporting the project’s goal of delivering real-time exercise feedback in a compact standalone device.
• STM32F411CEU6 (Black Pill) – Core Processing UnitThe STM32F411CEU6 was chosen as the main processor because it offers an excellent balance between computational power and energy efficiency. Based on the ARM Cortex-M4 architecture and running at up to 100 MHz, it includes a hardware Floating Point Unit (FPU), which significantly accelerates the matrix operations required for TinyML inference.
With 512 KB of Flash memory and 128 KB of SRAM, the microcontroller provides enough resources to store both the AI model runtime and supporting libraries, including the graphics driver for the ST7735, without excessive memory constraints.
• MPU-9250 9-Axis IMU – Precision Motion TrackingThe MPU-9250 was selected because weight training involves complex three-dimensional body movements. Unlike standard 6-axis IMUs, the MPU-9250 includes an integrated magnetometer, which improves orientation estimation and helps reduce drift over time.
This allows the firmware to convert raw sensor data into stable quaternion representations such as (q0, q1, q2, q3), enabling more accurate detection of subtle posture deviations during exercise.
• ST7735 LCD and 1×4 Membrane Keypad – Standalone User InterfaceTo support the standalone design objective, VibeCoach uses a 1.8-inch TFT LCD based on the ST7735 along with a 1×4 membrane keypad.
This combination enables users to navigate menus, select exercise modes (such as squat or lateral raise), and perform sensor calibration directly on the device—without needing a smartphone or computer.
• RGB LED and Mini Vibration Motor – Multimodal Feedback SystemGyms are often noisy environments, so the system uses both visual and tactile feedback to ensure alerts are noticeable.
- The RGB LED follows a simple traffic-light concept:
- Green: correct form
- Yellow: minor deviation
- Red: significant form error
- A 3–5 V mini vibration motor provides immediate haptic feedback, allowing users to correct their posture without taking their eyes off the exercise.
For a wearable device, size and weight are critical. A 3.7 V 250 mAh Li-Po battery was chosen because it offers a high energy density while remaining lightweight and compact.
Charging is managed by the TP4056, which provides safe charging and aligns the device with modern USB-C charging standards.
System Architecture & Operational PipelineTo guarantee stable digital signal transitions and prevent erroneous triggers from hardware noise, the GPIO parameters were thoroughly customized within STM32CubeMX. For the user input interface, the input pins assigned to the 1x4 membrane keypad are configured with internal Pull-up resistors. This design eliminates the need for external pull-up resistors on the PCB, maintaining a minimal hardware footprint while ensuring the pins default to a stable HIGH state until pressed. On the other hand, the output pins driving the RGB LED notification channels and peripheral control lines are set to Push-Pull mode with a Medium output speed profile. This configuration provides the optimal balance between sharp, low-latency signal switching for active workout alerts and minimized electromagnetic interference (EMI) inside the wearable enclosure.
To achieve flawless real-time gesture tracking without data bottlenecks, the I2C1 peripheral was explicitly configured in Fast Mode with a clock speed of 400 kHz. Since the MPU-9250 IMU continuously streams 9-axis kinematic data (accelerometer, gyroscope, and magnetometer), standard I2C Mode (100 kHz) would introduce high latency, disrupting the time-series window required by the TinyML engine. By raising the frequency to 400 kHz and setting the duty cycle to a balanced 2-to-1 ratio, the STM32F411 can poll sensor registers rapidly. This ensures that the data pipeline feeding the Madgwick fusion filter remains highly responsive, providing clean and uninterrupted orientation quaternion samples for edge inference.
The SPI1 peripheral is configured in Transmit Only Master mode since the ST7735 LCD only requires unidirectional data from the MCU. The data size is set to 8 bits with MSB First format. With a prescaler of 8, the baud rate runs at 6.25 MBits/s, providing a stable refresh rate for real-time menu rendering without screen tearing. CPOL is set to Low and CPHA to 1 Edge (SPI Mode 0) to match the LCD driver specifications.
Three internal hardware timers are configured in PWM Generation mode to drive the multimodal feedback system of VibeCoach:
- TIM1 is configured in PWM mode to control the haptic feedback vibration motor. With the MCU clock at 50 MHz, setting the Prescaler to 49 and Counter Period to 999 generates a stable frequency to dynamically adjust the vibration intensity based on form error severity.
- TIM2 and TIM3 are utilized to drive the channels of the RGB LED indicator. By using PWM outputs across these timers, the system can smoothly mix and modulate the Red, Green, and Blue color intensities to provide immediate visual alerts during workouts.
The USART peripheral is enabled mainly for debugging and data collection during the development phase. It connects the STM32 to the Edge Impulse CLI Data Forwarder via serial communication. This allows real-time raw IMU data to be streamed directly to the Edge Impulse platform for dataset sampling and model training. The baud rate is configured to handle continuous high-frequency sensor data streaming without packet loss.
Clock ConfigurationTo achieve a sustainable balance between real-time processing and power efficiency, the system clock of the STM32F411 was intentionally configured at 50 MHz. Since VibeCoach is a standalone wearable powered by a compact 250mAh Li-Po battery, running the microcontroller at its maximum 100 MHz frequency would drastically reduce operational time. By utilizing the High-Speed External (HSE) crystal oscillator and precisely tuning the Phase-Locked Loop (PLL), a 50 MHz SYSCLK provides the optimal sweet spot. It delivers more than enough computational performance for the ARM Cortex-M4 core to execute the Edge Impulse TinyML inference loop smoothly while maximizing battery longevity. Simultaneously, the APB prescalers are adjusted to maintain stable clock signals for the I2C1 bus (configured at 400 kHz Fast Mode for high-frequency IMU data ingestion) and the SPI1 bus for the LCD interface.The SPI1 peripheral is configured in Transmit Only Master mode since the ST7735 LCD only requires unidirectional data from the MCU. The data size is set to 8 bits with MSB First format. With a prescaler of 8, the baud rate runs at 6.25 MBits/s, providing a stable refresh rate for real-time menu rendering without screen tearing. CPOL is set to Low and CPHA to 1 Edge (SPI Mode 0) to match the LCD driver specifications.The SPI1 peripheral is configured in Transmit Only Master mode since the ST7735 LCD only requires unidirectional data from the MCU. The data size is set to 8 bits with MSB First format. With a prescaler of 8, the baud rate runs at 6.25 MBits/s, providing a stable refresh rate for real-time menu rendering without screen tearing. CPOL is set to Low and CPHA to 1 Edge (SPI Mode 0) to match the LCD driver specifications.The SPI1 peripheral is configured in Transmit Only Master mode since the ST7735 LCD only requires unidirectional data from the MCU. The data size is set to 8 bits with MSB First format. With a prescaler of 8, the baud rate runs at 6.25 MBits/s, providing a stable refresh rate for real-time menu rendering without screen tearing. CPOL is set to Low and CPHA to 1 Edge (SPI Mode 0) to match the LCD driver specificatio.
Project ManagerBefore generating the initialization code, the Project Manager settings were configured to streamline the workflow between STM32CubeMX and STM32CubeIDE. Toolchain/IDE is set to STM32CubeIDE with the latest firmware package. Crucially, under the Code Generator settings, "Keep User Code when re-generating" is enabled. This ensures that any custom user code written within the USER CODE BEGIN and END tags remains intact whenever the peripheral configuration is updated and re-generated.
Firmware Development in STM32CubeIDEAfter generating the initialization code from STM32CubeMX, the project was opened in STM32CubeIDE. The first step before writing the main application logic is incorporating the required external libraries into the project directory. This includes the ST7735 LCD display driver, the MPU-9250 library, and the Madgwick AHB fusion filter source files.
- LCD ST7735 Library from github
git clone https://github.com/Matiasus/ST7735.git- MPU-9250 Library from github
https://github.com/CrackAndDie/MPU9250-DMP-STM32.git- Madgwick Fusion Filter Library form github
https://github.com/mirhamza708/Madgwick-filter-STM32-MPU9250.gitWhy Madgwick Filter? (Algorithm Rationale)
An IMU sensor like the MPU-9250 is prone to high-frequency noise on the accelerometer and low-frequency drift on the gyroscope over time. To get accurate orientation data (Quaternions), a sensor fusion algorithm is required. VibeCoach uses the Madgwick Filter instead of the traditional Kalman Filter for two main reasons:
- Computational Efficiency: The Kalman Filter requires complex matrix multiplication, which consumes massive CPU cycles and RAM. The Madgwick Filter uses a gradient descent-based algorithm that is mathematically optimized, making it incredibly lightweight for an ARM Cortex-M4 microcontroller running at 50 MHz.
- High Accuracy at Low Sampling Rates: Madgwick's algorithm provides precise orientation estimation even at lower sampling frequencies. This efficiency helps minimize battery consumption on our 250mAh Li-Po battery while still delivering smooth, real-time tracking for workout form evaluation.
Calibration Feature
After integrating the libraries, the next step is developing the "Reference Pose Calibration" routine to normalize the sensor data.
The sequential data pipeline runs as follows:
Raw IMU Data > Madgwick Filter > Calibration Engine (invQ) > Final Normalized DataThis calibration method is chosen for inclusivity. Since every user has a unique physical posture and body size, hardcoded calibration baselines would fail. This adaptive approach ensures anyone can use VibeCoach with the same level of accuracy.
The firmware workflow operates through these steps:
- Preparation Phase: The LCD displays "Ready" for 2 seconds to stabilize the Madgwick filter registers while allowing the user to get into their starting position.
- Countdown Phase: The system counts down from 3 to 1. To keep the user focused without looking at the screen, a non-blocking haptic state machine triggers a short 200 ms vibration pulse exactly as each second ticks down.
- Sampling & Transformation Phase: During the countdown, the MCU captures 300 samples to calculate the user's average normal orientation baseline (q_base). Once completed, the inverse quaternion function (
invQ) continuously multiplies the conjugate of this baseline with real-time movement data.
This mathematically shifts the 3D coordinate frame, treating the user's unique starting posture as the true origin (0°). The resulting clean output is then ready to be fed into the Edge Impulse TinyML model.
Machine Learning (Edge Impulse)With the IMU data pipeline fully established in STM32CubeIDE, the next phase focuses on data collection and Machine Learning development using Edge Impulse.
Edge Impulse was selected primarily for its efficiency in rapid prototyping. The platform offers a fast learning curve, intuitive workflows, and seamless toolchains that drastically accelerate development time when building and deploying TinyML models on hardware constraints.
installing edge impulse via cliand code to send data to edge impulse
The first step in starting data collection with Edge Impulse is setting up the development environment. Since my workstation runs on Linux Mint, the Edge Impulse CLI was installed via the terminal using Node.js and NPM.
curl -fsSL https://nodesource.com | sudo -E bash - sudo apt-get install -y nodejsmake sure that node and npm are installed
node -v
npm -vand after that we can install the edge impulse
sudo npm install -g edge-impulse-cli --unsafe-permOnce the CLI tools were configured, the STM32 microcontroller was connected to the PC via a USB-to-UART module. By executing the
edge-impulse-data-forwarderBy executing the command in the Linux terminal, the final orientation data is streamed directly into the Edge Impulse Studio dashboard. Once this serial connection is successfully established, we can begin capturing datasets to train our TinyML model. To achieve this, specific UART transmission code was implemented on the MCU side to forward the real-time data packets to the desktop PC.
Dataset Acquisition & TinyML Model Training
Once the MCU was successfully connected to Edge Impulse Studio, the data acquisition process began. To ensure the quality and validity of the dataset, I also captured movement samples from a colleague who is an experienced gym practitioner.
This approach was taken so that the TinyML model could learn movement patterns from actual correct forms objectively, while enriching data variance to build a highly robust dataset for the trained classes.
Once the dataset was sufficient for prototyping purposes, the next phase was constructing the Impulse Design in Edge Impulse to maximize the efficiency of the TinyML model. The configuration parameters were carefully selected based on the physical characteristics of human biomechanics during workouts:
- Window Size (1000ms) & Window Increase (100ms): A 1-second time window is ideal for capturing a single phase of a workout repetition or movement transition. A short window increase (stride) of 100ms was implemented to enable high-density, continuous time-series overlapping. This ensures near-instantaneous, real-time inference, allowing the haptic feedback system to alert the user without noticeable latency.
- Spectral Analysis (Processing Block): Exercise routines generate periodic and repetitive kinematic signals. The Spectral Analysis block is utilized to extract frequency and power features (via FFT) from the quaternion data. This block is highly effective at filtering out raw signal noise and distinguishing between stable, controlled repetitions (correct form) and shaky, erratic movements (muscle fatigue or incorrect form).
- Classification (Learning Block): A Neural Network (Keras) classification block was selected because the ultimate goal of VibeCoach requires discrete decision-making, mapping the incoming normalized motion vectors into distinct categorical states: idle, wrong_move, or correct_move.
Following the hyperparameter adjustments in the Impulse Design and optimizing the neural network training configurations, the TinyML model training was successfully completed. Based on the evaluation within Edge Impulse Studio, the model achieved a solid accuracy of 90.1%.
It is worth noting that these results were obtained during an early prototyping phase with a relatively small-scale dataset. However, achieving an accuracy above 90% at this stage demonstrates that our signal processing pipeline—from the Madgwick filter to the inverse quaternion calibration frame transformation—successfully provides highly discriminative features. This enables the model to effectively distinguish between different workout form qualities in real-time.
The visualization above illustrates the final performance of the TinyML model inside Edge Impulse Studio. Achieving a 90.1% validation accuracy and a low loss of 0.27, the model's metrics break down as follows:
- Rest State Detection (IDLE): The IDLE class yields the highest metrics with 96.7% accuracy and a 0.97 F1 Score, ensuring the system remains stable and silent during rest windows.
- Form Quality Metrics (CORRECT_MOVE vs WRONG_MOVE):Correct exercise forms are identified at a high accuracy of 91.6%. Concurrently, 18.2% of the WRONG_MOVE datasets are still misclassified as correct repetitions. This overlap is visible in the Data Explorer cluster, where some red markers (incorrect classifications) intermingle with the main lime-green cluster.
This transparent evaluation highlights our primary focus for future iterations: expanding the dataset with a wider variety of incorrect posture samples to help the neural network establish sharper decision boundaries.
Edge AI Deployment & STM32 IntegrationAfter achieving a satisfying model accuracy, the final step is transitioning the artificial intelligence directly onto the hardware for on-device inference. The TinyML model is exported from Edge Impulse as a **C++ library** (or CMSIS-Pack). This library is then integrated back into the STM32CubeIDE project, enabling the microcontroller to perform standalone, offline movement classifications without relying on an internet connection or an external PC.
TinyML Model Integration via STM32CubeMX CMSIS-Pack
Once the model training is complete within the Edge Impulse Studio, the final crucial phase is transferring this artificial intelligence to execute 100% offline on the physical MCU. For this project, I utilized the CMSIS-Pack (.pack) deployment method exported from Edge Impulse and integrated via STM32CubeMX and STM32CubeIDE. The primary advantage of choosing a CMSIS-Pack over a standard generic C++ library deployment is the seamless software management it offers. The CMSIS-Pack functions as an official software expansion component that integrates directly into the STMicroelectronics code generation environment. This drastically simplifies include path configurations and resolves hardware-specific library dependencies automatically.
The on-device inference deployment workflow is structured into the following tactical steps:
- Exporting the CMSIS-Pack from Edge Impulse: Inside the Deployment tab of Edge Impulse Studio, the STM32 Cube.MX CMSIS-Pack option was selected. This process compiles the entire Neural Network architecture, spectral feature extraction blocks, and optimized mathematical operations for the ARM Cortex-M architecture into a singular unified.pack distribution file.
- Menginstal Pack di STM32CubeMX: Buka perangkat lunak STM32CubeMX, lalu masuk ke menu Software Packs Manager -> From Local... untuk memuat file
.packyang telah diunduh. Setelah berhasil diimpor, komponen Edge Impulse diaktifkan melalui menu Select Components, dan dikonfigurasi agar berjalan di bawah tumpukan hardware MCU target.
- Pembuatan Kode Otomatis (Code Generation): Setelah komponen pack dicentang di CubeMX, saya menekan tombol Generate Code. Secara otomatis, STM32CubeMX akan menyuntikkan seluruh pustaka inferensi AI, file header, dan dependensi matematika ke dalam pohon direktori proyek di STM32CubeIDE. Pustaka ini dikelola secara rapi di bawah folder komponen eksternal tanpa mengacaukan struktur kode utama.
- Project Migration to Native C++ (
main.cpp): By default, STM32CubeMX generates the primary application entry point in native C (main.c). However, since the Edge Impulse inference SDK is built entirely on C++, I manually converted the main file tomain.cpp. This direct migration allows all Edge Impulse classes, structures, and math functions to be invoked natively within the main loop, completely eliminating the need for complex external wrapper files. To ensure that the standard C-based STMicroelectronics hardware abstraction drivers compile flawlessly under the G++ compiler, the primary hardware headers were enclosed within anextern "C"linkage block. Inside thismain.cpparchitecture, the calibrated 3D orientation outputs from theinvQ()engine are directly loaded into the signal buffer and processed by therun_classifier()routine, enabling immediate real-time haptic motor triggering upon detecting an incorrect form (wrong_move).
To provide instantaneous posture correction without breaking the user's concentration during weightlifting, the feedback architecture inside tinyML.cpp is built upon two advanced embedded pillars: a Score Accumulator Logic and a Non-Blocking Vibration State Machine.
The control logic operates through the following systemic workflow:
1. Adaptive Score Accumulation System: Instead of triggering immediate haptic feedback based on a single inference frame—which is highly susceptible to transient signal noise—the system introduces a penalty accumulator score (s_wrong_score. When the TinyML model flags an incorrect form (wrong_move) with a confidence rating >= 70%, the score escalates by +2. Conversely, when the user corrects their form (correct_move or shifts to idle), the score gracefully decays by -1 toward a baseline floor of zero.
2. Graduated Haptic Feedback (PWM):
- The haptic alerts are modulated using Pulse Width Modulation (PWM) via Timer 1 to match the physical intensity of the vibration with the severity of the user's execution error: Score 4–7 (Info Alert): Triggers a single short pulse at low duty cycle (300/999) as a gentle notification.
- Score 8–11 (Medium Warning):Fires 2 distinct medium-intensity pulses (550/999) bound to a 1.5-second lock out/cooldown period.
- Score >= 12 (Strong Correction): Enforces 3 powerful vibration bursts (820/999) paired with a strict 3-second absolute cooldown to prevent persistent irritating vibrations while the user drops or re-racks the weight.
3. Non-Blocking Architecture Execution:All pulse timing delays and haptic cooldown tracks are processed using tick-evaluation functions (HAL_GetTick()) rather than blocking delay hooks. This asynchronous state machine model guarantees that the background TinyML inference frames and continuous data acquisition in add_sensor_data() remain active every 10ms, entirely eliminating CPU stalling and safeguarding sampling frequency consistency.
4. Interactive Visual RGB Feedback: For visual verification by a coach or workout partner, Timer 2 and Timer 3 peripheral channels drive an onboard RGB LED. The LED remains off during idle states, shines solid **Green** during flawless execution (score = 0), shifts to **Blue** as a cautionary indicator when minor form discrepancies compound, and turns solid **Red** when errors reach a critical, high-injury-risk tier.
The entire data processing lifecycle is orchestrated inside the main add_sensor_data() routine. This function executes continuously with a precise 10 ms pacing interval (HAL_Delay(10)) within the main loop. This timing window is carefully tuned to match our IMU sensor's 78Hz sampling frequency (approximately 12.8\ms per data frame).
By introducing this minor constraint, the MCU retains a highly stable processing overhead, ensuring that the TinyML inference frame completes well within the timing margins without the risk of serial buffer overflows or kinematic sampling jitter.
Power Management System & Wearable SafetyTo guarantee true mobility as a dedicated wearable device, VibeCoach is driven by a compact 3.7V 250mAh LiPo battery, managed via a TP4056 linear charging IC over a universal USB Type-C interface. The core challenge with Lithium chemistry is its dynamic voltage range (3.0V fully discharged to 4.2V at peak charge), which exceeds the maximum 3.3V analog tolerance of the STM32F411 ADC pins.
To resolve this hardware constraint, I implemented a Voltage Divider network using two balanced 10kOhm resistors. This configuration scales the active battery voltage precisely by half before routing it to the PA0 (ADC1_IN0) pin, safeguarding the MCU from overvoltage clipping.
On the software architecture side, the bsp_battery.cpp module is rigorously optimized to safeguard overall system performance, particularly preventing latency injection into the SPI-driven ST7735 LCD layout:
- Anti-Blocking Cache System and Pre-Warming: A full raw ADC read requires a blocking overhead of 160ms (32 samples multiplied by 5ms delay execution). Running this directly inside the display render pipeline would induce severe visual flickering. To eliminate this, a bsp_battery_force_init mechanism is introduced to pre-warm the data cache once during bootup inside main.cpp. The main loop then samples battery metrics directly from this non-blocking cache memory.
- Spectral Noise Suppression (Averaging and EMA Filter): High-frequency electrical ripple generated by the active LCD SPI lines corrupts raw ADC telemetry. The driver suppresses this by batch-averaging 32 hardware samples. This averaged vector is passed through an EMA (Exponential Moving Average) filter with an alpha value of 0.15 to construct an incredibly smooth, drift-free capacity trendline.
- Dual-Layer Hysteresis Stabilization: To prevent the on-screen display metrics from jittering or bouncing under sudden high-current draws, a dual-layer software hysteresis is enforced: a 0.05V constraint on the raw voltage tracking and a 2 percent gate on the active battery graphic update.
Although the VibeCoach framework is currently engineered within its prototyping phase, the component interconnections are structured modularly and systematically, demonstrating high-reliability execution without requiring a custom PCB at this stage. All hardware topologies revolve around the STM32F411 microcontroller as the central processing unit tasked with sensor data ingestion, TinyML model inference, power management, and real-time display rendering.
The VibeCoach project successfully demonstrates that Edge AI and TinyML can be seamlessly integrated into low-power microcontrollers like the STM32F411 for real-time, completely offline workout form correction. By implementing a robust data pipeline—stretching from adaptive orientation calibration to spectral feature extraction—the trained neural network achieved a solid validation accuracy of 90.1 percent. Backed by an asynchronous, non-blocking haptic state machine and an optimized battery management engine, the system provides safe, immediate physical and visual feedback without inducing processing jitter or interrupting the user's workout flow.
Future Work
As the system is currently in its initial prototyping phase, several strategic optimization tracks have been outlined to elevate the wearable framework toward production-grade standards:
- Dataset Expansion: Broadening the training dataset by capturing a wider array of incorrect movement forms from multiple gym practitioners to sharpen the neural network's decision boundaries.
- Wireless Connectivity: Integrating a Bluetooth Low Energy (BLE) stack to enable the wearable node to stream real-time workout telemetry and historical execution metrics directly to a companion mobile application.
- Hardware Miniaturization: Transitioning from development modules to a customized Surface Mount Device (SMD) Printed Circuit Board layout. This will drastically reduce the physical footprint, allowing VibeCoach to be housed in a highly ergonomic, lightweight silicone strap enclosure optimized for intensive athletic environments.




_4YUDWziWQ8.png?auto=compress%2Cformat&w=48&h=48&fit=fill&bg=ffffff)





_Ujn5WoVOOu.png?auto=compress%2Cformat&w=40&h=40&fit=fillmax&bg=fff&dpr=2)

Comments