Applied level: reading an IMU, fusing data and communicating on time

Choose I2C, SPI or UART for Arduino/ESP32 before reading an IMU, check units and timing, understand sensor fusion, and design messages that can detect stale and dropped data.

Last updated:

A sensor module on an orientation stand beside two boards and a data graph, for studying an IMU and communication
Concept image generated with AI; it is not a screenshot or a device model confirmed to be supported

Read the UART frame guide to practise decoding bytes into values, the sampling-rate guide before choosing the sensor's dt, and the IMU calibration guide before fusing data

Continue with the Complementary Filter chapter with worked calculations to separate prediction from the fused angle

Objectives and equipment

This chapter separates 'the data can be read' from 'the data can be used' by checking units, directions, time intervals and the effect of stale data. You can start the practice sets on a computer with Python 3.11 or later without a board. When you move to real equipment, use the board from the foundation chapter, an IMU module per its manual, and connecting wires. A second ESP32 board is optional for the communication exercises

Start from basic I/O and timing . Check whether the module supports I2C or SPI and whether its voltage level matches the board. Some modules have a level shifter and some do not, so use the datasheet of the actual module rather than looking only at the sensor name.

Before reading an IMU, see Choosing I2C, SPI or UART to separate the signal wiring from the meaning of the data

Choose I2C, SPI or UART to match the job

Objective: choose a communication channel the module supports, and write a configuration list that can be traced back Prerequisites: know GPIO, logic voltage and ground from the foundation chapter Getting started: read the board and module manuals and fill in the planning sheet on a PC or paper; no equipment needs to be connected yet

Concept image of a bench for preparing a microcontroller board, a sensor module, a signal-analysis tool and unconnected wires, beside a drone frame with the propellers removed

A photorealistic image created with AI to explain the preparation context; it is not a certified pinout or circuit, nor a measurement of real equipment

Compare the roles before choosing the wires

Channel Signals in the described form What jobs to consider it for
I2C SDA data and SCL clock; devices are selected by address Several sensors on a nearby bus, when the addresses and electrical conditions can be shared
SPI SCK clock, MOSI sent from the controller, MISO received back, and CS selecting the device Modules that support SPI, where the transaction/clock must be set per the datasheet
UART TX sends to the other side's RX, and RX receives from TX; this asynchronous form has no shared clock line Reading messages from a module or sending a log, with both sides using matching baud and frame format

The table counts only the generally described signals; power and ground must also be considered. It is not the total number of wires or the requirement of every module. Choose from the interfaces that actually exist, the remaining pins, the timing work and the error-checking method, and do not decide from the bus name alone

I2C - check the address and pull-ups

SDA/SCL need pull-ups to a voltage level the devices support. Check whether the breakout already has resistors and whether any addresses collide. Default pins may differ between boards, so GPIO numbers from the example are not used on every ESP32. Set the pins/clock per the manual and check the API's return values per Espressif I2C

If you use a scanner when you have the device, an address acknowledgement is only a starting point. Read the device-identification register per the datasheet, if there is one, and then check the units/axes/data range. Seeing an address does not certify that the IMU gives correct data or that the wiring works in all conditions

SPI - check the mode and the device's CS

State the SCK/MOSI/MISO/CS pins, bit order, the maximum clock the module supports and the SPI mode (clock polarity/phase) completely. When sharing a bus, select devices with CS according to each one's conditions, and check whether a library/other task uses the same peripheral or pins. The example Espressif SPI shows setting SPISettings, opening a transaction, selecting CS, transferring and ending the transaction

The names MOSI/MISO may be written COPI/CIPO per the Arduino documentation on SPI signal names . Compare the direction with the controller and not the wire colour. Do not assume the module will accept the frequency or mode from the example

UART - separate the baud from the received message

For the generally described logic-level UART, connect TX to RX with a common ground reference, and check the voltage levels and the baud/data bits/parity/stop bits on both sides per Espressif Serial The name Serial may be routed to a UART/USB differently depending on the board and options; read the manual of the actual model. Do not connect logic pins directly to RS-232/RS-485 without checking the interface circuit

