When developing an IoT device, it is easy to assume that if a sensor responds and delivers the expected number of samples, it is functioning properly. However, you must also verify whether the firmware reads data at the intended intervals, because sensor sampling jitter and drift are invisible in sample counts. If you derive velocity changes from acceleration in motion analysis, an erroneous time step assumption can skew the calculation results.

In one of our Zephyr RTOS projects, we configured the IMU thread for 20 ms, targeting an IMU sampling rate of 50 Hz. The sensor responded normally, and incoming readings populated successive frames. Only on-device timestamps revealed that the firmware was actually sampling data every 24.86 ms on average. This resulted in approximately 40.2 Hz instead of the targeted 50 Hz.

The issue stemmed from how the thread executed its work and slept between reads. We restructured its scheduling and offloaded blocking reads from auxiliary sensors to separate threads. Following these two adjustments, the average interval reached 20.00 ms. We measured the intervals between reads, though we did not evaluate the impact of this timing discrepancy on any specific algorithm.

Why does sensor sampling fail to maintain the configured interval?

A configured 20 ms delay in code may only apply to the sleep duration itself. If the thread starts sleeping only after completing its execution, the entire iteration takes longer than intended.

In our firmware, a single frame bundled five acceleration readings alongside data from other sensors. The total sample count matched expectations, but that alone did not reveal how frequently the IMU was actually being polled. Verifying that required measuring the exact intervals between consecutive reads.

We captured timestamps from the device’s monotonic clock and recorded them at the start of reading the IMU registers over I2C. The sampling interval was simply the duration between these timestamps. What we did not measure was the exact internal conversion timing inside the sensor itself. Consequently, even with regular read cycles, we could not guarantee that every read retrieved the result of a fresh hardware conversion.

Fixed delay vs. fixed interval in a Zephyr periodic thread

A shared thread base class called perform() and only then slept for the configured duration. This is a common way to write a Zephyr periodic thread, and it looks harmless. In the BEFORE version, the implementation looked like this:

				
					self->perform();
if (k_sem_take(&self->m_shouldStop, K_MSEC(self->m_sleepTimeMs)) == 0)
{
    break;
}
				
			

Where timing drift comes from

The semaphore provided a mechanism to terminate the thread. If no stop signal was asserted, k_sem_take() returned after the timeout expired. For the IMU, this was 20 ms, measured only after perform() finished executing.

Under a fixed delay scheme, the 20 ms sleep is compounded by the thread’s execution time and any scheduler latency. In our case, the I2C read alone took roughly 2.05 ms on average, alongside other operations in the loop. The full iteration therefore took noticeably longer than the configured sleep parameter implied.

With a fixed interval, successive executions start at fixed points in time. If the thread completes its read before the next deadline, it sleeps only for the remainder of that period. The period absorbs execution time instead of extending it.

Blocking sensor reads in Zephyr RTOS

Inside perform(), the thread notified an observer whose callback read the IMU and accumulated samples into a frame. Every five successful reads, this same thread also fetched data from two BME280 sensors. Looking only at the main loop, it was easy to overlook these additional reads.

How blocking reads stretched IMU sampling

 sensor_sample_fetch() is synchronous. The Zephyr Sensor API documentation specifies that the calling thread blocks until the driver finishes retrieving data. This sensor_sample_fetch blocking behavior applied directly to the environmental sensor reads within our IMU thread. After both fetch calls and the remaining loop operations completed, the thread still slept for a full 20 ms.

Because the callback executed in the context of the IMU thread, any prolonged fetch operation delayed the subsequent acceleration read and stretched the sampling interval. When profiling for blocking I/O, you must inspect callbacks and invoked methods to identify which routines block on hardware access.

How we fixed the sampling schedule in Zephyr RTOS

We switched the IMU thread to absolute deadlines, using a Zephyr absolute timeout instead of a relative sleep. Before entering the loop, we initialize the deadline using k_uptime_get(). After perform(), the AFTER version executes the following block:

				
					deadline += self->m_sleepTimeMs;
const int64_t now = k_uptime_get();
while (deadline < now)
{
    deadline += self->m_sleepTimeMs;
}
if (k_sem_take(&self->m_shouldStop, K_TIMEOUT_ABS_MS(deadline)) == 0)
{
    break;
}

				
			

The deadline variable is incremented by fixed period steps rather than timing a fresh 20 ms from the moment execution ends. K_TIMEOUT_ABS_MS specifies an absolute point in uptime, in accordance with Zephyr Kernel Timing specifications. The semaphore still allows the wait to be interrupted if the thread must stop. Other threads retain the earlier fixed delay behavior, so the same change can be applied to any other Zephyr periodic thread that needs a stable cadence.

If you are weighing k_sleep vs k_timer for periodic work, the Zephyr timer documentation notes that a periodic k_timer does not drift relative to the system timer, which makes it another valid way to build a fixed-interval schedule.

If a deadline is missed, the interval between reads can still end up longer. When execution takes too long, the while loop skips elapsed target times so the thread waits for the next future slot. We do not fire off back-to-back reads to “catch up,” as that would not retroactively produce samples from past points in time.

