<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Xvegcm on Medium]]></title>
        <description><![CDATA[Stories by Xvegcm on Medium]]></description>
        <link>https://medium.com/@xvegcm?source=rss-9e574583cf14------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*I910y1K1kd_lhwUy.jpg</url>
            <title>Stories by Xvegcm on Medium</title>
            <link>https://medium.com/@xvegcm?source=rss-9e574583cf14------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:26:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xvegcm/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Multi Sensor Fusion Framework for Human Motion Tracking]]></title>
            <link>https://medium.com/@xvegcm/building-a-multi-sensor-fusion-framework-for-human-motion-tracking-63b0270857a5?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/63b0270857a5</guid>
            <category><![CDATA[human-motion]]></category>
            <category><![CDATA[imu]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 06:16:20 GMT</pubDate>
            <atom:updated>2026-11-19T06:16:20.002Z</atom:updated>
            <content:encoded><![CDATA[<p><em>body mounted IMUs, LiDAR human tracking, camera posture events, and an error state UKF</em></p><p>Human motion tracking sounds straightforward: attach inertial sensors, integrate their measurements, and estimate how a person moves. My experiments quickly showed why that description is incomplete. Physical mounting, coordinate alignment, asynchronous timestamps, noisy target association, and measurement quality all matter before the filter can produce a meaningful result.</p><p>I built a C++ framework to investigate how five wearable IMUs can work with an external LiDAR based human tracker and camera derived posture observations. This is an engineering experiment, not a finished motion capture product. The goal is a modular pipeline where I can change sensor configurations, replay recorded sessions, and learn which constraints actually help.</p><p>This article describes acquisition on a Raspberry Pi, Python post processing, coordinate calibration, the error state UKF, and one representative recorded session. The clearest result is a trade off: camera posture updates barely changed 2D position RMSE but reduced the predicted 2D jerk RMS by about 11.5% in that session.</p><h3><strong>System overview</strong></h3><p>The wearable setup uses one IMU at the waist, one on each thigh, and one on each shank. All five devices are mounted on the anterior side of the body. An external 2D LiDAR pipeline estimates the human position and velocity. A camera pipeline contributes discrete posture information rather than full 3D joint coordinates.</p><pre>+------------------------+---------------------------------------------+--------------------------------------------------+<br>|         Input          |        Logged or derived observation        |             Role in this experiment              |<br>+------------------------+---------------------------------------------+--------------------------------------------------+<br>| Five wearable IMUs     | Acceleration, angular rate, magnetic field  | Segment orientation prediction; static detection |<br>| 2D LiDAR human tracker | Human cluster x, y and derived velocity     | Correct 2D global position and velocity          |<br>| Pi camera              | Video, then posture events after processing | Trigger posture dependent knee constraints       |<br>+------------------------+---------------------------------------------+--------------------------------------------------+</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzDz1F-ftjdsJ1IjIqMEdg.png" /><figcaption><em>Figure 1. Fusion architecture. The C++ replay layer orders measurements by timestamp. Gyroscope driven prediction and tracker or posture updates feed an error state UKF whose outputs include 2D motion, segment orientations, and numerical diagnostics.</em></figcaption></figure><p>Keeping the streams as time stamped events was a deliberate choice. Forcing every sensor to a single nominal sampling grid would hide irregular packet arrival and gaps. In replay, the measurements are merged and ordered by time; the prediction interval follows the elapsed time between processed events.</p><h3><strong>How I collect a session on Raspberry Pi</strong></h3><p>The data acquisition program is written in Python and runs several independent collectors in threads or background processes. It creates a time stamped session directory so that files from one run can be analyzed together. The Raspberry Pi acts as the local capture host, while the sensor fusion estimator runs later on the saved data.</p><pre>+-----------+--------------------------------------------------+--------------------------------------------------------------------------------------+<br>| Collector |                Transport and file                |                                What is actually saved                                |<br>+-----------+--------------------------------------------------+--------------------------------------------------------------------------------------+<br>| IMU 1–5   | MQTT topics from five Pico devices; one CSV each | Pico sensor time, Pi receive time, offset aligned time, ax/ay/az, gx/gy/gz, mx/my/mz |<br>| 2D LiDAR  | RPLidar serial connection; point CSV             | Pi timestamp, scan angle, distance, converted x/y, return quality                    |<br>| Pi camera | rpicam-vid or libcamera-vid; H.264 video         | 1280 × 720 video; optional MP4 remux using ffmpeg                                    |<br>+-----------+--------------------------------------------------+--------------------------------------------------------------------------------------+</pre><h4>Recording protocol</h4><p>A simple on screen countdown keeps the procedure repeatable: 30 seconds to prepare, 30 seconds standing still, 15 seconds of the prompted forward walking or leg movement, a manually stopped dynamic motion period, and another 30 seconds standing still. The collectors start after preparation and stop after the final static segment. The two stationary periods help establish and check the IMU baseline; the motion segment supplies variation for calibration and testing.</p><h4>Timestamp alignment is approximate</h4><p>The Pi stamps the LiDAR samples with its local epoch time. For each IMU MQTT topic, the script estimates one offset from the first received packet: offset = Pi receive time − Pico sensor time. It records aligned_ts = Pico sensor time + offset, alongside both original times. This is a practical software alignment step, not hardware synchronization. Network latency on the first packet, clock drift, packet bursts, and missing samples can still affect alignment. The video recorder in this script does not directly write a per frame timestamp CSV.</p><p>After capture, a second Python program generates the clean files and diagnostic figures. It normalizes timestamps, processes raw LiDAR points into a human cluster, derives tracker velocity, and runs YOLOv8 nano pose estimation on recorded video. The C++ replay program then reads *_imuN_clean.csv, *_human_cluster_clean.csv, and *_valid_human_timeline.csv. Data capture, perception, and fusion are separate computational stages.</p><h4>How the human cluster is extracted</h4><p>The LiDAR processing builds a background occupancy grid with 0.15 m cells from the first 30 seconds of data, when the subject is expected to stand still. Later points falling in known background cells are removed. The code forms overlapping 100 ms LiDAR windows at 50 ms steps. The cluster seed is selected near the previous position, subject to a distance check. Nearby foreground points within a 0.3 m radius are averaged to estimate x and y. Velocity is then estimated using position differences across a history of eight windows.</p><p>This is a lightweight association algorithm, not a trained semantic human detector. Its dependence on background occupancy, and continuity from the previous cluster explains why it can fail near a wall or after a wrong association. The script also exports foreground points, the background model, and tracking debug videos, which are valuable when inspecting these failures.</p><h4>How camera posture events are generated</h4><p>The same post processor uses a YOLOv8n pose model to locate 17 image keypoints, tests whether the body is visible and approximately front facing, and compares standing geometry with a subject specific reference learned early in the recording. It then writes a posture timeline. These are categorical posture cues used by the UKF for intermittent anatomical pseudo measurements, not direct 3D camera joint coordinates.</p><h3><strong>What the input data looks like</strong></h3><p>The following plots come from one selected session. They illustrate the inputs and timing behavior of a real indoor recording, rather than a controlled laboratory benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlxHJdy0GjjNqc4VbSJnqw.png" /><figcaption><em>Figure 2. Human cluster X and Y measurements over time after LiDAR point processing. Repeated movements and pauses are visible, but this plot alone cannot prove that every associated cluster belongs to the person.</em></figcaption></figure><p>The human cluster plot is especially useful for debugging. It is tempting to treat a smooth position trace as a correct target trace, but a tracker can be confidently wrong when it associates background returns with the person. The background model includes the initial standing period, and an associated position is propagated as the next window’s reference. I later found that proximity to a wall is one of the more difficult cases in my apartment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-rQvMG3RHibfb4MMNvZtQ.png" /><figcaption><em>Figure 3. Recorded inter arrival timing variations for five IMU streams, and LiDAR points. Each panel subtracts the median inter arrival interval of that stream. Large spikes indicate timing gaps or bursts in the logged data.</em></figcaption></figure><p>The timing plot also explains the value of event based replay. The IMU streams show occasional long gaps, while the LiDAR point stream has a reported median inter point interval of 0 ms at millisecond timestamp resolution. That zero is not a LiDAR scan rate. A single global sampling rate would conceal these differences.</p><h3>IMU calibration from sensor axes to body segments</h3><p>All IMUs face forward, but that does not mean every device is perfectly aligned to its corresponding body segment. Straps can twist, the mounting surface can move, and each segment has a different physical orientation. I therefore distinguish three frames: the chip fixed IMU frame I, the anatomical segment frame S, and a global world frame W.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xih8H1VwnRTPwqB7BXia4g.png" /><figcaption><em>Figure 4. Front mounted sensor geometry and the IMU, segment, and world frames. The calibration matrix R(S←I) converts sensor coordinates to anatomical segment coordinates. R(W←S) then expresses the segment in the global reference frame.</em></figcaption></figure><p>In my mounting convention, the sensor X axis points approximately downward in a standing pose, Y is approximately lateral, and Z points outward from the anterior side of the body. For the anatomical segment frame, X is anterior, Y is the dominant hinge direction, and Z points distally along the limb at rest. The world frame is fixed relative to the environment and does not rotate with the body.</p><h4>Static gravity and gyroscope PCA</h4><p>I first average acceleration during a stationary period to estimate a gravity related reference direction. This anchors the limb axis during calibration; it does not mean the segment axis remains aligned with gravity once the leg moves. During calibration motion, I analyze the gyroscope covariance matrix and use its dominant PCA (Principal Component Analysis) eigenvector to estimate the principal hinge like rotation axis. Cross products and orthogonalization complete the local segment frame.</p><p>PCA eigenvectors have an unavoidable sign ambiguity. I apply sign consistency checks rather than assuming that the raw principal component has the correct anatomical direction. The resulting rotation matrices encode coordinate changes. With the convention that R(A←B) maps coordinates from B to A, the full chain is R(W←I) = R(W←S) · R(S←I).</p><h3>The error state unscented Kalman filter</h3><p>The C++ estimator maintains 2D position (x, y), 2D velocity (vx, vy), five orientation quaternions, and five three axis gyroscope biases. That is 39 nominal state values. The uncertainty representation has 34 dimensions because each unit quaternion uses a local three dimensional rotation error rather than four independent quaternion errors.</p><p>The UKF generates sigma points in this local error space. Quaternion boxplus and boxminus operations apply and compare small rotations without breaking the unit norm constraint. Gyroscope measurements, corrected by estimated bias, propagate the corresponding segment orientation. Each IMU has an accumulated elapsed time so a new angular rate sample can use its own interval.</p><p>In this implementation, IMUs and LiDAR serve different purposes. The IMU gyroscopes are primarily used to estimate body-segment orientations. For 2D position tracking, the UKF uses a constant-velocity model to predict motion between measurements. This means the filter temporarily assumes that the current velocity remains unchanged until new information becomes available.</p><p>LiDAR-derived human tracking measurements then update the estimated position and velocity. Although IMU acceleration could also be integrated to estimate movement, small sensor biases and errors in gravity compensation can accumulate into significant position drift. Therefore, this implementation does not directly use acceleration to predict 2D translation.</p><h4>Measurement updates and diagnostics</h4><p>The tracker supplies 2D position and velocity updates. A stationary detector checks accelerometer norm and gyroscope activity and can trigger a zero velocity pseudo measurement (ZUPT). Camera posture events can activate an experimental knee angle constraint derived from relative thigh and shank quaternion orientation. In other words, the camera does not directly provide 3D joint locations to this filter.</p><p>For each update, I monitor innovation and normalized innovation squared (NIS), alongside covariance matrices and numerical checks. The NIS can flag a measurement that is inconsistent with predicted uncertainty, but it cannot guarantee that a LiDAR cluster is the correct person. A false target association may still appear plausible enough to pass a statistical gate.</p><h3>A representative comparison with and without camera updates</h3><p>I compared two replay configurations on the selected recording and added the measured and predicted jerk values from the same session summary. The trajectory plots include a static background model, a tracker derived reference labeled “Measurement Ground Truth” in the plotting script, and the UKF predictions. This reference is not an independent motion capture ground truth, so the reported RMSE values quantify agreement with the tracker output, not absolute accuracy in the room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDYG6pfaS20aM1Bj6Niq1w.png" /><figcaption><em>Figure 5. Trajectory using IMUs and LiDAR derived tracking, without camera posture updates. The plot reports 2D RMSE = 1.6436 m relative to its tracker derived reference.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mJmOYQdTESaokaNxsAfaZg.png" /><figcaption><em>Figure 6. The same recorded session with camera posture updates enabled. The plot reports 2D RMSE = 1.6446 m. The result is effectively unchanged in this metric and slightly higher numerically.</em></figcaption></figure><p>The new comparison table adds an important dimension to that result: predicted jerk. The image based posture updates did not improve the position or velocity RMSE here, but the estimated trajectory has a lower reported jerk RMS. The measured reference jerk is unchanged between runs, as expected because both configurations use the same data.</p><pre>+------------------------------------+----------------+-------------+--------------------+<br>| Metric for session 20261003_155157 | Without camera | With camera | Change with camera |<br>+------------------------------------+----------------+-------------+--------------------+<br>| 2D position RMSE (m)               |       1.643635 |    1.644552 | +0.06%             |<br>| 2D velocity RMSE (m/s)             |       0.776044 |    0.776298 | +0.03%             |<br>| Predicted 2D jerk RMS (reported)   |       4345.971 |    3847.187 | −11.48%            |<br>| Measured 2D jerk RMS (reported)    |        28.6396 |     28.6396 | unchanged          |<br>+------------------------------------+----------------+-------------+--------------------+</pre><p>This is evidence of a lower calculated jerk metric in one replay, not proof of more accurate human motion. The predicted jerk values are orders of magnitude larger than the measured reference jerk. Because jerk is a third time derivative, short timing gaps and step like estimate corrections can magnify it substantially. Before making a smoothness claim, I need to verify units, sample spacing, derivative method, outlier handling, and repeatability across sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6GRyUAiHu-ntAznbFMTKOA.png" /><figcaption><em>Figure 7. With camera enabled, time series of x/y position and x/y velocity compared with the same tracker derived reference. The plots include sharp outliers and startup transients; component RMSE values should not be interpreted as an independent absolute accuracy test.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tV1pKtQXSmgy_UIi8jslg.png" /><figcaption><em>Figure 8. Position and velocity innovation residuals from the UKF replay with camera posture updates enabled. The four plots show the residuals for the X and Y components of position and velocity. Occasional spikes indicate discrepancies between measurements and predictions, but they do not independently identify the source of the error.</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AykhKO-GnOWoxi51hJLmKQ.png" /><figcaption><em>Figure 9. Per axis position and velocity normalized innovation diagnostics in the camera enabled run. The plotting script overlays 5.99, a 95% reference for a joint two dimensional NIS, so the red guide should not be interpreted as the applied per axis rejection threshold.</em></figcaption></figure><p>A diagnostic detail matters here: the C++ update functions gate the joint two dimensional position and velocity innovations at NIS = 9.21 (99% for two degrees of freedom). The saved log plots show separate x and y normalized squared residuals, while the red guide is 5.99 (95% for two degrees of freedom). Therefore, an individual curve crossing the red line does not establish that the runtime gate rejected a measurement. A future diagnostic figure should plot the joint NIS against the actual gate, with any per axis reference using the matching one dimensional distribution.</p><h3><strong>The hard parts are often upstream of the filter</strong></h3><h4>Separating a person from the wall</h4><p>My home testing area is smaller than the LiDAR nominal sensing range. The challenge is not that the LiDAR cannot reach far enough; it is that I sometimes walk near a wall while performing the forward motion segment of IMU calibration. Human and background returns then become hard to separate. In some runs the human clustering pipeline appears to combine wall returns with the moving person or switch associations, creating a physically incorrect position trace.</p><p>If that contaminated trace is used as a position or velocity correction, the UKF can be pulled away from the actual motion. The cause is upstream in segmentation and data association, even though it appears downstream as an estimation error. A better pipeline would inspect cluster continuity, geometry, confidence, and distance to known background before accepting a human track; I have not yet established that those checks solve the problem.</p><h4>More IMUs did not automatically improve the answer</h4><p>I also found that using all five IMUs did not consistently outperform a simpler waist sensor configuration in earlier experiments. This is a useful warning about expanding the state vector. Extra devices introduce additional calibration and bias parameters and may have limited observability if the measurement model does not constrain their orientation strongly enough. Loose mounting is another plausible error source.</p><p>Rather than assuming that a five sensor configuration must win, I want to evaluate waist only, waist plus selected limb sensors, and all five sensors under the same replay data and diagnostic criteria. That experiment can isolate whether the performance limit is calibration, temporal alignment, measurement design, or target detection.</p><h4>Timing and visual posture constraints</h4><p>Asynchronous events are manageable, but capture timing is not the same as accurate time synchronization. First packet offset alignment can drift and does not account for every transport delay. Camera posture classifications are also lower bandwidth observations whose timestamps must be registered to the IMU and tracker streams. Improving this time alignment is part of the measurement problem, not just a logging detail.</p><h3>Conclusion</h3><p>This project began as a way to combine five wearable IMUs. It has become a practical lesson in acquisition, timing, calibration, target association, uncertainty modeling, and estimation. In the selected run, the camera reduced reported predicted jerk RMS but not 2D RMSE. The error state UKF matters, but the meaning and reliability of its measurements matter just as much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63b0270857a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When More Sensor Data Makes a UKF Worse]]></title>
            <link>https://medium.com/@xvegcm/when-more-sensor-data-makes-a-ukf-worse-76afc3e8397d?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/76afc3e8397d</guid>
            <category><![CDATA[human-motion]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <category><![CDATA[imu-sensor]]></category>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 05:42:20 GMT</pubDate>
            <atom:updated>2026-09-08T05:53:16.533Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What a waist-mounted IMU taught me about drift, missing measurements, and knowing when to trust a sensor</em></p><p>I expected a waist-mounted IMU to improve my human-motion tracker. Instead, feeding its acceleration into the Unscented Kalman Filter (UKF) made the estimate drift farther, spike harder, and recover more slowly.</p><p>The baseline’s 2D position error was 0.074 m. When I added waist acceleration as a state and measurement, it rose to 1.610 m.</p><p>That was the result I needed to understand. I had added a signal that seemed directly relevant to motion. Why was the filter doing worse?</p><p>I compared four configurations on the same dataset. The results changed how I think about sensor fusion: a measurement only helps when the model can interpret what it measures, when it arrives, and how much uncertainty it carries.</p><h3>The tracker behind the experiment</h3><p>My prototype combines one LiDAR with five IMUs to track planar human motion. LiDAR provides position and velocity observations for a tracked human cluster. The IMUs support orientation and gyroscope-bias estimation for the lower body.</p><p>IMU1 and IMU2 sit on the left and right shanks, near the ankles. IMU3 and IMU4 sit on the thighs, near the knees. IMU5 sits at the waist.</p><p>The baseline has 39 state components: planar position and velocity, plus a four-component quaternion and a three-axis gyroscope bias for each of the five IMUs. One experimental version adds two waist-acceleration components, bringing the total to 41.</p><p>The key question was whether waist acceleration could improve the translational estimate between LiDAR updates.</p><h3>Why acceleration seemed like the obvious next step</h3><p>The idea was straightforward: use acceleration to predict how velocity and position change. In simplified form:</p><p>v(k+1) = v(k) + a_W(k) × Δt<br> p(k+1) = p(k) + v(k) × Δt + ½ a_W(k) × Δt²</p><p>Here, a_W is the planar acceleration input derived from the waist IMU. The equations are familiar. The difficult part is deciding whether that input actually represents the motion being tracked.</p><p>A sensor attached to the waist also picks up local body motion and walking impacts. Gravity leakage, frame-alignment error, accelerometer bias, calibration error, and timestamp mismatch can all contaminate the signal used for prediction.</p><p>Once those errors enter the prediction, they accumulate in velocity and then position.</p><p>That becomes especially troublesome when LiDAR updates disappear. Acceleration keeps arriving, but valid human-cluster measurements can have gaps. During those gaps, the filter continues propagating motion with less external information to correct it.</p><h3>Four ways to run the same data</h3><p>I kept cross-covariance handling and the rest of the evaluation pipeline unchanged, then compared four configurations:</p><pre>Table 1. Four configurations tested on the same dataset.<br>+----------------------------------+---------+------------------------+----------------------+<br>|          Configuration           | States  |        Control         |     Measurements     |<br>+----------------------------------+---------+------------------------+----------------------+<br>| Baseline                         | 39      | None                   | LiDAR px, py, vx, vy |<br>| Accel. state                     | 41      | None                   | LiDAR + ax,W, ay,W   |<br>| Accel. control                   | 39      | ax,W, ay,W             | LiDAR px, py, vx, vy |<br>| Filtered LiDAR                   | 39      | None                   | Moving-average LiDAR |<br>| Value 1                          | Value 2 | 123                    | 10.0                 |<br>| Separate                         | cols    | with a tab or 4 spaces | -2,027.1             |<br>| This is a row with only one cell |         |                        |                      |<br>+----------------------------------+---------+------------------------+----------------------+<br><br></pre><p>In the tables, “Accel. state” means acceleration as a state and measurement; “Accel. control” means acceleration as a control input. These runs compare two ways of introducing acceleration and a simpler alternative: smoothing the LiDAR input.</p><h4>Two safeguards were already in place</h4><p>The filter applies approximate joint limits to each sigma point. Sensor measurements are transformed into body-segment and world frames so relative segment rotations can be checked.</p><p>For this setup, only hip and knee constraints are applied. There are no foot-mounted IMUs, so the ankle ranges listed in the broader model are not active constraints in this experiment.</p><pre>Table 2. Model joint-angle ranges. Only hip and knee limits are applied in this experiment.<br>+----------------------------------+---------+---------------------------------------+-------------------+<br>|              Joint               |  Axis   |                Motion                 | Model range (deg) |<br>+----------------------------------+---------+---------------------------------------+-------------------+<br>| Hip                              | Pitch   | Extension (−) / flexion (+)           | -20 to +120       |<br>| Hip                              | Roll    | Adduction (−) / abduction (+)         | -30 to +45        |<br>| Hip                              | Yaw     | External (−) / internal (+)           | -45 to +45        |<br>| Knee                             | Pitch   | Flexion (−) / extension (0)           | -140 to 0         |<br>| Knee                             | Roll    | Varus (−) / valgus (+)                | -5 to +5          |<br>| Knee                             | Yaw     | External (−) / internal (+)           | -10 to +10        |<br>| Ankle                            | Pitch   | Dorsiflexion (−) / plantarflexion (+) | -20 to +50        |<br>| Ankle                            | Roll    | Inversion (−) / eversion (+)          | -30 to +25        |<br>| Ankle                            | Yaw     | External (−) / internal (+)           | -20 to +20        |<br>| Value 1                          | Value 2 | 123                                   | 10.0              |<br>| Separate                         | cols    | with a tab or 4 spaces                | -2,027.1          |<br>| This is a row with only one cell |         |                                       |                   |<br>+----------------------------------+---------+---------------------------------------+-------------------+<br><br></pre><p>These are implementation limits for this experiment, not clinical reference ranges.</p><p>A zero-velocity update (ZUPT) also sets vx and vy to zero when accelerometer and gyroscope signals from all five IMUs satisfy their stationary thresholds. That helps during confirmed stationary periods, but it cannot remove every error accumulated while the person is moving.</p><h3>The trajectory told the story first</h3><p>The baseline and filtered-LiDAR runs stayed near the LiDAR-derived reference path. Both runs using waist acceleration developed large excursions. The acceleration-as-state version diverged most severely.</p><figure><img alt="Trajectory comparison across the four configurations. Both acceleration-based runs drift away from the reference path." src="https://cdn-images-1.medium.com/max/1024/1*-6No3PNBN6xXLDTWXOs9xA.png" /><figcaption>Trajectory comparison across the four configurations. Both acceleration-based runs drift away from the reference path.</figcaption></figure><p>The 2D position RMSE was 0.074 m for baseline, 1.610 m for acceleration as a state and measurement, 0.487 m for acceleration as a control input, and 0.092 m for filtered LiDAR.</p><p>These errors describe agreement with the reference used in this experiment. The trajectory reference is LiDAR-derived, so the comparison should not be read as independent motion-capture validation.</p><h3>The gaps mattered as much as the measurements</h3><p>Looking at the time series helped explain the failure. Acceleration remained available through gaps in valid LiDAR human-cluster observations. The largest state excursions appeared around intervals when the translational measurement constraint was missing or weakened.</p><figure><img alt="Position, velocity, and input availability over time. Acceleration remains available through gaps in valid human-cluster measurements." src="https://cdn-images-1.medium.com/max/1024/1*m3LMzeoDx0Ag-UWe4zymVg.png" /><figcaption>Position, velocity, and input availability over time. Acceleration remains available through gaps in valid human-cluster measurements.</figcaption></figure><p>That alignment does not prove that every spike came from a LiDAR dropout. It is consistent with a filter integrating an imperfect acceleration signal during periods when external corrections are limited.</p><h3>What innovation and NIS added</h3><p>A trajectory shows where the estimate went. Innovation shows how strongly a new measurement disagrees with the filter’s prediction.</p><p>Normalized innovation squared (NIS) expresses that disagreement relative to the predicted uncertainty. Large spikes can signal that the model and measurements are disagreeing more than the uncertainty model expects.</p><figure><img alt="Innovation comparison. The acceleration-driven configurations show the largest residual spikes." src="https://cdn-images-1.medium.com/max/1024/1*UnXXU-fN2BMV1UGVwK8puw.png" /><figcaption>Innovation comparison. The acceleration-driven configurations show the largest residual spikes.</figcaption></figure><figure><img alt="NIS comparison with the plotted 95% threshold. Isolated excursions highlight periods of strong model–measurement disagreement." src="https://cdn-images-1.medium.com/max/1024/1*mNa5kPXX6CfCMJdfVlUNCg.png" /><figcaption>NIS comparison with the plotted 95% threshold. Isolated excursions highlight periods of strong model–measurement disagreement.</figcaption></figure><p>A small average NIS is not automatically better. It can reflect conservative covariance, and an average can hide short periods of poor behavior. I read these statistics alongside RMSE, smoothness, and the time-series plots.</p><h3>The accuracy–smoothness tradeoff</h3><p>Here are the component errors and predicted jerk RMS from the same evaluation. Position RMSE is in meters; velocity RMSE is in meters per second. Jerk values are reproduced as reported by the evaluation pipeline.</p><pre>Table 3. Tracking error and predicted jerk.<br>+----------------+------------+------------+---------------+---------------+-------------+<br>| Configuration  | RMSE x (m) | RMSE y (m) | RMSE vx (m/s) | RMSE vy (m/s) | 2D jerk RMS |<br>+----------------+------------+------------+---------------+---------------+-------------+<br>| Baseline       |      0.047 |      0.057 |         0.095 |         0.219 |   9,568.636 |<br>| Accel. state   |      1.471 |      0.656 |         0.749 |         0.382 |  17,413.871 |<br>| Accel. control |      0.311 |      0.374 |         0.291 |         0.369 |  21,391.233 |<br>| Filtered LiDAR |      0.060 |      0.070 |         0.117 |         0.232 |   3,333.011 |<br>+----------------+------------+------------+---------------+---------------+-------------+</pre><p>The reported measured-data jerk RMS was 29.485. The absolute jerk values depend on the differentiation and timing used in the evaluation, so I treat them as pipeline-specific smoothness diagnostics.</p><p>Baseline gave the lowest position and velocity error. Filtered LiDAR reduced predicted jerk by about 65% relative to baseline, with slightly higher RMSE. Both acceleration configurations were less accurate and had higher predicted jerk.</p><h4>The consistency numbers need context</h4><p>The mean NIS values provide another view of model–measurement agreement:</p><pre>Table 4. Mean NIS for position and velocity components.<br>+----------------+--------+--------+--------+--------+<br>| Configuration  | NIS px | NIS py | NIS vx | NIS vy |<br>+----------------+--------+--------+--------+--------+<br>| Baseline       |  0.376 |  0.537 |  0.296 |  0.349 |<br>| Accel. state   |  0.376 |  0.537 |  0.321 |  0.364 |<br>| Accel. control |  0.376 |  0.537 |  0.300 |  0.351 |<br>| Filtered LiDAR |  0.325 |  0.303 |  0.050 |  0.065 |<br>+----------------+--------+--------+--------+--------+</pre><p>Filtered LiDAR had much lower mean velocity NIS. Its slightly worse RMSE is a reminder that lowering NIS alone does not establish a better tracker.</p><p>The evaluation also reported the percentage of samples outside the P05–P95 NIS band:</p><pre><br>+----------------+--------+--------+--------+--------+<br>| Configuration  | px (%) | py (%) | vx (%) | vy (%) |<br>+----------------+--------+--------+--------+--------+<br>| Baseline       | 12.779 | 15.843 | 24.087 | 26.454 |<br>| Accel. state   | 13.241 | 15.581 | 79.084 | 63.086 |<br>| Accel. control | 13.127 | 15.653 | 38.879 | 36.456 |<br>| Filtered LiDAR | 13.892 | 17.780 | 26.978 | 35.081 |<br>+----------------+--------+--------+--------+--------+</pre><p>The acceleration-as-state run had the largest reported outside-band percentages for velocity: 79.084% for vx and 63.086% for vy. The control-input version was also above baseline.</p><p>These are two-sided outside-band percentages, not counts of upper-threshold spikes alone. They should be interpreted together with the plotted NIS traces and the evaluation’s band definition.</p><h3>My interpretation: the input and model did not match</h3><p>The results point toward a mismatch between the waist-acceleration signal and the global translational model.</p><p>The waist IMU does not directly measure the planar acceleration of the LiDAR-tracked human cluster. Local motion and residual gravity or alignment errors can enter the prediction as if they were global translation. During measurement gaps, those errors have time to accumulate.</p><p>Treating acceleration as a deterministic control input can underrepresent that uncertainty. Adding it to the state and measurement vectors does not, by itself, resolve bias, timing, or the relationship between waist motion and the tracked position.</p><p>Because both acceleration configurations degraded, a larger state vector alone is not a sufficient explanation. This comparison does not isolate every possible cause, but it gives me a concrete place to investigate: how acceleration is represented and trusted.</p><h3>Plausible joint angles are not yet reliable gestures</h3><p>The relative-angle plots exposed a separate limitation. Joint constraints kept the estimates within plausible ranges, but the roll, pitch, and yaw signals still showed noise and occasional spikes.</p><figure><img alt="Left and right shank rotations relative to the thigh sensors. High-frequency variation and spikes limit gesture-level interpretation." src="https://cdn-images-1.medium.com/max/1024/1*nqrEzTqadAnMLH67VQzYiw.png" /><figcaption>Left and right shank rotations relative to the thigh sensors. High-frequency variation and spikes limit gesture-level interpretation.</figcaption></figure><figure><img alt="Left and right thigh rotations relative to the waist sensor. Pitch and yaw remain noisy across configurations." src="https://cdn-images-1.medium.com/max/1024/1*yk7qi3UnwgJ5771DZq2ILA.png" /><figcaption>Left and right thigh rotations relative to the waist sensor. Pitch and yaw remain noisy across configurations.</figcaption></figure><p>In this implementation, these estimates were not reliable enough for gesture-level interpretation. That does not establish a general limit for every IMU-and-LiDAR system. It shows that anatomical constraints alone were not enough here.</p><p>A future experiment could add camera-based pose keypoints, such as those from a YOLO-style pose model, to provide more direct observations of joint geometry.</p><h3>What I would change next</h3><p>For now, I would keep the constant-velocity translational baseline. It performed best on this dataset. From there, I would test changes one at a time.</p><p><strong>Make uncertainty explicit. </strong>Estimate accelerometer bias and residual gravity, and propagate acceleration uncertainty instead of treating the signal as exact.</p><p><strong>Check timing and availability. </strong>Align IMU and LiDAR timestamps carefully and account for delayed or intermittent measurements.</p><p><strong>Use acceleration more selectively. </strong>Test quality-based gating using motion state, LiDAR availability, and innovation behavior. Another option is to use acceleration to adapt process noise Q rather than directly drive position and velocity.</p><p><strong>Add joint observations. </strong>Test camera-based pose measurements where the current orientation estimates remain ambiguous.</p><p>Each change needs the same evaluation: position and velocity error, jerk, innovation, NIS behavior, and recovery after measurement gaps. A lower score in one column is not enough.</p><h3>The lesson I am taking forward</h3><p>On this dataset, the simplest translational model was the most accurate. Waist acceleration made the estimate worse through both routes I tested. Smoothing LiDAR offered a different tradeoff: a smoother output with a small increase in error.</p><p>I still see value in the accelerometer. The next step is to give its signal a model that accounts for what it measures, when it arrives, and how uncertain it is.</p><p>Before adding another sensor input, I now ask a more useful question: does the filter know when to trust it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76afc3e8397d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Low-Cost Multi-Sensor Human Detection and Tracking System]]></title>
            <link>https://medium.com/@xvegcm/low-cost-multi-sensor-human-detection-and-tracking-system-7c39bc13731f?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c39bc13731f</guid>
            <category><![CDATA[human-motion]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[lidar]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 07:15:06 GMT</pubDate>
            <atom:updated>2026-03-19T22:44:15.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>Human detection and tracking is a fundamental capability in many robotic and smart sensing systems.</p><p>Traditional approaches often rely heavily on cameras and computer vision models. However, camera-based systems introduce several challenges:</p><ul><li>privacy concerns</li><li>lighting sensitivity</li><li>computational requirements</li></ul><p>This project explores a <strong>privacy-preserving alternative</strong> using spatial sensing rather than visual imaging.</p><p>The system integrates multiple sensors including:</p><ul><li>LiDAR</li><li>Time-of-Flight (ToF) distance sensors</li><li>infrared presence sensors</li><li>wearable IMU sensors</li></ul><p>The prototype combines multiple sensing modalities and processes data through <strong>Python and C++ pipelines</strong> to detect and track human motion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3u1CuGPUz6DK14Ie6cm2pQ.jpeg" /><figcaption>Setup for Raspberry Pi 5 (main) and Lidar/TOF/IR Sensor</figcaption></figure><h3>2. System Architecture</h3><p>The system follows a <strong>multi-stage processing architecture</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hefFguPJPa-p2ibUBs32Cg.png" /><figcaption>System Architecture</figcaption></figure><h3>Data Pipeline</h3><pre>Sensors<br>   ↓<br>MQTT wireless transmission<br>   ↓<br>Python preprocessing<br>   - LiDAR clustering<br>   - constraint checking<br>   ↓<br>C++ sensor fusion / state estimation<br>   ↓<br>Human trajectory estimation</pre><h3>Sensor Inputs</h3><p>The current prototype integrates:</p><ul><li>LiDAR</li><li>ToF distance sensor</li><li>infrared presence sensor</li><li>wearable IMU sensors mounted on the heels</li></ul><p>Future extensions may include:</p><ul><li>fisheye cameras</li><li>additional IMU sensors for full-body tracking</li><li>radar sensing</li><li>multi-sensor spatial coverage</li></ul><h3>3. Hardware Components</h3><h3>LiDAR</h3><p><strong>Model:</strong> RPLIDAR A1</p><p>LiDAR is the <strong>primary sensing modality</strong>.</p><p>It provides <strong>2D scans of the surrounding environment</strong> and generates spatial point clouds used for:</p><ul><li>background mapping</li><li>human cluster detection</li><li>trajectory estimation</li></ul><p>However, LiDAR data often exhibits:</p><ul><li>sparsity</li><li>noise</li><li>fluctuating point returns between frames</li></ul><p>These characteristics require additional clustering and filtering methods.</p><h3>Time-of-Flight Distance Sensor</h3><p><strong>Sensor:</strong> VL53L1X</p><p>The ToF sensor measures the <strong>distance to objects directly in front of the system</strong>.</p><p>It is primarily used during <strong>system initialization</strong>.</p><p>At the beginning of the experiment:</p><ul><li>the human subject stands in front of the sensor</li><li>the ToF reading identifies the human location</li><li>LiDAR points corresponding to the human are removed from the background model</li></ul><h3>Infrared Presence Sensor</h3><p><strong>Sensor:</strong> STHS34PF80</p><p>This sensor detects:</p><ul><li>presence</li><li>motion</li></ul><p>Although it does not provide spatial information, it acts as a <strong>confirmation signal for human activity in the sensing region</strong>.</p><h3>Wearable IMU Sensors</h3><p>The system also explores <strong>wearable IMU sensors attached to the human body</strong>.</p><p>The IMU module used in this prototype is:</p><p><strong>Adafruit ICM-20948 9-DoF IMU</strong><br> (MPU-9250 Upgrade)</p><p>The ICM-20948 integrates:</p><ul><li>3-axis accelerometer</li><li>3-axis gyroscope</li><li>3-axis magnetometer</li></ul><p>This <strong>9-degree-of-freedom inertial measurement unit</strong> provides motion information for:</p><ul><li>orientation estimation</li><li>motion detection</li><li>gait dynamics analysis</li><li>stationary state detection</li><li>inertial state estimation</li></ul><p>Compared with the older <strong>MPU-9250</strong>, the <strong>ICM-20948</strong> offers:</p><ul><li>improved noise performance</li><li>better integration with modern embedded systems</li></ul><h3>Wearable Sensor Node</h3><p>Each sensing unit contains:</p><ul><li>Raspberry Pi Pico W</li><li>Adafruit ICM-20948 IMU sensor module</li><li>wireless communication capability</li></ul><p>The IMU provides:</p><ul><li>accelerometer data</li><li>gyroscope data</li><li>magnetometer data</li></ul><p>Sensors can be attached to body locations such as:</p><ul><li>heels</li><li>limbs</li></ul><p>to capture motion dynamics during walking.</p><h3>Wireless Communication</h3><p>Each wearable node transmits IMU data wirelessly using <strong>WiFi MQTT communication</strong>.</p><p>Architecture:</p><pre>ICM-20948 IMU sensor<br>      ↓<br>Raspberry Pi Pico 2 W<br>      ↓<br>MQTT wireless transmission<br>      ↓<br>Main processing system (Raspberry Pi 5)</pre><p>This architecture allows the system to <strong>scale easily by adding additional IMU nodes</strong>.</p><h3>4. Experimental Protocol</h3><p>The experiment follows a simple protocol:</p><p><strong>30 s stationary → motion → 30 s stationary</strong></p><h3>First 30 seconds</h3><p>Used for:</p><ul><li>environment scanning</li><li>background modeling</li><li>tilt compensation</li><li>initialization of system parameters</li></ul><h3>Motion period</h3><p>Used to capture human movement and evaluate tracking performance.</p><h3>Final 30 seconds</h3><p>Reserved for:</p><ul><li>system calibration</li><li>validating system stability</li><li>possible correction methods</li></ul><h3>5. Background Modeling</h3><p>During the first 30 seconds, the LiDAR scans the surrounding environment.</p><p>Steps:</p><ul><li>scan the environment using LiDAR</li><li>discretize the space into grid cells</li><li>store background points in the grid</li></ul><p>The <strong>grid resolution</strong> strongly affects the background quality.</p><p>Trade-off:</p><p>Coarse grid</p><ul><li>stable</li><li>less spatial detail</li></ul><p>Fine grid</p><ul><li>higher detail</li><li>increased noise sensitivity</li></ul><p>This resolution requires further optimization.</p><h3>6. Human Removal in Background Model</h3><p>Human points must be removed before the background map is finalized.</p><p>Current approach:</p><ul><li>construct the background using LiDAR data</li><li>use ToF distance measurement to identify the human location</li><li>remove those LiDAR points from the background</li></ul><h3>Limitation</h3><p>Some human points may already be included in the background during initial scanning.</p><h3>Planned improvement</h3><p>Use a <strong>camera-based human detection system</strong> to remove human points before background construction, resulting in a cleaner background model.</p><h3>7. LiDAR-Based Human Detection</h3><p>After initialization, the system detects humans using <strong>LiDAR point clouds</strong>.</p><p>Because LiDAR points are sparse and noisy, the system performs <strong>human clustering</strong>.</p><p>Nearby LiDAR points are grouped together to form a <strong>human cluster</strong>, representing the estimated human location.</p><p>However, cluster centers may fluctuate due to noise.</p><h3>8. Temporal Constraint Tracking</h3><p>To maintain stable tracking across frames, the system applies a <strong>distance constraint</strong>.</p><pre>distance(current_cluster , previous_cluster) &lt; threshold</pre><p>If the cluster jump exceeds the threshold, it is considered:</p><ul><li>noise</li><li>false detection</li></ul><p>This constraint relies on the assumption that <strong>human motion speed is limited</strong>.</p><h3>9. Human Cluster Stability vs Precision</h3><p>An important experimental observation emerged.</p><p>Trying to make the cluster extremely precise sometimes causes the system to become unstable.</p><p>When the clustering algorithm aggressively follows individual LiDAR points:</p><ul><li>cluster jitter increases</li><li>tracking stability decreases</li></ul><p>Allowing slightly more variation in the cluster often produces <strong>more stable trajectory estimates</strong>.</p><p>This suggests:</p><blockquote><em>Measurement stability may be more important than instantaneous precision.</em></blockquote><h3>10. Sensor Coverage Limitations</h3><p>Another challenge occurs when the human temporarily leaves the LiDAR sensing region.</p><p>When this happens:</p><ul><li>the cluster disappears</li><li>trajectory gaps appear</li><li>noise increases</li></ul><p>Algorithm tuning alone cannot solve this problem.</p><p>The fundamental limitation is <strong>sensor coverage</strong>.</p><h3>Planned solution</h3><p>Deploy <strong>multiple sensors in different locations</strong> to increase coverage.</p><h3>11. Sensor Timing and Event-Driven Processing</h3><p>The system operates using an <strong>event-driven architecture</strong>.</p><p>Sensors transmit data asynchronously via <strong>MQTT</strong>.</p><p>Therefore:</p><ul><li>timestamps must be verified</li><li>incoming data must be sorted by time</li></ul><p>The filter updates <strong>only when new measurements arrive</strong>, without interpolation.</p><h3>12. State Representation</h3><p>The system currently uses a simplified state vector containing:</p><ul><li>position (x, y, z)</li><li>velocity (vx, vy, vz)</li></ul><p>Additionally, the architecture includes:</p><ul><li>orientation states</li><li>IMU bias states</li></ul><p>These bias states are currently included for <strong>future expansion</strong>, but are not actively calibrated.</p><h3>13. Motion Stabilization</h3><p>IMU orientation data obtained from the <strong>ICM-20948 sensor</strong> is used to detect stationary states.</p><p>When the system detects that the subject is stationary, it applies corrections similar to <strong>Zero Velocity Updates (ZUPT)</strong> used in inertial navigation.</p><p>Benefits:</p><ul><li>reduces drift accumulation</li><li>stabilizes trajectory estimation</li></ul><h3>14. Noise Modeling Insight</h3><p>Filtering experiments revealed an important insight.</p><p>Noise parameters <strong>P, Q, and R</strong> must include:</p><ul><li>an upper bound</li><li>a lower bound</li></ul><p>Maintaining these bounds prevents the filter from becoming <strong>overconfident</strong> and improves robustness to sudden motion changes.</p><p>If the noise becomes too small:</p><ul><li>the filter becomes overconfident</li><li>it fails to respond to sudden motion changes</li></ul><p>Maintaining a reasonable <strong>minimum noise bound</strong> improves adaptability.</p><h3>15. Results</h3><h3>Good Prediction Case</h3><p>Example trajectory showing <strong>stable human tracking</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaGouAvRH-5lpYrS82_tdQ.png" /><figcaption>Prediction/Measurement and Human Cluster Jittering for Good Prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gzt3Zycowg0HldTW4kEspg.png" /><figcaption>ZUPT/non-ZUPT for Good Prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7hqrvVjJITa3ImCh2rlcA.png" /><figcaption>Trajectory for Good Prediction</figcaption></figure><h3>Bad Prediction Case</h3><p>Example scenario where <strong>LiDAR cluster loss introduces trajectory gaps</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK1y2G4VRCyAiT-p4FGwHg.png" /><figcaption>Prediction/Measurement and Human Cluster Jittering for Bad Prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4-Hcgu210TilNMnqFlqLdQ.png" /><figcaption>ZUPT/non-ZUPT for Bad Prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gz445O5VJLVe4Fy6Kmac1A.png" /><figcaption>Trajectory for Bad Prediction</figcaption></figure><h3>16. Future System Improvements</h3><p>Several improvements are planned.</p><h3>Camera-Assisted Background Removal</h3><p>Use <strong>fisheye cameras</strong> to detect human locations during initialization and remove those points before building the background model.</p><h3>Multi-Sensor Expansion</h3><p>Future systems may incorporate additional sensors such as:</p><ul><li>radar sensors</li><li>additional IMUs</li></ul><p>Radar sensors may detect <strong>living motion signatures when LiDAR signals are weak</strong>.</p><h3>Multi-IMU System</h3><p>Expand from:</p><pre>2 IMU → multiple IMUs</pre><p>for <strong>full-body motion tracking</strong>.</p><h3>Multi-Sensor Coverage</h3><p>Deploy sensors in <strong>multiple positions</strong> to reduce tracking gaps.</p><h3>17. Prototype Wearable Node</h3><p>Wearable sensing nodes currently consist of:</p><ul><li>Raspberry Pi Pico 2W</li><li>ICM-20948 IMU sensor modules</li></ul><p>These nodes provide a <strong>low-cost and lightweight platform</strong> for collecting motion data during experiments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEUBlq8TINIhTpBhb-4yoA.jpeg" /><figcaption>Pico 2 W + IMU</figcaption></figure><h3>18. Conclusion</h3><p>Building a <strong>real-world sensing system</strong> reveals many practical challenges that are often not visible in theoretical algorithms.</p><p>Key lessons from this prototype include:</p><ul><li>sensor coverage can be more important than algorithm tuning</li><li>measurement stability may matter more than instantaneous precision</li><li>noise parameter bounds strongly influence filter behavior</li><li>asynchronous sensor systems require careful data handling</li></ul><p>The long-term goal is to build a <strong>scalable multi-sensor platform for human motion tracking and robotics applications</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c39bc13731f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sensor Fusion for Dummies (Mechanical Engineer Edition) III]]></title>
            <link>https://medium.com/@xvegcm/sensor-fusion-for-dummies-mechanical-engineer-edition-iii-1831fcb70ed4?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/1831fcb70ed4</guid>
            <category><![CDATA[sensors]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[dummies]]></category>
            <category><![CDATA[sensor-fusion]]></category>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Wed, 24 Sep 2025 07:10:49 GMT</pubDate>
            <atom:updated>2025-09-24T18:37:44.425Z</atom:updated>
            <content:encoded><![CDATA[<p>Sensor Fusion for Dummies (Mechanical Engineer Edition) III</p><h3>💡 2D vs 3D Sensor Fusion on a Low-Cost Raspberry Pi Platform</h3><p>Transitioning from a planar (2D) UKF to a full 3D, quaternion-aware UKF significantly improves heading stability in real-world driving, enabling more accurate handling of tilt, elevation changes, and complex turns. Although this upgrade increases total processing time by roughly 36% on the same dataset, it provides a strong foundation for robust long-duration navigation. The remaining challenge is long-horizon yaw robustness, where targeted tuning of quaternion updates and gyro-bias management will deliver the greatest stability gains.</p><h3>⚖️ 2D vs 3D Sensor Fusion</h3><p>In the transition from 2D to 3D sensor fusion, we introduced full quaternion-based orientation tracking, extended velocity and acceleration to 3 axes (x, y, z), and added tilt-compensated magnetometer integration. This enables full 6-DOF motion tracking and better handling of real-world navigation scenarios with elevation changes, roll/pitch variations, and dynamic heading shifts.<br> <br>Interestingly, although 2D models seem simpler, 2D sensor fusion is often harder to match to real-world data. Key limitations include:</p><ul><li>Lack of full orientation context: Without roll and pitch correction, 2D heading (theta) can misrepresent the actual direction of movement, especially when the device is tilted.</li><li>No tilt compensation: Accelerometer measurements can be misinterpreted when the platform is not level, leading to incorrect velocity or position updates.</li><li>Weak heading constraints: GPS or velocity data alone provide insufficient heading information, making the filter prone to divergence or unstable theta estimates.</li><li>Model mismatch: Real-world motion often occurs in a tilted 3D space, while 2D filters assume perfect planarity — this leads to degraded performance and poor residual matching.<br> <br>In tests, 2D filters often showed worse heading stability and higher position drift compared to the full 3D model, especially in segments involving turns or elevation change.</li></ul><h3>🛠️ What I Built</h3><p>I designed a low-cost, real-time sensor fusion system on a Raspberry Pi to estimate outdoor vehicle motion.</p><ul><li>Hardware:<br>- Raspberry Pi 5 (main controller)<br>- Adafruit 9-DOF IMU (LSM9DS1, I2C)<br>- Adafruit GPS module (PA1616S, I2C)<br>- Adafruit Barometric Pressure and Altimeter (BMP390, I2C)</li><li>Sampling Rates:<br>- Accelerometer: 50 Hz<br>- Gyroscope: 50 Hz<br>- Magnetometer: 20 Hz<br>- GPS: 10 Hz<br>- Barometric Pressure and Altimeter: 1 Hz</li><li>Software:<br>- C++ with multithreaded data logging<br>- Python for visualization and analysis</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lxCap7Mqad__fSOXKLyMQ.jpeg" /><figcaption>Raspberry Pi 5 for Sensor Fusion Data Collection</figcaption></figure><h3>📊 UKF State Design</h3><ul><li>2D UKF State:<br>- State vector (13-D): [x, y, vx, vy, ax, ay, qw, qx, qy, qz, bgx, bgy, bgz]<br>- Measurement vector (7-D): [x, y, vx, vy, ax, ay, yaw]</li><li>3D UKF State<br>- State vector (16-D): [x, y, z, vx, vy, ax, ay, az, qw, qx, qy, qz, bgx, bgy, bgz]<br>- Measurement vector (9-D): [x, y, z, vx, vy, ax, ay, az, yaw]</li></ul><h3>🔑 Key Functions in C++ UKF Development</h3><ul><li>⏱ Timestamp Event-Triggered Sync — Avoids artificial interpolation.</li><li>🔄 Sigma Point Generation &amp; Quaternion Handling — Uses tangent space for quaternions to avoid instability.</li><li>⚖️ Adaptive Q/R Tuning — Dynamically adjusts noise covariances using innovations and NIS statistics.</li><li>🛡 Heading-Only Fallback — Stabilizes heading without disrupting translational states.</li><li>📐 Tilt Compensation &amp; Correction — Initializes with accelerometer + magnetometer; continuously corrects drift.</li><li>🧹 Covariance Conditioning — Maintains positive-definite covariance matrix.</li><li>🔽 Filtering — Low-pass and moving-average filters smooth noisy sensor data.</li><li>🌱 Bias Decay / Regularization — Adds a small decay term to bias states to prevent long-term drift.</li><li>📊 Decoupled Adaptive Noise Tuning — Tunes Q and R separately on each axis.</li><li>🔄 ZUPT Zero Velocity — Detects stationarity and zeroes velocity when appropriate.</li></ul><h3><strong>📊 Fusion Comparison Results</strong></h3><p>🔎 Plot Insights</p><p>From the estimated vs. measured trajectories, the 3D filter produces a smoother, more physically consistent path, particularly during turns and elevation changes. Innovation-vs-time plots show smaller residuals and higher chi-square consistency in 3D, while quaternion and Euler angle plots highlight significantly more stable yaw and tilt behavior. Gyro-bias curves confirm stronger long-term drift suppression in 3D.<br> <br> These visual comparisons reinforce the numerical results: 3D sensor fusion not only reduces heading RMSE but also improves vertical estimation and long-horizon stability, all at a moderate increase in computation time (~36%).</p><p>We evaluated multiple IMU sensor fusion datasets using the same UKF-based architecture but with different filter settings and conditions.<br> <br> Comparison of 2D and 3D sensor fusion:</p><ul><li>Process Time<br>- 2D total process time: 1011.4 s<br>- 3D total process time: 1378.9 s <br>- increase: ~36%</li><li>RMSE metrics<br>- 2D RMSE_x: 3.33 | RMSE_y: 2.72 | RMSE_theta: 0.73<br>- 3D RMSE_x: 3.36 | RMSE_y: 2.68 | RMSE_z: 1.57 | RMSE_theta: 0.48</li></ul><h3>Trajectory Plots (Estimated vs Measured)</h3><ul><li><strong><em>2D<br>- </em></strong>Vehicle trajectory shows clear lateral offsets from GPS measurements, especially at turns.<br>- During elevation changes, x/y trajectory errors grow larger, matching the reported RMSE_x ≈ 3.3 m and RMSE_y ≈ 2.7 m.<br>- Heading (theta) exhibits abrupt jumps, creating slight “jitters” in the path during sharp turns.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2oXe40PzoihQT2_RuuvFag.png" /><figcaption>Comparison of Estimated/Measurement for 2D Sensor Fusion</figcaption></figure><ul><li><strong><em>3D<br>- </em></strong>On the same curved and sloped segments, the estimated trajectory closely follows GPS, with errors distributed more evenly.<br>- The 3D filter’s z-axis (altitude) estimate aligns well with barometer trends, with RMSE_z ≈ 1.6 m, indicating strong vertical reconstruction capability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*fTvBNAS00ZavV_ImZrGD0g.png" /><figcaption>Comparison of Estimated/Measurement for 3D Sensor Fusion</figcaption></figure><blockquote>Takeaway<br> The 3D filter maintains continuity and consistency in both horizontal and vertical directions, making it especially suitable for real-world scenarios with slopes or multi-level roadways.</blockquote><h3>Innovation vs Timestamp</h3><ul><li><strong><em>2D<br>- </em></strong>Residuals (innovations) remain offset from zero for extended periods, and sharp spikes appear in velocity (vx, vy) and heading (theta).<br>- NIS_vel mean is only about 0.43, showing that the filter is overconfident in its velocity model and under-fits the measurements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ObUqwL_ikIjCu0wyW_venA.png" /><figcaption>NIS for 2D Sensor Fusion</figcaption></figure><ul><li><strong><em>3D<br>- </em></strong>Residuals in xy and z directions stay closer to zero, consistent with NIS_pos_xy ≈ 4.05 and NIS_pos_z ≈ 0.11.<br>- Although xy-plane NIS is somewhat high, its ~50% coverage is reasonable for a multi-dimensional state.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*4DCty4jFIM0E4FNO6FwKxQ.png" /><figcaption>NIS for 3D Sensor Fusion</figcaption></figure><blockquote>Takeaway<br> The 3D system better absorbs complex real-world error structures and provides a clear advantage on the vertical (z) axis.</blockquote><h3>Quaternion and Euler Angle Stability</h3><ul><li><strong><em>2D<br>- </em></strong>Quaternion components show sudden jumps during sharp turns; yaw (theta) exhibits discontinuities.<br>- This corresponds to RMSE_theta ≈ 0.73 rad (~42°), indicating relatively unstable heading estimation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ZtfmE4R3VIJZJNQT1EddKQ.png" /><figcaption>Euler Angle for 2D Sensor Fusion</figcaption></figure><ul><li><strong><em>3D<br>- </em></strong>Quaternion traces remain smooth across all axes, and pitch and roll evolve naturally without abrupt changes.<br>- RMSE_theta drops to ≈ 0.48 rad (~27°), a significant improvement in heading stability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*BVQg0RToYC27DQ_xKbEyxg.png" /><figcaption>Euler Angle for 3D Sensor Fusion</figcaption></figure><blockquote>Takeaway<br> Thanks to Markley quaternion averaging and tilt compensation, the 3D filter delivers more reliable heading estimation and long-term continuity.</blockquote><h3>Gyro Bias Evolution</h3><ul><li><strong><em>2D<br>- </em></strong>bgz (yaw bias) drifts slowly upward over time, with NIS_bgs ≈ 0.57, indicating insufficient bias correction.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*QKrvmErDGhMFN6GMO1WqWw.png" /><figcaption>Gyro Bias for 2D Sensor Fusion</figcaption></figure><ul><li><strong><em>3D<br>- </em></strong>bgx, bgy, and bgz remain close to zero, with NIS_bgs nearly zero.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*oK2Vglbm2MCmtM7Ozq9kxw.png" /><figcaption>Gyro Bias for 3D Sensor Fusion</figcaption></figure><blockquote>Takeaway<br> The 3D system is far more effective at limiting long-term drift through bias decay and innovation-based bias updates.</blockquote><blockquote>Key takeaway:<br>While position and velocity estimation are robust, heading stability remains challenging.</blockquote><blockquote>Clamping acceleration innovation and applying a low-pass filter on the z-axis help stabilize the vertical state in 3D.</blockquote><blockquote>Clamping theta improves yaw stability. ZUPT improves x, y, z consistency to better match real-world motion.</blockquote><h3>🔮 Next Steps</h3><p>With core algorithms and key filters fully implemented, the next phase focuses on advanced validation and adaptive tuning:</p><ul><li>Extended endurance testing — run multi-hour datasets across varied motion profiles (continuous slopes, stop-and-go traffic) to confirm long-horizon stability of yaw and vertical states.</li><li>Extreme-case stress tests — evaluate robustness under temperature drift, vibration spikes, and high-dynamic maneuvers to ensure Q/R and covariance conditioning remain resilient.</li><li>Machine-learning–defined P / Q / R — explore data-driven or reinforcement-learning approaches to adapt process and measurement noise covariances online for different environments and sensor aging.</li></ul><h3>✅ Conclusion</h3><p>The 3D sensor fusion system on a Raspberry Pi platform offers more robust orientation control and better handling of elevation and tilt than a 2D filter, with only a moderate (~36%) increase in computational cost. Further refinement of quaternion updates, yaw correction, and gyro-bias management will extend stability for long-duration, real-world deployments. These findings will be continuously updated in future Medium articles and GitHub releases.</p><h3>📊 Detailed Fusion Results</h3><ul><li><strong><em>2D Results<br></em></strong>- RMSE: RMSE_x: 3.453388 | RMSE_y: 2.912071 | RMSE_vx: 0.070263 | RMSE_vy: 0.086176 | RMSE_ax: 0.348456 | RMSE_ay: 0.460629 | RMSE_theta: 0.730983</li><li>NIS Means: nis_pos: 1.627044 | nis_vel: 0.427116 | nis_accel: 1.425223 |<br> nis_quat: 0.021160 | nis_bgs: 0.571808</li><li>NIS Coverage within [5%, 95%] (chi2): nis_pos: 61.502% | nis_vel: 25.236% | nis_accel: 72.855% | nis_quat: 44.209% | nis_bgs: 29.279%</li><li><strong><em>3D Results<br>- </em></strong>RMSE: RMSE_x: 3.355175 | RMSE_y: 2.682700 | RMSE_z: 1.568534 | RMSE_vx: 0.107163 | RMSE_vy: 0.128937 | RMSE_ax: 0.449436 | RMSE_ay: 0.521319 | RMSE_az: 0.973547 | RMSE_theta: 0.478247</li><li>NIS Means: nis_pos_xy: 4.051816 | nis_pos_z: 0.110184 | nis_vel: 0.609853 | nis_accel: 2.679919 | nis_quat: 0.195306 | nis_bgs: 0.000000</li><li>NIS Coverage within [5%, 95%] (chi2): nis_pos_xy: 49.248% | nis_pos_z: 74.535% | nis_vel: 34.443% | nis_accel: 60.218% | nis_quat: 13.148% | nis_bgs: 0.000%</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1831fcb70ed4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sensor Fusion for Dummies (Mechanical Engineer Edition) II]]></title>
            <link>https://medium.com/@xvegcm/sensor-fusion-for-dummies-mechanical-engineer-edition-ii-bf9db564bd64?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9db564bd64</guid>
            <category><![CDATA[sensor-fusion]]></category>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 19:17:34 GMT</pubDate>
            <atom:updated>2025-09-04T19:17:34.605Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Python to C++: Building a Real-Time Sensor Fusion Library</h3><p>💡 <strong>Why I Moved from Python to C++</strong></p><p>When I first implemented sensor fusion in Python, the experience was smooth and convenient. Libraries like <strong>FilterPy</strong> made it easy to prototype algorithms and quickly visualize results.</p><p>But there was one problem: speed. Python was simply too slow for real-time applications. Once I started deploying algorithms on embedded hardware, latency became a critical issue.</p><p>That’s when I decided to rebuild my entire sensor fusion system in <strong>C++</strong>. Unlike Python, C++ doesn’t provide plug-and-play sensor fusion libraries, so I had to design my own Unscented Kalman Filter (UKF) from scratch.</p><p>This article shares that journey — comparing Python and C++, walking through the system I built, and highlighting key lessons for anyone developing a sensor fusion framework.</p><h3>⚖️ Python vs. C++ for Sensor Fusion</h3><p>Language Pros Cons <strong>C++</strong> High performance, low latency, fine-grained memory control Steeper learning curve, limited built-in visualization <strong>Python</strong> Easy to learn, excellent libraries (NumPy, SciPy, FilterPy, Matplotlib) Slower execution, not ideal for real-time systems<br><strong>⚖️ Python vs. C++ for Sensor Fusion</strong></p><pre>| Language | Pros                                             | Cons                                |<br>|----------|--------------------------------------------------|-------------------------------------|<br>| C++      | High performance, low latency, fine-grained      | Steeper learning curve, limited     |<br>|          | memory control                                   | built-in visualization              |<br>| Python   | Easy to learn, excellent libraries               | Slower execution, not ideal for     |<br>|          | (NumPy, SciPy, FilterPy, Matplotlib)             | real-time systems                   |</pre><p><strong>Tip:</strong> If real-time speed isn’t critical, stick with Python for prototyping. But if you need embedded, low-latency performance, C++ is worth the effort.</p><h3>🛠️ What I Built</h3><p>I designed a low-cost, real-time sensor fusion system on a Raspberry Pi to estimate outdoor vehicle motion.</p><p><strong>Hardware</strong></p><ul><li>Raspberry Pi 5 (main controller)</li><li>Adafruit 9-DOF IMU (LSM9DS1, I2C)</li><li>Adafruit GPS module (PA1616S, 10 Hz)</li></ul><p><strong>Sampling Rates</strong></p><ul><li>Accelerometer: 50 Hz</li><li>Gyroscope: 50 Hz</li><li>Magnetometer: 20 Hz</li><li>GPS: 10 Hz</li></ul><p><strong>Software</strong></p><ul><li>C++ with multithreaded data logging</li><li>Python for visualization and analysis</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3lxCap7Mqad__fSOXKLyMQ.jpeg" /><figcaption>Hardware Setup of Sensor Fusion Measurement</figcaption></figure><h3>🔑 Key Functions in C++ UKF Development</h3><p>Rebuilding the UKF from scratch taught me that certain functions were absolutely critical for achieving stability and real-time performance:</p><ul><li><strong>⏱ Timestamp Event-Triggered Sync</strong> — Instead of interpolating low-frequency data, the system lets the high-frequency IMU propagate continuously and only applies corrections when lower-rate measurements (GPS, magnetometer) arrive. This avoids artificial interpolation and keeps updates naturally aligned in real time.</li><li><strong>🔄 Sigma Point Generation &amp; Quaternion Handling</strong> — Uses tangent space for quaternions to avoid instability when averaging.</li><li><strong>⚖️ Adaptive Q/R Tuning</strong> — Dynamically adjusts noise covariances using innovations and NIS statistics.</li><li><strong>🛡 Heading-Only Fallback</strong> — When NIS spikes due to orientation anomalies, revert θ/yaw (quaternion heading component) to the last safe value while preserving position and velocity. This stabilizes heading without disrupting translational states.</li><li><strong>📐 Tilt Compensation &amp; Correction</strong> — Initializes with accelerometer (gravity) + magnetometer (heading); continuously corrects drift.</li><li><strong>🧹 Covariance Conditioning</strong> — Keeps the covariance matrix positive definite and numerically stable.</li><li><strong>🔽 Filtering</strong> — Low-pass and moving-average filters smooth noisy raw sensor data.</li><li><strong>🌱 Bias Decay / Regularization</strong> — Adds a small decay term to bias states (e.g., gyroscope bias) so they slowly relax toward zero instead of drifting indefinitely. This prevents long-term divergence while preserving short-term accuracy.</li><li><strong>📊 Decoupled Adaptive Noise Tuning</strong> — Adaptively tunes Q and R separately on each axis (x, y, z) to handle anisotropic sensor noise and direction-dependent dynamics.</li></ul><p>These details made the difference between a prototype that diverged in minutes and a reliable real-time fusion engine that survived outdoor driving tests.</p><h3>📊 UKF State Design</h3><p>My system uses a 13-dimensional state vector:</p><pre>[x, y, vx, vy, ax, ay, qw, qx, qy, qz, bgx, bgy, bgz]</pre><ul><li><strong>x, y</strong> — Position in world frame</li><li><strong>vx, vy</strong> — Velocity in world frame</li><li><strong>ax, ay</strong> — Acceleration in body frame</li><li><strong>[qw, qx, qy, qz]</strong> — Orientation quaternion</li><li><strong>bgx, bgy, bgz</strong> — Gyroscope bias</li></ul><p><strong>Initialization:</strong></p><ul><li>Accelerometer → gravity alignment</li><li>Magnetometer → heading estimation</li><li>Gyro bias states → prevent long-term drift</li></ul><p><strong>Things to watch out for:</strong></p><ul><li>Unit consistency (degrees vs. radians)</li><li>World ↔ body frame conversions</li><li>Filtering strategy (low-pass &gt; moving average for real data)</li><li>Heading-only fallback: limit rollback to θ/yaw (quaternion heading) instead of the full state to avoid jumps in x/y, v</li><li>Confirm your IMU data orientation (ENU vs. NED)</li></ul><h3>📏 Performance Evaluation</h3><p>I relied on two main metrics:</p><ul><li><strong>NIS (Normalized Innovation Squared):</strong> Measures consistency between estimates and measurements. Target: keep within 5%–95% chi-square bounds.</li><li><strong>RMSE (Root Mean Square Error):</strong> Evaluates accuracy against ground truth trajectories. Lower RMSE = better estimation.</li></ul><p>Together, these metrics balanced responsiveness vs. stability with adaptive tuning.</p><h3>📊 Results of the C++ Sensor Fusion</h3><p>During real-world driving tests, I logged and compared estimated states against raw measurements:</p><ul><li><strong>Trajectory:</strong> Overall trajectory tracking was consistent and visually close to GPS ground truth. Some time delay in velocity was observed due to ZUPT gating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0k1tP5T8hQQR9cMCOfq02Q.png" /><figcaption>Trajectory of Measurement and Prediction</figcaption></figure><ul><li><strong>Acceleration:</strong> Fusion successfully reduced raw accelerometer noise, producing smoother estimates.</li><li><strong>Heading:</strong> Orientation estimation worked reasonably well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSnBRrlji20iem0XZICEWg.png" /><figcaption>Result of Measurement and Prediction</figcaption></figure><p><strong>NIS Performance:</strong> Most states stayed below 95% bounds, though position NIS was degraded by ZUPT-related delays. Further optimization of quaternion and gyro bias is needed to bring more NIS values within the 5%–95% chi-square bounds, since quaternion and gyro currently rely too heavily on measurements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egDn08eA202xxGIpciIXXw.png" /><figcaption>NIS Variation of State Vector</figcaption></figure><h3>RMSE Results</h3><pre>| Metric    | Value   |<br>|-----------|---------|<br>| RMSE_x    | 58.414  |<br>| RMSE_y    | 43.266  |<br>| RMSE_vx   | 0.064   |<br>| RMSE_vy   | 0.137   |<br>| RMSE_ax   | 0.356   |<br>| RMSE_ay   | 0.467   |<br>| RMSE_theta| 0.029   |</pre><p><strong>Interpretation:</strong> RMSE_x and RMSE_y are relatively high, showing that position estimates still require optimization. However, velocity and acceleration RMSE values remain low, reflecting good short-term motion tracking accuracy.</p><h3>NIS Means</h3><pre>| Metric    | Value    |<br>|-----------|----------|<br>| nis_pos   | 215.136  |<br>| nis_vel   | 0.506    |<br>| nis_accel | 1.443    |<br>| nis_quat  | 0.000169 |<br>| nis_bgs   | 0.000359 |</pre><p><strong>Interpretation:</strong> The very high nis_pos suggests the filter is overconfident in position, while nis_vel and nis_accel remain reasonable. Quaternion and bias innovations are extremely small, which may indicate over-trusting measurements.</p><h3>NIS Coverage within [5%, 95%] (chi-square)</h3><pre>| Metric    | Coverage |<br>|-----------|----------|<br>| nis_pos   | 5.53%    |<br>| nis_vel   | 15.92%   |<br>| nis_accel | 70.74%   |<br>| nis_quat  | 0.52%    |<br>| nis_bgs   | 2.18%    |</pre><p><strong>Interpretation:</strong> Coverage shows that velocity and acceleration stay mostly within expected bounds, while position, quaternion, and bias coverage are poor. This highlights the need for refined gating and adaptive tuning.</p><p>These results show that while the system provides stable velocity and bias estimation, position NIS performance can be improved. Future work will refine gating and adaptive tuning.</p><h3>🚀 Lessons Learned</h3><ul><li><strong>Python = prototyping.</strong> Great for iteration, debugging, and visualization.</li><li><strong>C++ = deployment.</strong> Real-time speed and embedded control outweigh the lack of libraries.</li><li><strong>Bias handling is essential.</strong> Ignoring gyro bias guarantees divergence.</li><li><strong>NIS is your friend.</strong> It’s the quickest sanity check for filter consistency.</li><li><strong>Visualization matters.</strong> Export C++ results to Python/Matlab to debug effectively.</li></ul><h3>✅ Final Thoughts</h3><p>Transitioning from Python to C++ was not easy. After nearly 20 years away from C++, I was surprised that <strong>C++20 feels closer to Python</strong> than I expected, making the shift less intimidating.</p><p>If you’re a mechanical engineer diving into sensor fusion:</p><ul><li>Start in Python to validate concepts.</li><li>Move to C++ only when performance demands it.</li></ul><p>In the end, building your own sensor fusion library is challenging — but deeply rewarding. You don’t just run algorithms; you own every line of code that keeps your system stable in the real world.</p><h3>🔮 Next Steps</h3><p>The next milestone is <strong>sensor calibration</strong> (especially accelerometer and magnetometer). Proper calibration reduces systematic errors, ensures consistent scaling, and improves orientation estimation reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9db564bd64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Sensor Fusion for Dummies — A Practical Guide for Mechanical Engineers]]></title>
            <link>https://medium.com/@xvegcm/sensor-fusion-for-dummies-a-practical-guide-for-mechanical-engineers-5acf522e95b3?source=rss-9e574583cf14------2</link>
            <guid isPermaLink="false">https://medium.com/p/5acf522e95b3</guid>
            <dc:creator><![CDATA[Xvegcm]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 02:30:32 GMT</pubDate>
            <atom:updated>2025-07-15T04:56:13.545Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Sensor Fusion for Dummies — A Practical Guide for Mechanical Engineers</strong></p><blockquote><em>How I went from MEMS sensor design to real-time sensor fusion on a Raspberry Pi.</em></blockquote><p><strong>Why I Wrote This</strong></p><p>I’ve spent most of my career as a mechanical engineer — working on MEMS sensors, factory automation, and chip packaging. But over time, I noticed something frustrating:</p><blockquote>No matter how precise the sensors were, there was always drift. Always noise. Always disagreement.</blockquote><p>Accelerometers were noisy. Gyroscopes drifted. Magnetometers got lost in interference. And GPS? It cut out under trees.</p><p>After years of trying to fix each sensor individually, I realized: maybe we should let them help each other instead. That’s where sensor fusion comes in.</p><p>But for mechanical engineers like me, entering this world wasn’t easy. Most tutorials assume a software background. So this article is my attempt to make sensor fusion accessible — to explain what I wish I knew when I started.</p><p><strong>What Is Sensor Fusion?</strong></p><p>Sensor fusion combines the strengths of different sensors while minimizing their weaknesses.</p><blockquote>Each sensor is like a noisy, biased witness. But if you cross-check them and weigh their trust appropriately, you can reconstruct the truth.</blockquote><pre>Sensor         | Pros                                   | Cons<br>---------------|----------------------------------------|---------------------------------------------<br>Accelerometer  | High sampling rate; no GPS outage      | Noisy, biased over time<br>Gyroscope      | Tracks angular motion well             | Drift accumulates over time<br>Magnetometer   | Absolute heading; immune to drift      | Noisy, sensitive to magnetic interference<br>GPS            | Stable, low noise                      | Low rate; signal dropout in some areas</pre><p><strong>How Kalman Filtering Works</strong></p><p>Kalman filtering estimates the system state by predicting it based on a model and correcting it using measurements.</p><p><strong>🔄 UKF Timing Logic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*_qwrXcsAjimAwQXthh_wag.png" /><figcaption>Process Flow of Sensor Fusion</figcaption></figure><pre>Step        | Time        | From → To                                      | Description<br>------------|-------------|-----------------------------------------------|--------------------------------------------------<br>Prediction  | t → t+dt    | Estimated State (t) → Estimated State (t+dt)  | Predicts next state using system model (no sensor input)<br>Update      | t+dt        | Measured State (t+dt) → Estimated State (t+dt)| Corrects prediction using new sensor data</pre><p>In short: Prediction moves the state forward based on models; Update pulls the state back based on real measurements.</p><p>If the system follows a <strong>Gaussian distribution, </strong>Kalman filters are suitable. For <strong>arbitrary distributions, </strong>we use <strong>Particle Filters. </strong>And different Kalman filter variants suit different system types and computation budgets.</p><p><strong>🔍Filter Type Comparison</strong></p><pre>Filter Type         | Distribution Assumption | Representation          | Pros / Cons<br>--------------------|-------------------------|-------------------------|-------------------------------------------------<br>Kalman Filter (KF)  | Gaussian (Normalized)   | Mean + Covariance Matrix| ✅ Fast, simple / ❌ Assumes linearity &amp; Gaussian noise<br>Particle Filter (PF)| Arbitrary               | Weighted particles      | ✅ Flexible / ❌ Slow, can degrade over time</pre><p><strong>🧠 KF Variants</strong></p><pre>Filter Type | System Type            | Computation | Advantages / Disadvantages<br>------------|------------------------|-------------|------------------------------------------<br>KF          | Linear                 | Low         | ✅ Fast / ❌ Linear only<br>EKF         | Nonlinear (Jacobian)   | Medium      | ✅ Common / ❌ Needs Jacobian, can diverge<br>UKF         | Nonlinear (No Jacobian)| High        | ✅ Accurate / ❌ Computationally heavier</pre><p>Once the basic filter model is in place, we tune its noise models. In sensor fusion, the key challenge is balancing the <strong>P, Q, and R matrices:</strong></p><p><strong>📊 The Three Core Noise Matrices in KF</strong></p><pre>Matrix | Represents                  | Controls                  | Root Cause of Noise<br>--------|-----------------------------|---------------------------|---------------------------------------------<br>P      | State covariance            | Confidence in current state| Initial uncertainty, observability gaps<br>Q      | Process noise covariance    | Prediction flexibility     | Model simplification, wind, actuator errors<br>R      | Measurement noise covariance| Trust in sensor data       | Sensor noise, interference, quantization</pre><p><strong>What I Built</strong></p><p>I built a low-cost, real-time sensor fusion system that runs on a Raspberry Pi to estimate outdoor vehicle motion.</p><p><strong><em>🧠 Hardware:</em></strong></p><ul><li>Raspberry Pi 5 as controller</li><li>Adafruit 9-DOF IMU (LSM9DS1) via I2C</li><li>Adafruit GPS module (PA1616S, 10Hz<em>)</em></li></ul><p><strong><em>📈 Sampling Rates:</em></strong></p><ul><li>Accelerometer: 50 Hz</li><li>Gyroscope: 50 Hz</li><li>Magnetometer: 20 Hz</li><li>GPS: 10 Hz</li></ul><blockquote><em>Note: IMU supports 100Hz, but I2C bus limited it to ~50Hz. SPI could reach full rate.</em></blockquote><p><strong><em>🧰 Software:</em></strong></p><ul><li>Python with multi-threaded data logging</li><li>Timestamp interpolation and sync</li><li>UKF using `filterpy`</li><li>Adaptive Q/R tuning via innovation and NIS</li></ul><p><strong>UKF State Design</strong></p><p>We used a 10D state vector:</p><p>python: [x, y, vx, vy, ax, ay, qw, qx, qy, qz]</p><ul><li>x, y: Position (world frame)</li><li>vx, vy: Velocity (world frame)</li><li>ax, ay: Acceleration (body frame)</li><li>qw, qx, qy, qz: Orientation (quaternion)</li></ul><p>We initialize orientation using:</p><ul><li>Tilt-compensated accelerometer (gravity)</li><li>Magnetometer for heading</li></ul><blockquote>Note: Mechanical engineers often think in yaw, roll, and pitch. But in software, quaternions are preferred — they require only 4 elements and avoid singularities.</blockquote><p>We tune Q/R adaptively using NIS (Normalized Innovation Squared) and the residual (innovation) between predicted and measured states.</p><p><strong>Performance Evaluation</strong></p><p><strong><em>📏 Metrics:</em></strong></p><ul><li><strong>RMSE: </strong>Root Mean Square Error between estimate vs measurement</li><li><strong>NIS: </strong>Squared difference between measurement and estimate, normalized by uncertainty</li><li><strong>Mean NIS : </strong>Ideal value ≈ dimension of the observed state</li><li><strong>Chi-square bounds (5%–95%): </strong>% of NIS values within confidence bounds</li></ul><blockquote>Lower NIS and RMSE → Better tuning and consistency</blockquote><p><strong>Results</strong></p><p><strong><em>Trajectory Plot:</em></strong></p><p>Overlay of GPS vs UKF-estimated trajectory. While globally aligned, zoom-in reveals GPS sparsity vs. UKF smoothness — due to IMU-enhanced update frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlUASTww2Pac4b2dQ4YDBA.png" /><figcaption>Trajectory Plot of Sensor Fusion Model</figcaption></figure><p><strong><em>Measurement State Plot:</em></strong></p><p>Full and zoomed plots show UKF x/y/vx/vy closely track GPS, while ax/ay and theta (yaw) show more deviation, especially during stationary periods. Further tuning is needed for those states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHz4U5xy7dGephQCJ1xO4A.png" /><figcaption>Measurement State Plot</figcaption></figure><p><strong><em>NIS Plot:</em></strong></p><p>Plots of innovation and mean NIS reveal that x/y/ax/ay/theta are well tuned. However, vx/vy underperform — likely because GPS-derived velocities are indirect, thus limiting innovation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxOfwJMfFWp1ZEOc9a0SPQ.png" /><figcaption>NIS Plot</figcaption></figure><p><strong>What I Learned (And What’s Next)</strong></p><ul><li>Adaptive Q improves velocity tracking, but can destabilize yaw</li><li>Fixed Q for quaternion stabilizes heading</li><li>Tracking ax/ay residuals over time helps spot anomalies</li></ul><p><strong>📌 Next Steps:</strong></p><ul><li>Add bias estimation: bx , by</li><li>Use magnetometer only during initialization</li><li>Expand from 2D → 3D (add barometric altitude)</li><li>Publish ROS2 topics and integrate SLAM</li></ul><p><strong>Final Thought</strong></p><blockquote>“One of the most frustrating things in sensor fusion is when your filter thinks the car is accelerating left… but your accelerometer says it’s going right.”</blockquote><p>So I plotted the difference between estimated and measured acceleration over time:</p><ul><li>Occasional spikes? Acceptable.</li><li>Constant bias? Problem.</li><li>General alignment? Good.</li></ul><p>✅ The results were directionally stable and within tolerable error bounds.</p><p>If you’re a mechanical engineer stepping into robotics or autonomy, I hope this gives you a practical, confidence-building entry point into sensor fusion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5acf522e95b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>