A paper calculation example: assume UART at 115,200 baud, 8N1, transmitting continuously with no gaps and no flow control. One byte uses start 1 + data 8 + stop 1 = 10 bits per Microchip: asynchronous frame so there is a data ceiling of 11,520 bytes/s; an encoded 32-byte message takes about 2.78 ms (32 × 10 / 115200 seconds) on the wire. If 100 messages/s are sent, about 27.8% is used on the wire. This value is a calculation under assumptions; it excludes queue time, message-handling work, gaps or USB latency, and is not a benchmark result

One Thai character may use several bytes, so count the size after encoding and include the protocol's header/newline. Writing to a buffer is not the same as the destination having received it. See ESP-IDF: UART transmission and then continue with the sources and scope of the log

Signal diagram: I2C uses SDA and SCL, SPI uses SCK, MOSI, MISO and CS, and UART connects TX to RX, with the voltage, ground and device settings to be checked

A diagram of the signal roles in the general forms; it does not specify GPIO pins or power wires. Use it together with the datasheet and the pinout of the actual board/module. Open the full-size signal diagram

Planning steps before connecting

  1. State the job, such as reading an IMU or receiving messages, choose the board/module model and the manual URL, and check the interfaces actually supported
  2. Fill in the pin names, logic voltage/power, ground and the bus settings in the planning sheet. Do not fill in electrical values that the datasheet does not specify
  3. Define what will be read to confirm the communication, such as the device-identification register, or a message with length/units, and the timeout/error to record. A reply value alone does not confirm the meaning of the data
  4. Estimate the number of bytes and the time used. State the timestamp/clock point before linking to control work. Review the STM32 timing budget when several tasks share the time
  5. When you have equipment and a manual matching the model, check the circuit with the power off and try one module at a time per the real-board guide . Keep the settings and raw files; do not add measured results to the worksheet from guesses

Troubleshooting tips: if I2C does not respond, check address/pull-up/voltage/pins; if SPI gives constant values, check CS/mode/direction/number of bytes; if UART gives garbled text, check baud/frame/ground and data format. Change one condition at a time and keep the evidence. These symptoms are inspection guidance, not confirmation of the cause in equipment that has not been measured

Download the communication-channel selection guide, the blank interface planning sheet, the UART calculation exercises, the calculation answers and limitations, the sources of the interface topics and the manifest of the interface guide This worksheet is separate from the 10 guided practice sets and the earlier score, and has no effect on boards or new learner results

Read a UART frame from bytes to values

Objective: separate the span where bytes can be read from the message boundary, and check byte order and errors before using the values Prerequisites: able to read hexadecimal, the byte unit and the UART settings correctly Getting started: use a PC or paper with hypothetical data; no board connection is needed yet

Concept image of a study desk for reading UART frames, with a microcontroller board, a USB adapter and unconnected wires, a notebook dividing the message fields, and a drone frame with the propellers removed

A photorealistic image created with AI to explain the context; it is not a pinout, a circuit connection or a send/receive result from real equipment

How many bytes can be read does not tell whether the message is complete

UART sends a sequence of bytes, while the job's protocol defines the message boundaries and meaning itself. One read may yield part of a frame or several frames together. See Espressif Serial API: available() counts bytes waiting to be read; read() returns a byte or -1; readBytes() may return fewer than requested on timeout, so check the number actually read before accessing the buffer and do not convert -1 into data

Do not treat the UART start/stop bits as the start and end of a multi-byte message, and do not use a quiet period as a boundary unless the protocol specifies it. If a value read is not yet complete, keep the state waiting within the buffer size and the specified time; do not wait indefinitely in control work

A self-declared 6-byte frame exercise

This frame was created for paper practice; it is not MAVLink or a drone control command . Every token below is one hexadecimal byte, not ASCII text actually sent

Position, starting from 0 Role
0 start marker A5
1 a one-byte sequence
2 and 3 a 16-bit little-endian value: the low byte comes before the high byte
4 XOR over only the bytes at positions 1, 2 and 3
5 end marker 5A at this position

The marker may appear in the payload, so read according to the 6-byte length and check that the end is at position 5; do not cut at the first 5A found. This exercise does not define physical units, a timestamp or a boot session, so it still cannot be used to decide freshness or to control flight

The first frame A5 07 34 12 21 5A: the XOR is 07 XOR 34 XOR 12 = 21 and the unsigned value is 0x1234 = 4,660 . The order of the bytes of a field differs from the order of bits a peripheral sends within one byte; see the protocol before decoding