We moved the BME280 reads to separate threads that asynchronously update an internal cache. When assembling a frame, the IMU thread grabs the latest cached values without blocking on two synchronous fetch calls. Environmental measurements follow their own slower dynamics, so a new IMU sample does not require a synchronized environmental measurement.

We deployed and evaluated both modifications together. Since we did not test them in isolation, we cannot determine what proportion of the improvement came strictly from absolute timeouts versus decoupling the BME280 reads.

Sensor sampling before and after the fix

Both firmware versions were evaluated on the same nRF52840 board. We retained identical diagnostic routines across both builds, as diagnostic logging incurs its own execution overhead. Records were written directly to a RAM buffer without emitting text logs on every read. Intervals were calculated using on-device timestamps, ensuring that BLE transmission latency to the host computer did not skew the measurements.

BEFORE IMU register-read intervals; WizzDev
  • BEFORE: Intervals consistently exceeded the intended 20 ms, with individual outliers approaching nearly 100 ms. The dashed line marks the target interval.

AFTER IMU register-read intervals; WizzDev
  • AFTER: Readings cluster tightly around 20 ms. The primary scale matches that of BEFORE, while an inset zoom from 19 to 21 ms highlights remaining deviations.
Metric BEFORE AFTER
Average interval
24.86 ms
20.00 ms
Effective sampling rate
40.2 Hz
50 Hz
Average five-interval window
124.3 ms
100 ms

From 40.2 Hz to 50 Hz

Following the fix, the firmware read the IMU at the intended average rate, and the prolonged outliers seen in the BEFORE profile disappeared. The effective sampling rate rose from 40.2 Hz to the target IMU sampling rate of 50 Hz. For each version, we analyzed two consecutive segments from the same run without rebooting in between; the rounded metrics across both segments were identical. Neither version exhibited I2C read errors or dropped records throughout the evaluated segments.

The five-interval window represents the elapsed time between reading i and reading i+5. At a 20 ms period, this equals 100 ms. Note that five samples within a frame span four intervals, representing the elapsed time from the first to the fifth read. The table compares read timing exclusively, omitting frame transmission overhead.

If downstream processing assumes a 20 ms time step while data arrives at an average interval of 24.86 ms, the assumed time base diverges from physical reality. Sample counts per frame alone cannot reveal this mismatch. We did not evaluate the downstream impact on any specific algorithm in this benchmark.

We gathered these measurements under controlled conditions on a single board, with the production NUS (Nordic UART Service) stream subscription disabled. The board also stayed connected over USB, which may have paused SD card writes. We have not yet confirmed whether this timing holds up under concurrent SD logging and active NUS transmission; that requires dedicated testing.

How timing drift differs from sensor sampling jitter

The distinction between timing drift vs jitter explains why the fix changed the average rate but did not make every interval perfect. Under a fixed delay scheme, processing time extends each iteration, causing reads to lag progressively further behind a nominal 20 ms grid. We refer to this cumulative shift here as timing drift. Individual intervals might appear uniform, but they remain too wide to sustain the intended cadence.

Jitter represents cycle-to-cycle variation between individual intervals. After the fix, intervals ranged roughly from 19.32 to 20.69 ms. Although the average hovered near 20 ms, individual readings still deviated from their scheduled targets. An absolute schedule sets deadlines on a fixed grid without adding execution times, yet the thread itself can still experience scheduling latency before waking up. This kind of residual RTOS jitter is normal; as Percepio explains in its article on debugging jitter bugs, some minor jitter is hard to avoid and rarely causes problems.

Consequently, post-fix firmware can sustain an average rate of 50 Hz while retaining a small amount of sensor sampling jitter. We evaluated the schedule relative to the device’s monotonic clock, without verifying crystal oscillator accuracy against an external instrument reference.

How to debug irregular sensor sampling

To measure sampling jitter reliably, start by capturing timestamps as close to the hardware sensor read as possible. Packet reception times in a host script (such as Python) reflect transport delays, while a frame timestamp often applies to a batch of samples. Accurately assessing sampling regularity requires the exact timestamps of individual reads.

Next, profile the total execution time of the IMU read, including callbacks and blocking I/O. Mutex contention or flash/SD writes can easily stall the subsequent iteration. Before tuning thread priorities, measure these runtimes and verify whether your configured period enforces a fixed delay or a fixed interval. If you are still choosing a platform, our comparison of Arduino vs FreeRTOS for IoT product development explains when an RTOS is worth it.

When designing the loop, define upfront how missed deadlines should be handled. In this project, we drop elapsed target slots. Other applications may require raising an error flag or buffering telemetry. When comparing firmware builds, keep diagnostic routines identical and check record integrity, because otherwise lost samples can easily be misread as delayed reads.

Key Takeaways

  • A configured 20 ms value may represent only sleep time. In a fixed-delay design, execution runtime adds directly to each loop iteration.

  • Blocking reads from other sensors stall sampling. Offloading auxiliary sensors to separate worker threads with a shared cache keeps the high-rate IMU thread lightweight.

  • A Zephyr absolute timeout and thread separation restored 50 Hz. In this benchmark, the average frequency reached exactly 50 Hz, though minor sensor sampling jitter remained.

  • Record timestamps at the driver level to measure sampling jitter and handle missed deadlines deliberately. Define whether your application should skip missed slots, interpolate, or flag an error.