Gains:
- Ability to construct fusion logic (integrator/Kalman filter) that combines IMU, encoder and distance sensor data with AI
- Ability to configure and interpret MQTT-based IoT data streams and telemetry with the help of AI
- Ability to detect and correct sensor noise, calibration and time synchronization issues in AI output
No sensor is perfect. The gyroscope is very accurate in the short term, but drifts over time. The accelerometer is stable in the long run but gets noise from vibration. The encoder measures the position precisely, but it is wrong when there is a slip. GPS works in a wide area but is low frequency and noisy. The mechatronics engineer has to produce a single, reliable truth from these imperfect sensors; This is sensor fusion. Moreover, in modern systems, this data does not only remain local, but flows to cloud and control centers via IoT networks. Artificial intelligence is a powerful aid in both setting up fusion algorithms and configuring and interpreting IoT telemetry. In this unit, we cover the complementary filter, Kalman filter logic and how to set up MQTT-based IoT flow with AI and catch noise and synchronization traps.
Why Sensor Fusion?
Every sensor has a "good frequency zone". The purpose of fusion is to use each sensor in the area where it is strong and support it with the other in the area where it is weak.
sensor
strong point
weakness
gyroscope
Short-term angular velocity, fast response
Drift over time
accelerometer
Long-term slope reference (gravity)
Vibration/noisy on movement
encoder
High resolution location
Slip/backlash error
GPS
absolute position
Low frequency, noise, no indoor
Relying on a single sensor introduces the weakness of that sensor into the system. Fusion, for example, combines the fast but drifting angle of the gyroscope with the slow but steady reference of the accelerometer, yielding an angle that is both fast and drift-free.
Complementary Filter
The simplest and most common fusion is the complementary filter. The idea is intuitive: trust the gyroscope at high frequency (fast change), the accelerometer at low frequency (slow, stable). One line summary:
# Complementary filter: pain estimation (pitch) # alpha ~ 0.98 : more to the gyroscope, less to the accelerometer (degrees/sec) acceleration_ange : angle calculated from accelerometer (degrees) dt : sampling period (sec) """ gyro_pac = previous + gyro_speed * dt # integrate gyroscope return alpha * gyro_pace + (1 - alpha) * acceleration_angle# Verification logic: pure gyroscope (drifts) if alpha=1, # if alpha=0 pure accelerometer (noisy). The intermediate value balances the two.
The coefficient alpha here determines the balance: if it is close to 1, it relies on the gyroscope (risk of drift increases), if it is close to 0, it relies on the accelerometer (noise increases). The typical value is 0.95–0.98. AI may suggest this value, but the correct alpha depends on your system's sample rate and noise character; is set experimentally.
Tip: When printing an integral filter to AI, be sure to ask how dt is measured. Most errors come from assuming dt is constant but in reality the cycle time varies. Measure dt real with millis()/timestamp, don't write constants.
Kalman Filter Logic
The complementary filter is simple but does not model noise statistics. The Kalman filter produces an optimal (under certain assumptions) estimate by probabilistically modeling sensor noise and process uncertainty. It works in two steps:
- Predict: Predict the next situation and its uncertainty with the system model.
- Update: Weigh the new measurement against the measurement reliability (Kalman gain) and correct the estimate.
Kalman gain K automatically answers the question "should I trust the measurement or the model more" at every step. If the measurement noise is large, K becomes smaller (confidence in the model), if the process uncertainty is large, K becomes larger (confidence in the measurement). AI easily writes a one-dimensional Kalman filter; but it is your job to choose the noise covariances (`Q`, `R`) correctly and they come from the actual noise of the system.
Attention: Q (process noise) and R (measurement noise) values given by AI are sample/placeholder. If you do not determine these from the actual measurement noise of the system (e.g. the variance measured when the sensor is stationary), the filter will be either too slow or too noisy. Do not trust the covariances given by the AI as the "true value".
IoT Data Stream: MQTT and Telemetry
The clean data you produce with fusion is usually transported to the center via an IoT network. The most common protocol in the industry is MQTT: lightweight, publish-subscribe model, suitable for low bandwidth. AI quickly establishes MQTT publisher/subscriber code and JSON telemetry schema.
import json, timeimport paho.mqtt.client as mqttclient = mqtt.Client()client.connect("broker.local", 1883, keepalive=60)def telemetry_broadcast(temperature, temperature, vibration_rms): message = { "ts": time.time(), # timestamp -- condition for synchronization "pain_deg": round(pain, 2), "temperature_c": round(temperature, 1), "vibration_rms": round(temperature_rms, 3), "unit": {"pain": "deg", "temperature": "C", "vibration": "mm/s"} } client.publish("machine/line1/sensor", json.dumps(message), qos=1)# qos=1: delivered at least once. Using qos=0 (may be lost) on critical data.
Two engineering decisions are important here: (1) timestamping (ts) each message—different sensors are sampled at different times, synchronization is only possible with timestamping; (2) QoS level—critical data uses at least qos=1 (delivered at least once), qos=0 allows message loss.
Noise, Calibration and Synchronization
No matter how good the fusion is, three problems with the input distort the result:
- Noise: If raw sensor data goes into fusion without being filtered, the fusion output will also be noisy. Pre-filtering (median, low pass) may be required.
- Calibration: Offset and scale errors (e.g. the zero point of the accelerometer is shifted) systematically mislead the fusion. Sensors must be calibrated before use.
- Time synchronization: Timestamping and interpolation are required to align sensors sampled at different rates (e.g. 10 Hz GPS with 1 kHz IMU).
AI can add these steps to the code, but whether each is required and its parameters are specific to your system. In the AI output "where is the calibration?" and “are the timestamps aligned?” Be sure to ask questions.
Weak Prompt / Strong Prompt
WEAK:"Calculate angle from IMU data."(Which filter? Is drift handled? How dt? Unclear.)STRONG:"Combine accelerometer and gyroscope data from MPU6050 with integral filter and estimate pitch angle. Calculate dt from real timestamp, do not assume constant. Set alpha as parameter (default 0.98). Calculate accelerometer angle with tane2. Filter as a write as class, keep previous angle, add optional median prefilter for noise."
Mini Case
Robotics engineer Selin wants a complementary filter from AI for angle estimation on a two-wheeled balancing robot. The AI gives a clean code, but the robot slowly leans to one side. Selin checks dt: the code assumes dt is constant 0.01 s, whereas the cycle time varies due to Bluetooth telemetry. When dt is calculated from the real timestamp, the drift decreases but does not disappear completely. Then he looks at the calibration of the accelerometer; Even when the sensor is stationary there is a 2° offset. When I remove the calibration offset, the robot stands upright. Finally, it notices that it uses qos=0 when broadcasting telemetry via MQTT and increases it to qos=1 for critical angle data. AI delivered fusion skeleton in minutes; but the engineer's verification caught three system-specific issues: variable dt, calibration offset, and QoS.
Common Mistakes
- Assuming dt is constant, whereas the cycle time varies (fusion drifts).
- Fusing sensors without calibrating them (systematic offset).
- Trying to align sensors of different speeds without timestamping.
- Leaving with the sample value of the AI without measuring the Kalman Q/R covariances from the real noise.
- Allowing message loss by using qos=0 on critical IoT data.
- Giving raw noisy data to fusion without pre-filtering.
In summary
- Fusion uses each sensor in the frequency region where it is strong and compensates for its weakness.
- The complement filter is simple; Establishes gyroscope-accelerometer balance with alpha.
- Kalman filter models noise probabilistically; Q/R comes from the real system.
- In MQTT telemetry, timestamping and appropriate QoS are critical engineering decisions.
- Noise, calibration and time synchronization determine the quality of fusion.
- dt is measured from real time; calibration and QoS are verified without leaving it to the AI.
Application task
For an IMU (real or simulated gyro + accelerometer data) have the AI generate the integral filter and make sure the dt is calculated from the real timestamp. Then: (1) try alpha for 0.90, 0.98 and 1.0 and observe drift and noise balance, (2) add an intentional fixed offset (calibration error) to the sensor and see how the fusion output drifts, (3) convert the data to MQTT JSON schema and add timestamp and unit fields. Note which alpha value gives the most balanced result for your data and how much the calibration offset distorts the output.