The second frame A5 08 9C FF 6B 5A: the XOR is 6B; the unsigned value is 0xFF9C = 65,436 . If the schema declares signed 16-bit two's complement , convert a value with the high bit set to 65,436 − 65,536 = −100 . Do not infer signedness or units from a sensor's name, and do not rely on casting a pointer to a struct in place of reading the schema

Divide the reads without splitting a message wrongly

Assume nothing is lost, no bytes are inserted, and reading starts exactly at the start of the first frame. The receiver gets three spans in order:

Read round Bytes received
1 A5 07 34
2 12 21 5A A5
3 08 9C FF 6B 5A

After round 1 there is no complete frame yet; after round 2 the first frame is complete and A5 remains for the start of the second frame; after round 3 the second frame is complete. So there are 2 frames from 3 read rounds , not 3 messages. For unsigned, the two values are 4,660 and 65,436; the latter may be called -100 only once the schema states signed

Diagram dividing three read spans into two six-byte UART frames, then separating the boundary check, XOR, schema and data freshness

The diagram uses hypothetical data and shows byte boundaries; it is not a waveform or a result from a serial monitor. Open the full-size frame diagram

Passing XOR does not certify the data

Frame A5 09 34 12 00 5A fails the XOR because the computed value is 2F which differs from 00 but swapping the payload to A5 07 12 34 21 5A still passes the original XOR, even though the decoded value is 0x3412 = 13,330 instead of 4,660. This example shows the limitation of XOR; no error rate was measured

Real work uses framing and an error checker according to the protocol with a library matching the model, such as MAVLink serialization which has its own packet format and checksum. Do not substitute this practice frame for it. Passing an error check does not confirm the sender, the right to command, the units or the freshness of the data

Initial recommendations: check that the schemas match, budget the buffer and timeout, limit data before decoding, and separate the reasons for rejection, such as incomplete, wrong marker, differing checksum or schema mismatch. If you must find the start of a frame again when bytes are corrupted, resynchronisation must be defined and tested additionally; the three-span exercise above does not test this case

Practice steps and recording conclusions

  1. Read the UART frame set guide and copy the blank frame planning sheet , defining the length, byte order, signedness and units. If not yet known, record unknown
  2. Do the bytes and frames exercise , drawing the leftover buffer after each round, then check the answers with their scope . The exercises do not add points to the earlier assessment
  3. Compute the wire time under the assumption of continuous 8N1 UART at 115,200 baud: 6 bytes x 10 bits = 60 bits, taking about 0.521 ms per frame, excluding queue, timeout, gaps, USB or decode time
  4. Continue with the criteria for screening decoded messages to consider sequence, data age and boot session, which this frame exercise does not yet have, and then read the sources and scope of the log before collecting real data
  5. When you will develop a real parser, prepare cases for missing data, multiple frames, a marker in the payload, loss of alignment and a full buffer, and check through a protocol-specific test set before connecting equipment, per the real-board preparation guide . This round has no executable parser or real send/receive results

Sources of the practice set: schema and sample data · the frame file hash list

What each type of sensor tells you

Sensor What it measures What to watch out for
Gyroscope Rotation rate about an axis, such as deg/s or rad/s Bias makes integrated angles drift; vibration and noise also have an effect
Accelerometer Specific force along each axis, in g or m/s² Motion affects the readings; values at rest must be interpreted according to the coordinate frame
Barometer Pressure for estimating altitude Requires reference conditions; wind and the environment have an effect
ToF / rangefinder Distance to the surface seen by the sensor Mounting direction, target surface and measurement range have an effect

The gyro and accelerometer are often combined as an IMU. Define the X/Y/Z axes and positive directions before using the data, and do not assume every module uses the same axes or units. Real systems separate the sensor driver and data correction from the data consumers; see ArduPilot sensor drivers

Separate the sampling rate from the sensor read rate

Objective: explain aliasing and plan the data rate and filter points before using an IMU Prerequisites: know Hz and ms and be able to read a numeric table Getting started: use a PC or paper with mathematical signals; no board or flight-parameter tuning is needed

Concept image of a sampling-rate study desk with a microcontroller board, an IMU module, a USB cable and unconnected signal wires, a timing-table notebook and a drone frame with the propellers removed

A photorealistic image created with AI for learning context; it is not a certified circuit or a measurement of a real sensor

Four rates that must be stated separately

Rate What to check
Internal sampling rate The point where the sensor or ADC captures the signal, and the filter before that point
ODR, or output data rate The frequency at which the device provides a new sample, according to mode and datasheet
The rate the MCU reads Reading the latest register, or pulling several samples from a FIFO
The rate the job uses it The cadence of the filter/controller and the age of the sample used

A paper assumption: a sensor gives new values 100 times/s but the MCU reads the latest-value register 1,000 times/s with no FIFO, and the register changes only when there is a new sample. The repeated reads therefore do not create 1,000 new samples/s. Check data-ready, a sample counter or a timestamp as the device supports. One FIFO pull may yield several samples, so check overflow and the time of each sample too

A set rate of 100 Hz has a period of 10 ms when uniform, but the actual read intervals may drift from pending work. Do not set dt from the loop cycle without checking the timestamp point and duplicate data. Separate the time the sample was produced, the time it was read and the time it was used. If they are on different clocks, state how the times are compared

A 20 Hz versus 80 Hz exercise that gives identical samples

Declare the signal x(t) = cos(2π f t) with amplitude 1 with no physical unit , starting phase zero and no random noise, ideally sampled uniformly at fs = 100 samples/s, t[n] = n / 100 s . The following examples are computed values, not gyro data

Time (ms) f = 20 Hz f = 80 Hz
0 1.0000 1.0000
10 0.3090 0.3090
20 −0.8090 −0.8090
30 −0.8090 −0.8090
40 0.3090 0.3090
50 1.0000 1.0000

The two signals coincide at the sample points because 80 = 100 − 20 and for integer n cos(2πn − θ) = cos(θ) This example therefore cannot separate 80 Hz from 20 Hz from the samples on this grid alone. It is aliasing foundational reading Analog Devices: sampling and aliasing

A computed graph of 20 Hz and 80 Hz cosines with coinciding sample points at 100 samples per second, and a diagram of the filtering position before the rate is reduced; it is not a sensor result

The lines and points were generated with Matplotlib from the declared equations. The amplitude axis has no unit and it is not a measured waveform. The lower part is a general conceptual sequence, not the pipeline of every IMU. Open the full-size sampling graph and diagram

Using Nyquist with assumptions and margin

For uniform sampling of a band-limited baseband signal, let the highest frequency be below fs/2 and allow margin for the filter's transition band according to the job. Do not choose fs from the frequency you want to see alone. If there is vibration or noise above that, it may alias into the band of interest

At fs = 100 samples/s the Nyquist limit is 50 Hz At the boundary, mind the phase: if the signal is sin(2π × 50 × t) and sampling starts at t = 0, you get sin(πn) = 0 at every point even though the signal between points is not zero. So 'two samples per period' alone is not regarded as guaranteeing recovery of every signal

This model does not include jitter, quantisation, clipping or the response of real devices. Read Analog Devices: anti-aliasing filter which describes filtering before the ADC and the sampling-rate margin in real work. A real filter has a transition band; it does not cut off instantly at a single frequency

Filter before the point where the rate is reduced, and check the latency

Separate two points: before the ADC the signal must be limited according to the structure of the analog front-end; once there is high-rate digital data and the rate will be reduced, filter appropriately for the new rate before choosing to keep some samples, such as 1,000 -> 100 samples/s by keeping every 10th, not cutting the data first and then trying to remove the alias afterward. See the conceptual order in ADI AN-282: sampled data systems

Averaging or low-pass filtering after aliasing has occurred does not tell which frequency the original signal was, and additional filtering affects latency. The position of the filter/ODR/FIFO of the actual chip and driver must be read. An example system PX4 filter pipeline v1.16 separates the filtering stages and their effect on latency. This chapter is for reading the structure; it proposes no tuning values for flight

Practice steps and initial recommendations

  1. Read the sampling guide and make a copy of the blank sampling-rate planning sheet , stating the sample/ODR/read/use rates, the clock and the filter points. Use unknown when there is no data yet
  2. Do the sampling-rate and aliasing exercises before opening the answers with their assumptions . Check the Hz versus ms and the phase used. The exercises do not add points to the earlier assessment
  3. Plan to check for new samples, duplicate data, FIFO overflow and the real timestamp interval before using a constant dt. If reads are frequent but the values are the same, do not immediately conclude the sensor is stuck, because a constant signal and repeated reads also give equal values
  4. Read the STM32 timing budget and measurement points to include queue and filter time in the plan, then return to Sensor Fusion to choose dt according to the meaning of the data
  5. When you have equipment, use the real-board preparation guide and keep the source/config/clock/log and the limitations. This round has no measurement of bandwidth or filter tuning on real equipment. Raising the rate does not confirm accuracy or steady flight

Sources of the practice set: the sampling-rate equations and assumptions · the sampling set hash list

Separate bias, sensitivity and noise before fusing an IMU

Objective: explain what calibration can and cannot yet correct before using values from an IMU Prerequisites: read the units deg/s and g and be able to find an average Getting started: use a PC or paper with hypothetical numbers; no board is needed. This chapter does not change calibration values or flight parameters

Concept image of a calibration study desk with an IMU module on a cube stand, a microcontroller board, an unconnected USB cable, a notebook of sample points and a drone frame with the propellers removed

A photorealistic image created with AI for learning context; the attitude of the equipment in the image is not a certified calibration pose or evidence of a measurement result

Classify the error before choosing a fix

What to separate Meaning in the model What to check next
Bias / offset A shift from the value that should be obtained under reference conditions The reference, units, axes, temperature, and whether the data has already been compensated
Gain / sensitivity The rate of change of output per input Separate the conversion of LSB to physical units from the gain error after conversion
Noise / variation Values scattered around the mean The time interval, bandwidth and duplicate data; four points are not enough to state the chip's noise statistics
Axis direction / clipping A wrong sign or axis / a value beyond the measuring range Check the mapping and range; subtracting an offset does not fix these two cases

Use the single-axis model y = s × x + b + e where x is the reference value and y is the reported value in the same unit, s is a unitless gain, b is an offset in the units of y, and e is the variation. The model excludes cross-axis, nonlinearity or temperature. Read the offset and sensitivity principles in Analog Devices AN-1057 in the section Calibration for Offset and Sensitivity Mismatch Error

A stationary gyro: subtracting the mean does not remove the variation

Hypothetical exercise: the true rate of rotation is zero, in deg/s, and there are four new samples [0.4, 0.5, 0.6, 0.5] The mean is 0.5 deg/s When this is subtracted, [-0.1, 0.0, 0.1, 0.0] the new mean is zero, but the values between the points still differ. This short example does not prove a real bias or the noise pattern of a device

If a residual bias of 0.1 deg/s remains constant over 10 s it accumulates a wrong angle of 1° from error = bias × time under the ideal model; this is not a certification of accuracy after calibration. Taking a span in which it is still rotating and subtracting the mean would also subtract the real rotation, and bias may change with operating conditions

In an example of a real procedure PX4 gyro calibration v1.16 the vehicle must be kept still per QGroundControl; if it moves, the procedure restarts. Do not take the number 0.5 from the exercise and set it on a real board. PX4 thermal compensation v1.16 describes compensation for bias that changes with temperature. This chapter does not do thermal calibration

A stationary accelerometer does not mean all axes are zero

Keep the body FRD definition of the earlier practice set: X forward, Y right, Z down. When placed level and still in the ideal model, the specific force is [0, 0, −1] g or Z = −9.80665 m/s² according to the constants of the original exercise, so the whole Z value is not subtracted to zero, because that would subtract the gravity information used to estimate attitude. The direction and sign of a real module must be checked against the datasheet/driver and the orientation mapping

A two-point, one-axis example: set the reference x to +1 and -1 g along the declared axis, and assume the reported values y are +1.10 and -0.94 g, using a linear model with no noise:

  • b = (y+ + y−) / 2 = 0.08 g
  • s = (y+ − y−) / (2 g) = 1.02 unitless
  • x_est = (y − b) / s in units of g. Subtraction alone does not fix a sensitivity error
Exercise point x reference (g) y hypothetical (g) subtract b only (g) subtract b then divide by s (g)
used to find b and s +1.00 +1.10 +1.02 +1.00
used to find b and s −1.00 −0.94 −1.02 −1.00
equation check, not used in the fit 0.00 +0.08 0.00 0.00
equation check, not used in the fit +0.50 +0.59 +0.51 +0.50

The last two rows are generated from the same equation, so they check only the arithmetic and are not validation from independent measurement. The model does not cover cross-axis or temperature range and does not replace the three-axis calibration procedure of a flight stack. See PX4 accelerometer calibration v1.16 which sets the orientation and then holds the vehicle still in several poses as instructed

A graph of hypothetical gyro data before and after subtracting the mean, with an accelerometer model line comparing offset removal and gain correction, together with the order for checking compensation

The Matplotlib graph was generated from the numbers and equations in the exercise. The equation check points are not independent experimental results. Open the full-size calibration graph and diagram

Practice steps and initial recommendations

  1. Read the paper calibration guide and make a copy of the blank calibration planning sheet , stating the units, axes, reference and the compensation status of the data. If not yet known, write unknown
  2. Do the bias and gain exercises before reading the answers with their scope , separating the points used for the fit from the equation-check points. There are no new points in the earlier assessment
  3. Check in the driver/library whether the output has already been converted or compensated, to prevent subtracting an offset twice, and keep the raw log and original config before computing. Read the sampling rate to separate a new sample from a repeated read
  4. When you have equipment, use the real-board preparation guide and the procedure of the manufacturer or flight stack. Keep the stationary interval, units, temperature, config and an independent measurement set not used in the fit; separate measured results from paper answers
  5. Return to Sensor Fusion when you can explain the input data and the scope. Calibration does not fix every error in time, axes or motion, and passing the exercise does not confirm steady flight

Sources of the practice set: the calibration model and reference sources · the calibration set hash list

Sensor fusion: making several sources help each other

The gyro is good for tracking rotation over short periods, while the accelerometer helps reference the direction of gravity when motion conditions are suitable. Data fusion must account for units, bias, noise and timing; it is not averaging two raw values with different units.

Start with the idea of a complementary filter to understand how each data source helps in a different frequency range, then study the EKF, which combines a state model and uncertainty with measurements. A flight stack's EKF also checks data consistency and quality, so using an EKF does not guarantee drift-free data in every case. See PX4 EKF v1.16

Download the IMU and message practice set for PC

Download the PC practice set with code, data and answers (ZIP) · Blank worksheet (CSV) · Combined answers (JSON) · File list and SHA-256

This set uses the Python standard library, so no extra packages need to be installed. All the data is generated from synthetic equations per protocol.json and is used to practise unit conversion, comparing angles and explaining message reception. The program and answers passed repeated runs on Windows Python 3.11/3.14 and Ubuntu Python 3.12, but no IMU has been measured and no real radio has been sent

  1. Extract the ZIP and read the assumptions: open a terminal in the extracted folder and read README.md and protocol.json check python --version on a system that uses the command python3 replace the command name on every line
  2. Check the practice set and run the two IMU cases: use the commands below and open the imu-analysis.csv and summary.json obtained in each result folder
  3. Run the 12-row messages: open message-analysis.csv and trace the reasons each row is accepted or rejected, together with the time and the source sequence number
  4. Fill in the worksheet before seeing the answers: state the units, assumptions and the CSV rows that are evidence, then compare with answers/ If it will not run, check the folder, file names and Python version before changing the formulas
python -m unittest discover -s . -v
python imu_lab.py imu --input data/imu-roll.csv --output results/imu-baseline
python imu_lab.py imu --input data/imu-motion.csv --output results/imu-motion
python imu_lab.py messages --input data/telemetry.csv --output results/messages

Axes and units of the exercise: body FRD means X forward/Y right/Z down, with roll positive by the right-hand rule. This set has only roll, with no pitch/yaw while lying level and still. The Z-axis specific force equals -9.80665 m/s2. The angle formula atan2(-ay,-az) therefore applies to this assumption. The gyro values in the CSV are in deg/s; the program converts them to rad/s and integrates by the trapezoid rule using dt from the real timestamps. The bias estimate uses the first second that the generator specifies as still. This formula does not replace the calibration step for every kind of device. A real system must check field names and times, such as PX4 SensorCombined v1.16 and the flight controller's coordinate frame

A graph of the computed results from synthetic IMU data, comparing the reference angle, a gyro with bias and a complementary filter, with an interval of added force

A graph computed from the practice set, not an image of real measurements. In the added-motion case, a 3 m/s2 force is added on the Y axis during 5-5.5 seconds. Open the full-size IMU graph to enlarge the details

Roll estimation method RMSE of the baseline case (deg) RMSE of the added-force case (deg)
Integrate a gyro that still has bias 2.887792 2.887792
Correct the bias, then integrate the gyro 0.000630 0.000630
Complementary filter 0.004671 2.386747
Filter with a norm check before using the accelerometer 0.004671 0.005033

RMSE against the reference angle set by the generator. In this set, the bias-corrected gyro does very well because the assumptions favour integration; this is not a conclusion that it is better than sensor fusion in a real system. The filter uses tau=0.5 s and alpha=tau/(tau+dt) and the norm gate accepts the accelerometer when the norm differs from g by no more than 0.3 m/s2. This is only a heuristic of the exercise: a norm close to g does not confirm that there is no motion or wrong axis

Message screening criteria: the exercise uses a single clock and a single boot session. An age of 40 ms passes but 41 ms is old; a future timestamp is rejected. A 16-bit sequence can wrap from 65535 back to 0; update the latest number only with accepted messages, and reject backward or half-range-ambiguous cases. The result is accepted 7, duplicate 1, out_of_order 1, stale 2 and future_timestamp 1, while the accepted-stream gaps of 3 are the missing numbers in the accepted list. It still cannot be concluded that the radio lost 3 packets . The CSV holds decoded messages; it did not check ESP-NOW/UART transmission, CRC or encryption

Practise step by step: read an IMU and screen messages with reasons

Objective: check axes, units, time and message order before using the data for control Prerequisite knowledge: able to read Serial and timestamps Suggested time: 45-60 minutes, a recommended time with no experimental results from real learners. A calculator/CSV reader can be used, or replay the PC set above with Python 3.11+

The practice sequence goes from PC data to checking axes, units and time, and analysing the IMU and the messages separately, before concluding within the scope

The guide image is used together with the photorealistic image above in the chapter. The data and results in this activity are the earlier synthetic ones, not measurements of a real sensor or radio

Download how to do it, the 8-question worksheet, the blank message screening table, the original 12-row messages and protocol before opening the answers with reasoning . The source and SHA-256 can be checked in manifest The two original files were selected directly from the earlier ZIP

1. Check axes and units before calculating - A1-A3

Read the protocol and write the FRD and the sign of the specific force at Z when lying level and still in the ideal case. Then convert the bias 0.5 deg/s to rad/s compute the angle accumulated from a constant bias over 10 seconds, and find alpha when tau=0.5 s, dt=10 ms State the unit of every answer, separating the value at the end of the interval from the RMSE over the whole interval

Recommendation: convert ms to s before substituting into formulas, and check the CSV column names before comparing with real firmware, such as PX4 v1.16 SensorCombined using the gyro rad/s, acceleration m/s² in body FRD and a timestamp in microseconds since system start

2. Explain the filter when a disturbing force is present - A4

Use the results imu-motion in the table above/the earlier summary, comparing the complementary and norm-gated filters and counting the samples in the 5.00-5.50 second interval that have the disturbing force per the protocol. Explain that a norm close to g does not prove there is no motion, and that a good result in a single fixture does not certify the filter on a real IMU

3. Screen messages row by row - A5-A6

Open telemetry.csv fill in age_ms, disposition, accepted_gap and the reasons in the blank table, where the number data_row is counted from the first data row, not including the header. Keep last_seq only the messages that accepted pass the checks in order: negative age -> age over 40 ms -> duplicate seq -> old or ambiguous seq -> accept

Try explaining two key points yourself: how ages of 40/41 ms give different results, and how 65534→0 differs from 0→65535 by computing delta=(seq-last_seq) mod65536 The forward edge accepted is 1..32767, while 0 (duplicate) and 32768..65535 are rejected in this protocol

4. Conclude only what the evidence supports - A7-A8

Total the accepted/rejected messages with the gaps and answer whether the gaps can tell of real radio loss. Explain why row 8 (seq=3, age -10 ms) is rejected but row 9 (seq=3, age 20 ms) can be accepted, and why the formula rx-sample must have the clock/boot/session declared before use with two devices

Self-check after doing it: open the answers, with a proposed 2 points per question (answer 1 + reason/unit or limitation 1), 16 in total. Record the topics to review in the worksheet. The score helps choose what to reread; there is no criterion certifying flight readiness, and it has not been assessed with real learners. Once you can explain it, continue with the Freshness chapter or MCU and Sim activities

Steps for a bench IMU experiment when you have equipment

Diagram: IMU -> check axes, units, time -> sensor fusion -> check order and data age before sending or recording

Fused data must have its age and conditions checked before use. The realistic image at the top of the page shows the equipment and plots as a concept, not measured results.

  1. Read the module example: check the connection and device ID, then log raw values or values converted by the library, stating the units and library name.
  2. Keep it still and collect data: use the timestamp_ms, gx, gy, gz, ax, ay, az table, record the actual interval between samples, and observe the mean and the spread.
  3. Rotate one axis at a time: mark the positive directions on the board, rotate slowly, and check whether the values change on the expected axis. Tilting while also moving makes the accelerometer harder to interpret.
  4. Test the estimation: if the library provides an orientation output, compare it with board positions of known orientation. Record units, conditions and behaviour at rest before tuning the filter.

Calibration should follow the procedure of the chosen sensor or flight stack. Adjusting offsets yourself to make the numbers look nice may hide axis or unit errors.

Designing verifiable messages

UART or ESP-NOW can be used for the exercises. Divide messages into control, telemetry and configuration to know their roles, but message type numbers such as 0xAA or 0xBB are only values set by the developer. Having a type number does not automatically assign priority.

Data/mechanism What problem it solves
version, type, length Rejects unsupported formats and payloads of the wrong size
sequence number Detects duplicated, out-of-order or lost messages; counter wrap-around must be defined
Time and data age Prevents old data from being used as if it were new; if sender time is used, the relationship between the two clocks must be known
Bounded queue and drop policy Limits backlog and chooses which data should replace the latest value
Task-level acknowledgement Confirms, when necessary, that the receiving application has received or used the data
Pairing and authorisation Controls which devices may send acceptable commands

ESP-NOW is a connectionless protocol over Wi-Fi on supported chips. A successful send callback at the MAC level does not confirm that the application has used the data. Work in the callback should be short and passed on through a queue. Unicast encryption requires correct peer/key settings, and do not assume broadcast is encrypted the same way. See the ESP-NOW documentation

Data-loss exercise and evaluation criteria

Send only the sequence number, a dummy value and a timestamp to display on serial or an LED, without connecting any actuator. Set a clear data-age threshold before testing, then stop the sender program or deliberately skip one sequence number. The receiver should report missing/stale data and be able to distinguish it from sensor reading errors.

The expected outcome is a CSV with clear units and axes, a table of actual time intervals, and a log that explains dropped messages. If values cannot be read, check the wiring, address and interface before changing the filter. If data stutters, check timing and backlog before concluding that the sensor is faulty. Continue to Advanced: STM32 and firmware once you can explain the data path.

Self-check of understanding

Open the three-level assessment with reasons with 4 questions per level, recording the before-reading/after-review rounds only in the browser. It uses the same questions and is not a measurement of real learners or a certificate

Prepare to collect evidence from a real board

A guide to preparing UNO/ESP32/STM32 experiments, with worksheets Check the wiring version, source/core clock and raw files before concluding the results. The guide is ready to use, but the real upload/measurement still awaits equipment

Choose the next practice set or review

Return to the index of the 10 MCU practice sets to choose a scenario according to your goal and the background you should know, or take the 12-question understanding assessment to find the topics to review

After checking the answers, record the answers you corrected, the reasons, and what the evidence still does not confirm, then choose the next set that helps answer that question. The worksheet score and the assessment are separate parts, used for choosing your own review

Used in courses

How to cite this page

Drone Institute, Rangsit University. (2026). Applied level: reading an IMU, fusing data and communicating on time. In UAS Technology Knowledge Hub (B.Tech.). https://rsu-uat.pk-research.work/en/kb/knowledge/microcontrollers/applied/

Original from Drone-Hub: https://drone.pk-research.work/knowledge/microcontrollers/applied/ · © PK-Research