Three chips, three crystals, one recording. Left alone, the always-on chip drifts 186 ms in ten minutes. A two-way exchange and a Kalman filter hold all three on one timeline.
Learn how firmware on several small chips agrees on what time it is: a shared pulse, a two-way message exchange, and a filter that estimates each chip’s offset and skew.
Pick a way to sync, then drag the link jitter. Watch the purple always-on chip, which has the worst crystal, and the blue media chip. Then we build, piece by piece, the sync layer underneath: the counters, the pulse, the exchange, the fit and the filter.
You need a little C and the idea that a clock is a counter that ticks. We build the rest from zero. The Kalman filter lesson helps for Chapter 6, but we derive what we use.
Built from primary sources, no slides: the NTP specification, RFC 5905, and the Lab Streaming Layer time synchronization notes. It follows Timestamp at the Pin. Every device here is a model that runs in your browser, not real silicon.
Illustrative model, not silicon. The media MCU runs +32 ppm fast and the always-on MCU −310 ppm slow (inside the ±500 ppm Nordic rates the nRF52840 LFRC at when it is calibrated), each crystal’s skew wandering 0.02 ppm per square-root second. The pulse method captures with 1 µs steps. The jitter slider is the standard deviation of one exchange.
Chapter 0
See why three chips that record the same moment disagree about when it happened, and why the gap keeps growing
A person wears a headband. It records brain signals, a microphone records the room, and a small camera records the face. The person claps once. Later you replay the recording. The clap is loud in the audio, sharp in the camera, and a spike in the brain signal. You line up the three streams and the spike lands half a second before the clap.
Nobody made a mistake in the analysis. Each stream came from a different chip, and each chip stamped its samples with its own sense of time. The three senses of time had drifted apart. This lesson builds the part of the firmware that stops that drift.
A wearable maker, Sabi, states the job in one line of a published role description: “Build the multi-MCU time-sync layer that lets us correlate EEG, audio, and camera data downstream.” We will build exactly that layer, in a browser model, from the ground up.
An MCU (microcontroller unit) is a small chip with a processor, memory and peripherals. It has no wall clock. It has a crystal: a sliver of quartz that vibrates at a steady frequency when you apply voltage, like a tiny tuning fork. The chip counts those vibrations.
The counter is the whole clock. If a 32.768 kHz crystal drives a counter, the counter goes up 32,768 times each second. To get seconds, the firmware divides the count by 32,768. A tick is one count. A timestamp is the counter value read at the moment something happened, often scaled to seconds.
The crystal is not perfect. Its real frequency is a little above or below the number on its label. The error is written in ppm, parts per million. A crystal that is 20 ppm fast makes 20 extra ticks in every million. Over one second that is 20 millionths of a second. Over an hour it is 20 × 10−6 × 3,600 s = 0.072 s, or 72 ms.
The product splits its work across chips. An acquisition MCU runs the biopotential front end and reads the EEG samples. A media MCU handles audio, the camera and the radio. An always-on MCU sleeps most of the time on a slow, cheap clock and wakes for events. Each chip has its own crystal, or its own on-chip RC oscillator. No two run at exactly the same rate.
How far apart can two be? A cheap on-chip RC oscillator (a resistor and a capacitor that set the pace, no crystal) is the loosest. Nordic rates the nRF52840’s 32.768 kHz RC oscillator, the LFRC, at ±500 ppm only when firmware recalibrates it often (every 8 s or less), and says temperature also moves it. Uncalibrated it is far looser. One chip at +500 ppm and one at −500 ppm differ by 1,000 ppm. That is 1 ms every second, or 3.6 s every hour.
Here the three chips all start in perfect agreement at time zero. Nothing ever corrects them. A blink happens at some moment, and each chip stamps it by reading its own counter. Drag the elapsed time and watch where the stamps land. The values are our toy numbers: the media chip is 32 ppm fast and the always-on chip is 310 ppm slow, a value inside the ±500 ppm band.
The warm mark is the master time. The blue and purple marks are what the media chip and the always-on chip write down for the same blink. Drag the minutes since boot.
Illustrative: both chips start aligned at boot. The media chip runs +32 ppm and the always-on chip −310 ppm against the acquisition chip. Error = ppm × 10−6 × elapsed seconds. This is a model of the arithmetic, not a measurement.
After 10 minutes the media chip stamps the blink 19.2 ms late and the always-on chip 186 ms early. After an hour the always-on chip is 1.116 s off. The gap grows in a straight line, because a constant ppm error adds the same amount each second. A camera at 30 frames per second shows a new frame every 33.3 ms, so even the media chip loses a frame in under 18 minutes.
Giving every chip the same crystal does not work. Two crystals from the same reel still differ by a few ppm, and temperature moves each one differently. So we do not remove the difference. We measure it, and we translate each chip’s timestamps onto one shared timeline.
There are three measurement tools. A sync pulse is one wire that all chips watch, so they can latch their counters at the same instant. A two-way exchange is a message sent out and answered, which lets a chip work out its offset even over a plain serial link. A filter turns the noisy measurements into a clean estimate of two numbers: the offset (how far apart the clocks read right now) and the skew (how fast the gap is growing, in ppm).
The hero above compares them. Free-running chips drift for good. A pulse every 60 seconds keeps the error under 19 ms for the worst chip, because it resets the offset but never learns the skew. The exchange plus a Kalman filter learns the skew too, and the error falls to tens of microseconds.
Chapter 1
Read a hardware counter safely, turn ticks into seconds, and keep the count honest when it wraps
Your firmware logs a button press at tick 4,294,967,200. A moment later it logs another at tick 150. The second press seems to come 4.29 billion ticks before the first. Nothing broke. The counter hit its top value and started again from zero.
Every time-sync scheme in this lesson starts from a counter reading. So we first make sure the reading is trustworthy. Two numbers describe any counter: how fine it ticks, and how big it can count.
The resolution of a counter is the length of one tick. A 32.768 kHz counter ticks every 1 / 32,768 s = 30.5 µs. A counter fed by an 84 MHz timer clock ticks every 11.9 ns. A finer tick lets you place an event more exactly inside one clock.
The accuracy of the clock is a different thing. It says how close the tick rate is to its label, in ppm (Chapter 0). A counter can have a very fine tick and still be 50 ppm fast. Fine resolution does not fix drift. Drift does not stop you from reading a fine tick. Keep the two ideas apart: resolution sets the smallest step, accuracy sets the slow slide.
Temperature and age move the accuracy. Nordic says the LFRC frequency changes with temperature, and that it can be calibrated against the 64 MHz clock’s crystal reference. A worn headband warms from room temperature to skin temperature in minutes. A skew that you measured at boot will not hold for the whole session. That is why Chapter 6 tracks skew as a changing number.
A counter has a fixed number of bits. An n-bit counter holds 0 to 2n − 1, then returns to 0. That return is the wrap. The time between wraps is 2n divided by the tick rate. These are the counters you meet on Cortex-M parts (check the reference manual of your exact part):
| Counter | Width and rate | Wraps every |
|---|---|---|
| STM32F407 TIM2 (32-bit timer) | 32 bits at up to 84 MHz | 51.1 s |
| Cortex-M4 DWT CYCCNT (cycle counter) | 32 bits at 168 MHz core clock | 25.6 s |
| nRF52840 RTC (real-time counter) | 24 bits at 32,768 Hz | 512 s |
| A 16-bit timer at 1 MHz | 16 bits at 1 MHz | 65.5 ms |
The wrap periods are plain division: 232 / 84,000,000 = 51.13 s, and 224 / 32,768 = 512 s exactly. A session that runs for an hour crosses 70 wraps of TIM2. Your code must count them.
Unsigned subtraction in C does the wrap for you. If now and then are both uint32_t, then now - then is the right number of ticks even when the counter wrapped once in between. The arithmetic is done modulo 232, so the wrap cancels.
The trick has one hard limit. It only knows one wrap. If more than one full period passes between your two reads, the subtraction cannot tell 3 ticks from 3 ticks plus a whole wrap. The answer is silently short by a whole number of periods. Drag the gap between reads in the device below, and choose a counter. Past the wrap period the read-out will tell you how much time vanished.
The saw is the counter value. Two dots are your two reads. Drag the gap between reads and watch the elapsed time you would compute.
Wrap periods are exact arithmetic (2bits / tick rate). The 84 MHz figure is the fastest timer clock of an STM32F407 APB1 timer and 168 MHz its maximum core clock; your board may run slower, so the wrap is longer. Check your part’s reference manual.
The fix is an extended counter: keep a 64-bit count in software. Each time you read the hardware, compare with the last low word. If the new low word is smaller, a wrap happened, so add one to a high word. You must read often enough to catch every wrap, or let the timer’s update interrupt do the counting.
c/* 64-bit ticks from a 32-bit timer. Call at least once per wrap (51 s for TIM2 at 84 MHz). */ static volatile uint32_t hi, last_lo; uint64_t ticks64(void) { __disable_irq(); /* the update ISR may also touch hi */ uint32_t lo = TIM2->CNT; /* the hardware counter */ if (lo < last_lo) hi++; /* the counter went down: it wrapped */ last_lo = lo; uint64_t t = ((uint64_t)hi << 32) | lo; __enable_irq(); return t; }
A 64-bit count at 84 MHz lasts about 6,960 years before it wraps, so you can forget the problem. Every later chapter uses ticks64() as “the local clock”.
The failure, as symptom, measurement, fix. The symptom: a log shows one sample stamped 51 seconds in the past, then normal again. The measurement: print the raw low word on both sides of the glitch. It drops from near 4.29 billion to near zero, and the glitch repeats every 51.13 s. The fix: the extended counter above, plus a test that runs the clock across a wrap on purpose.
On real hardware: on an STM32 Nucleo (for example F446RE), run TIM2 at the fastest tick, toggle an LED every wrap and measure the wrap period on a scope or logic analyzer. Compare it with 232 divided by your timer clock.
Chapter 2
Use one shared wire to make three chips write down their counters at the same instant, then see what that gives you and what it cannot
Three people stand in separate rooms with their own stopwatches. You want to know how far apart the stopwatches are. You shout “now” through a speaker that all three rooms hear at once. Each person writes down their stopwatch reading at that shout. Compare the three numbers and you know the offsets at that instant.
A sync pulse is that shout. It is one wire from the master chip to every other chip. The master drives it from low to high. Every chip sees the same edge, within a few nanoseconds of wire delay. That is far finer than the microsecond ticks we care about.
Each chip must write down its counter at the edge, and it must not be late. If the chip waits for an interrupt, then reads the counter in the handler, the read happens after a delay that varies: other interrupts, a flash wait state, a sleep wake-up. Timestamp at the Pin measured that jitter. The better way is input capture: the timer hardware copies its counter into a capture register at the exact tick of the edge, with no software in the path.
On an STM32 general-purpose timer, input capture mode copies TIMx_CNT into the register TIMx_CCRy when the chosen edge arrives on the pin. The firmware reads CCRy later, at leisure. The nRF52840 does the same with its TIMER: a capture task, driven by a GPIO event through the PPI system, copies the counter into a CC register. Nordic documents TIMER as a counter that can be 32 bits wide on a 16 MHz base clock.
Now the always-on chip shows a limit. The nRF52840 RTC counts 32.768 kHz ticks with a 30.517 µs resolution. Nordic lists no capture task for it: the RTC only has compare registers. So firmware reads its COUNTER in an interrupt, which adds latency jitter, or it wakes a TIMER with a capture task, which costs power. A slow counter also has a coarse tick. Either way, one tick of that counter sets the floor for how well that chip can be placed on the shared timeline.
Pulse number k fires at some master time. The master latches its own counter too, as M[k]. Chip i latches C[k]. Convert each count to seconds with its nominal tick rate. The offset of chip i at that pulse is
To stamp a later event at local time c, chip i reports c + θk. That is correct only at the pulse. After the pulse the chip’s clock runs at its own rate, and the true offset slides away at the skew. The stamp error grows as skew × time since the pulse.
A worked number. The always-on chip is 310 ppm slow. The pulse period is 60 s. Just before the next pulse the error is 310 × 10−6 × 60 s = 18.6 ms. The media chip at 32 ppm reaches 32 × 10−6 × 60 = 1.92 ms. That is the saw-tooth in the hero’s pulse mode. A shorter period cuts it in proportion: every 6 s the always-on error is 1.86 ms. But each pulse costs wire toggles and wake-ups on every chip.
Two pulses give two offsets. The change between them, divided by the time between them, is the skew. In symbols, δ = (θk − θk−1) / P, where P is the pulse period. With that estimate the chip can extrapolate: it reports c + θk + δ × (time since pulse). The saw-tooth shrinks a lot. What remains is the quantization of the latch (up to one tick), the wander of the skew, and the error in the slope.
The slope error shrinks as the period grows, because a fixed tick error is divided by a longer P. One microsecond of latch error over 60 s is a skew error of 0.017 ppm. So a long pulse period gives a very exact skew and a short one gives a fresher offset. You can feel that trade in the device below.
The line is the stamp error over ten minutes. Choose the pulse period, and switch skew fitting on or off.
Illustrative model: the same drifting clocks as the hero (skew wandering 0.02 ppm per square-root second). Each latch adds a uniform error of one tick. The error is signed: stamp minus true master time, shown as a magnitude.
A pulse has no name. Chip i sees an edge, but it does not know which edge. If one pulse is lost to noise, the chips count different numbers of pulses, and the offsets are wrong by a whole period. The master must also say what time each pulse stands for. That needs a message: “pulse 17 fired at master tick 5,031,998,764”, sent over a serial link after the edge.
A pulse also needs a wire. A BLE peripheral on the wrist cannot share one with a phone. And a wire can pick up noise, so give it a clean receiver (a Schmitt trigger input) and number every pulse. The next chapter drops the wire and uses only messages.
On real hardware: on two STM32 Nucleo boards, wire a GPIO output of board A to a timer capture input of board B and of A itself. Fire a pulse every 10 s and log both capture values. The difference should creep at the two crystals’ relative ppm. Plot it.
Chapter 3
Learn a chip’s offset from four timestamps over any serial link, and see exactly how much the answer can be wrong
The media chip sits on another board, and the only link between the boards is a UART cable. No spare wire exists for a pulse. The media chip wants to know how far its clock is from the acquisition chip’s clock. It can send a message, and the message takes time to arrive. That delay is the whole problem.
Suppose the acquisition chip simply sends “it is 1,026.2 ms”. By the time the media chip reads it, the number is old. The media chip cannot tell how old. The trick is to make the message come back, so the media chip can measure the round trip on its own clock.
The exchange has two messages and four stamps. The names follow the NTP specification, RFC 5905. We call the chip that asks the client (the media chip) and the chip that answers the server (the acquisition chip, our master).
T1 and T4 use the client’s clock. T2 and T3 use the server’s clock. No one needs to know the true time. We only compare differences measured by the same clock.
Let θ be the unknown offset: server clock minus client clock. Let d1 be the true travel time of the request and d2 the true travel time of the reply. When the request travels, the server clock reads T1 + θ + d1 on arrival. So T2 − T1 = θ + d1. For the reply, T4 = T3 − θ + d2, so T3 − T4 = θ − d2. Add the two lines and divide by two:
Take a UART link. The true offset is θ = 25 ms (unknown to the client). The request takes d1 = 1.2 ms. The server holds the request 0.5 ms before it replies. The reply takes d2 = 0.8 ms.
The client believes 25.2 ms. The truth is 25.0 ms. The error is 0.2 ms, exactly (1.2 − 0.8) / 2. The client never learned d1 or d2. It only learned their sum, 2.0 ms.
That sum gives a strong promise. Both delays are at least zero, so |d1 − d2| can never exceed d1 + d2. The offset error is therefore at most δ / 2. Here that bound is 1.0 ms, and the real error is 0.2 ms. The client can prove a worst case from its own measurement.
Time runs downward. Left is the client clock, right is the server clock, which runs 25 ms ahead. Set how long each message takes on the wire.
Toy numbers: true offset 25 ms, server holding time 0.5 ms. The formulas are those of RFC 5905 section 8. In a real link the two delays are not chosen by you; they come from queues, interrupts and radios.
The formula hides one bet: that the two legs take equal time. Slide the request and reply times apart in the device and the error follows (d1 − d2) / 2. When is the bet bad? When the request waits in a software queue on the client before it leaves, or when the reply is built by a task that the server’s scheduler delays. Neither delay is on the wire, yet both land in d1 or d2.
So stamp as close to the wire as you can. T1 should be read when the first bit leaves, not when send() is called. A UART transmit-complete flag, a DMA callback or a timer capture on the chip-select edge are better than a timestamp taken before the call. The same holds for T2, T3 and T4. This is the lesson of Timestamp at the Pin applied to messages.
ctypedef struct __attribute__((packed)) { uint8_t type; /* 1 = request, 2 = reply */ uint8_t seq; /* matches a reply to its request */ uint64_t t1; /* client ticks64() when the request left */ uint64_t t2; /* server ticks64() when the request arrived */ uint64_t t3; /* server ticks64() when the reply left */ } sync_msg_t; /* 26 bytes on the wire */ /* client side, when the reply lands (t4 stamped in hardware) */ void on_reply(const sync_msg_t *m, uint64_t t4) { int64_t a = (int64_t)(m->t2 - m->t1); int64_t b = (int64_t)(m->t3 - t4); int64_t theta = (a + b) / 2; /* offset in ticks */ int64_t delta = (int64_t)(t4 - m->t1) - (int64_t)(m->t3 - m->t2); feed_filter(m->t1, theta, delta); /* Chapters 4 to 6 */ }
At 115,200 baud with 8N1 framing, one byte takes 10 bit times: 86.8 µs. The 26-byte reply alone is 2.26 ms on the wire. That is fixed and known, but the timestamps inside the message must have been captured before they were sent. The server cannot put the transmit-complete time in a packet that has already left. Send T3 in the next message, or stamp T3 at the first byte and fix the byte count.
On real hardware: on two STM32 Nucleo boards joined by a UART, stamp T1 to T4 with a free-running 1 MHz timer and print δ for 1,000 exchanges. A histogram of δ shows the link’s real spread.
Chapter 4
Compare UART, SPI and BLE as time links, and learn why the exchange with the smallest delay is the one to believe
You run the exchange from Chapter 3 a thousand times over a UART. You get a thousand slightly different offsets. Most sit close together. A few are far off. Which one is the true offset? None of them is exactly right, and averaging them all will drag in the bad ones.
The reason is in the formula. Each exchange has an error of (d1 − d2) / 2, and the legs d1 and d2 change every time. The wire itself is steady. What changes is the software and the hardware around it: an interrupt that runs first, a DMA transfer that waits for the bus, a radio that waits for its next event.
A UART sends bytes one after another at a fixed baud rate. At 115,200 baud, one 8N1 byte is 10 bits, so 86.8 µs. The delay on the wire is exact and known. What varies is when the transmit starts and when the receiver notices the byte. With DMA and a hardware stamp, that jitter is tens of microseconds.
An SPI link is clocked by the master. At 8 MHz, one byte takes 1 µs, so a 26-byte message is 26 µs on the wire. SPI is fast, but the slave cannot start a message on its own. The master must ask. That makes the two legs different by construction: the request waits for the master to poll, and the reply is clocked out at once. Stamp the chip-select edge on both sides and the wait is no longer in the stamp.
BLE (Bluetooth Low Energy) sends data only at connection events, spaced one connection interval apart. A packet you queue just after an event waits for the next one. If your code stamps T1 at the moment it queues the packet, the stamp includes that whole wait, and the wait for the reply is a different random number. The legs are wildly asymmetric. If instead the radio hardware stamps the packet at the event itself, the wait leaves the stamp and the legs become nearly equal. Where the radio offers an event timestamp, use it.
Chapter 3 proved that the error of one exchange is at most δ / 2, where δ is its measured round-trip delay. That bound is not a guess. It follows from the fact that no message arrives before it was sent.
Now read it backward. An exchange with a small δ has a small bound. An exchange with a large δ may be fine, but it may be badly wrong, and you cannot tell which. The honest move is to keep the best and drop the rest. This is the minimum-delay filter: out of the last N exchanges, use the one with the smallest δ.
NTP does the same. Its clock filter keeps the eight most recent samples and sorts them by delay, lowest first. The offset of the first one feeds the rest of the system (RFC 5905, section 10).
A worked check with four exchanges, offsets in µs and delays in µs: (δ 2,400, error +310), (δ 2,300, error +40), (δ 7,900, error −2,100), (δ 2,500, error +90). The mean error is (310 + 40 − 2,100 + 90) / 4 = −415 µs. The minimum-delay pick is the second exchange, error +40 µs. One slow exchange spoiled the mean. The bound agrees: its δ / 2 = 3,950 µs admits a big error, and it had one.
The price is data. If you keep one exchange in sixteen, you get fewer measurements. You can ask for more exchanges, or ask less often and trust the filter in between (Chapters 5 and 6). The device lets you pick the window.
Each dot is one exchange: how long its round trip took against how wrong its offset was. Pink dots are the ones the filter keeps. Drag the window size.
Illustrative delay models, not measurements: a fixed wire time (26 bytes) plus random software delay with a long tail per leg; BLE adds a wait of up to a 30 ms connection interval per leg when stamped in code. The funnel is the proven bound: error cannot exceed half the delay.
The funnel in the picture is the bound. Every dot lies inside it. On the UART the dots hug the apex, so even the mean is near the truth. On BLE stamped in code, dots spread to the wings, and only the filter saves you. On BLE stamped at the radio, the funnel is narrow again.
The best exchange is still just one noisy number. The minimum-delay filter removes the worst outliers. It does not remove the symmetric noise that remains, and it does not remove a constant asymmetry. If the request path is always 100 µs longer than the reply path, every exchange is 50 µs off in the same direction, and no filter can see that. You can only find it by comparing with a pulse, a scope or a logic analyzer (Chapter 9 of the field guide lists the check).
The failure, as symptom, measurement, fix. The symptom: the media chip’s timeline sits a steady 600 µs from the pulse-based one. The measurement: capture a pulse and the exchange of the same instant on both chips and compare. The fix: find the software queue or driver delay that makes one leg longer, move the stamp nearer the wire, or measure the fixed bias once and subtract it.
On real hardware: on an nRF52840 DK, run the exchange over BLE twice, once stamping in the handler and once with the radio event captured by a TIMER through PPI. Plot δ for each. The first is spread over the connection interval, the second is not.
Chapter 5
Fit a straight line through noisy offset measurements, read the skew from its slope, and decide how many points to trust
Every five seconds the media chip finishes one exchange and gets one offset. Each is a little wrong. Plot the offsets against time and they form a slanted smear. The smear slopes because the crystals disagree: that slope is the skew. The scatter around the slope is the jitter.
One point tells you the offset now, with its noise. A hundred points tell you the offset and how fast it is changing, with much less noise. The tool that turns the smear into two numbers is a straight-line fit.
Model the offset as a line: θ(t) = a + b t. The intercept a is the offset at time zero. The slope b is the skew, in seconds of offset per second, which is the same as a unitless fraction. Multiply by 106 to get ppm. A slope of 0.0297 ms per second is 29.7 µs per second, which is 29.7 ppm.
Which line? The one that makes the squared gaps between the points and the line as small as possible. That is least squares. Squaring does two things: it treats up and down errors alike, and it punishes a big miss more than several small ones. For a line, the best a and b have a closed form:
Five exchanges, 10 s apart. Offsets in ms: 0.02, 0.33, 0.61, 0.94, 1.20 at t = 0, 10, 20, 30, 40 s.
With a line, the chip can name its offset at any time, not only at the moments of an exchange. That is the second gain. Between exchanges the stamp error no longer grows as skew × time, because the skew is now part of the map.
The slope noise follows a clean rule. If each offset has noise σ, the slope error is σ divided by the square root of Σ(t − t̄)2. For N points spaced T seconds apart, that sum is T2 N (N2 − 1) / 12. Check with our five points: 100 × 5 × 24 / 12 = 1,000, which matches. Double the number of points and the sum grows about eight times, so the slope error falls to about 0.35 of its old size.
So why not fit a thousand points? Because the line assumes the skew stays constant. A crystal’s skew moves with temperature, so old points describe an old skew. A long window averages away the noise but lags behind real change. A short window follows change but trusts noise. This is the first tuning knob of the whole lesson. Drag it below. The Lab Streaming Layer makes the same assumption: its XDF importers fit a straight line to each stream’s clock offsets, assuming constant clock drift.
Grey is the error of a single exchange. Pink is the error of the fitted line at the same moment. Both use the always-on chip’s wandering clock. Change the window and the jitter.
Illustrative model: one exchange every 5 s, Gaussian jitter with the chosen standard deviation, no asymmetry. The fit uses the last N exchanges and is evaluated at each exchange time. Real links add asymmetry and outliers (Chapter 4).
A short window follows the wandering skew but its slope is noisy. A long window gives a smooth slope that lags. Somewhere in the middle the error is lowest. The best window also depends on the jitter: with a quiet link a short window wins, with a noisy link you want more points.
Firmware does not store the whole pile. It keeps five running sums over the window: N, Σt, Σz, Σtz and Σt2. Adding a point adds to the sums. Dropping the oldest subtracts its terms. The slope is b = (N Σtz − Σt Σz) / (N Σt2 − (Σt)2).
The failure, as symptom, measurement, fix. The symptom: the fitted skew jumps by hundreds of ppm as the session gets longer. The measurement: print Σt2 and the denominator. A float32 has a 24-bit mantissa. A microsecond count of 3.6 billion (one hour) falls between 231 and 232, where float32 steps by 256 µs, larger than the jitter we want to fit. The fix: keep ticks in int64, subtract the start of the window, and only then convert to float. Times and offsets near zero keep their precision.
c/* sliding least squares for offset(t) = a + b*t. Times are int64 ticks minus t0, so doubles stay precise. */ typedef struct { double n, st, sz, stz, stt; } lsq_t; void lsq_add(lsq_t *s, double t, double z) { s->n++; s->st += t; s->sz += z; s->stz += t*z; s->stt += t*t; } void lsq_sub(lsq_t *s, double t, double z) { s->n--; s->st -= t; s->sz -= z; s->stz -= t*z; s->stt -= t*t; } int lsq_fit(const lsq_t *s, double *a, double *b) { double den = s->n * s->stt - s->st * s->st; if (s->n < 2 || den <= 0) return 0; *b = (s->n * s->stz - s->st * s->sz) / den; /* skew, seconds per second */ *a = (s->sz - *b * s->st) / s->n; /* offset at t0 */ return 1; }
On real hardware: log (T1, offset) pairs from an STM32 Nucleo pair for an hour while you warm one board with your hand. Fit a 12-point window and a 60-point window offline and compare their skew traces.
Chapter 6
Track two numbers at once, predict between exchanges, and correct with each new measurement by exactly as much as you trust it
The line fit of Chapter 5 has a weakness. It waits for N points, then it forgets the oldest one all at once. It treats every point alike, even though you know some exchanges were cleaner. It cannot say how sure it is. And if the link drops for a minute, it has nothing to say.
A Kalman filter fixes these. It keeps its belief about the clock as a small state, predicts forward in time with the physics of drift, and corrects the prediction when a measurement arrives. It is a running average that knows its own uncertainty. If you have met it before, the Kalman filter lesson goes deeper. Here we derive only what we use.
The state x holds what we want to know: x = [θ, δ]. The first number θ is the offset (seconds). The second δ is the skew (seconds per second). They are linked: the skew is how fast the offset changes.
Predict. Over a step of dt seconds, the offset grows by skew × dt and the skew stays the same. As matrices, xnew = F x with F = [[1, dt], [0, 1]]. We cannot be sure the skew stays put, because the crystal wanders. So prediction also makes us less certain. The covariance P (our uncertainty about x) grows: Pnew = F P FT + Q. The matrix Q says how much the state can wander in one step. Here it is a small number for the offset and a smaller one for the skew.
Update. An exchange gives a measurement z of the offset only, so H = [1, 0]. Its noise has variance R, which is the jitter squared. The filter compares the measurement with its prediction. That gap is the innovation, y = z − θ̂. Then it moves both state numbers by a fraction of y, set by the Kalman gain K. K is a trust slider: near 1 means trust the measurement, near 0 means trust the prediction. The gain comes from the two uncertainties:
Units are ms and seconds. Before the update, after predicting 5 s ahead, the filter holds θ̂ = 1.150 ms and δ̂ = 0.0300 ms/s (30 ppm). Its uncertainty is P00 = 0.0100 ms2 and P01 = 0.0004. The jitter is 0.5 ms, so R = 0.25. The exchange reports z = 1.40 ms.
The filter moved the offset by less than 4% of the surprise. It knew the exchange was noisy (R is large against P00), so it trusted its own prediction. The skew moved by a tiny amount too. After hundreds of exchanges those small nudges add up to a precise skew. If the link got cleaner and R shrank, K would grow and the filter would follow each exchange more closely.
R is easy: measure the spread of your exchanges (Chapter 4) and square it. Q is harder. It is the crystal’s wander. Too small a Q makes the filter stubborn: when a real change comes, such as the chip warming up, it follows far too slowly. Too large a Q makes it nervous: it follows every noisy exchange and loses the benefit of filtering. The ratio Q / R is what matters most.
The device runs the always-on chip with 500 µs of jitter. Turn on the temperature step: at five minutes the true skew jumps by 20 ppm, as if the chip were warmed by a hand. Compare the Kalman error with the 12-point line fit, and move Q and R by factors of up to 100 from their correct values.
Pink is the Kalman filter. Grey is the 12-point line fit from Chapter 5. Both see the same exchanges. Scale Q and R, and switch on a skew step.
Illustrative model: the always-on chip (−310 ppm), jitter 500 µs, an exchange every 5 s. The scale 1 uses the true jitter squared for R and the true wander (0.02 ppm per square-root second) squared for the skew part of Q. Real Q and R are estimates you tune from data.
Try it in this order. With the step off and both scales at 1, the filter beats the 12-point fit: about 144 µs typical against 243 µs. Now switch the step on. A 20 ppm jump is far more than the quiet wander the filter was told to expect, so it takes minutes to accept it: about 620 µs in the minute after the step, and still 1.6 ms later, while the line fit follows within a minute. Raise Q by ×30 and the filter follows too (about 225 µs after the step, 150 µs later), at the price of a little more steady noise (193 µs before the step). Q must cover the events you expect, not only the quiet wander. These numbers are for this seed and this model.
The filter predicts. If the link drops for a minute, it keeps running with its last skew, and the error grows slowly: Chapter 7 uses this as holdover. A pulse-only scheme would stay stuck at its last offset and drift at the full skew.
The failure, as symptom, measurement, fix. The symptom: after a long quiet link the filter reports a tiny uncertainty but the timeline is 2 ms off. The measurement: log the innovation y and S for each update. A well-tuned filter has y within about two √S of zero nearly all the time. Here y sits at several √S. The fix: raise Q, or add a check that rejects an exchange whose δ is large and widens P when too many are rejected.
On real hardware: run this filter on an STM32 Nucleo against a second board’s pulse. Plot the filter’s estimate minus the pulse-derived offset over an hour, then warm one board and watch the skew state move.
Chapter 7
Wire the counter, the exchange and the filter into one layer that translates any local timestamp to master time, and keeps going when the link drops
You now have the parts. A hardware counter on each chip (Chapter 1). A way to compare counters: a pulse (Chapter 2) or an exchange (Chapter 3). A way to choose good exchanges (Chapter 4). A filter that turns them into an offset and a skew (Chapters 5 and 6). This chapter puts them behind one small interface that the rest of the firmware can use.
The layer has one job: answer the question “this thing happened at local tick c; what was the master time?” Everything else is hidden.
Choose one chip as the reference. In our device it is the acquisition MCU. It reads the EEG converter at a fixed rate, and those samples are the data that must stay exact. The media chip and the always-on chip are clients. They each run the exchange with the master and each hold their own filter. There is no vote and no loop of corrections: the master’s counter is the timeline.
The master does not slow down or speed up its clock to match anyone. A client never steers its crystal either. Instead each chip keeps its crystal as it is and keeps a map from its own ticks to master time. Steering a clock hides the drift but makes timestamps jump; a map keeps raw stamps and lets you improve the mapping later.
The map is a line, valid from the moment of the last filter update: master = c + a + b × (c − cref). Here c is any local tick, cref is the local tick of the last update, a is the offset at cref and b is the skew. The layer publishes new values of (cref, a, b) after every exchange.
Now a design choice that matters for what comes next. There are two places to apply the map.
We do the second and also expose the first for live use. The Lab Streaming Layer works much the same way: each sample gets a timestamp from the sender’s own local clock, and the clock offsets are measured separately, by short UDP packet exchanges similar to NTP, repeated every few seconds. A recorder adds the latest offset to each inlet’s timestamps (LSL documentation, time synchronization). Our sync log plays that part for chips.
Links fail. A BLE connection drops when the wearer turns away. A UART cable can pick up noise. The layer must not stop. Without new exchanges the filter has nothing to correct with, but it still has a good skew. It keeps predicting: offset grows by skew × time. That mode is holdover. The map stays good for a long while, and its uncertainty grows with time since the last update.
Compare with the simplest alternative, which holds the last offset and stops. The always-on chip is 310 ppm slow in our model. If the offset is frozen for 5 minutes the error reaches 310 × 10−6 × 300 s = 93 ms. With the skew in the map, holdover leaves tens to hundreds of microseconds. Break the link below and compare.
The link is up until 3 minutes, then goes down for as long as you choose. The line is the error of the always-on chip’s timeline. The band is the filter’s own ±2 standard deviations.
Illustrative model: the always-on chip (−310 ppm), jitter 200 µs, an exchange every 5 s, skew wandering 0.02 ppm per square-root second. The band is shown only for holdover with skew, where the filter’s uncertainty means what it says.
With the skew, the error rises gently during the outage (about 30 µs after 60 s and 93 µs after 300 s in this model) and stays small when the link returns. With a frozen offset it reaches 18.6 ms after 60 s and 93 ms after 300 s, then needs a while to re-lock. The band widens as time passes, so downstream code can read it as a quality flag: “locked” when the band is tight, “holdover” when it is growing, “lost” when it passes your budget. Ship that flag in the sync log.
c/* one record per filter update; shipped in the sync log and used on-chip */ typedef struct __attribute__((packed)) { uint64_t c_ref_ns; /* local ticks (as ns) at the update */ int64_t a_ns; /* offset at c_ref: master = local + a */ int32_t b_ppb; /* skew in parts per billion (310 ppm = 310000) */ uint16_t sigma_us; /* filter's 1-sigma offset uncertainty */ uint8_t state; /* 0 = lost, 1 = holdover, 2 = locked */ } sync_rec_t; uint64_t to_master_ns(const sync_rec_t *r, uint64_t c_ns) { /* dt * b_ppb in one int64 overflows after about 8 hours at 310000 ppb, and a Cortex-M has no __int128. So split dt into whole seconds and a remainder. */ int64_t dt = (int64_t)(c_ns - r->c_ref_ns); int64_t sec = dt / 1000000000; int64_t rem = dt % 1000000000; /* under 1e9, so rem * b_ppb stays far below 2^63 */ int64_t corr = sec * r->b_ppb + rem * r->b_ppb / 1000000000; return c_ns + r->a_ns + corr; } void on_filter_update(const kf_t *kf, uint64_t c_ns) { sync_rec_t r = { c_ns, (int64_t)(kf->theta * 1e9), (int32_t)(kf->delta * 1e9), (uint16_t)(sqrt(kf->p00) * 1e6), STATE_LOCKED }; log_send(&r); /* the sync-log stream */ publish_map(&r); /* the live map the app uses */ }
Each record is 8 + 8 + 4 + 2 + 1 = 23 bytes. One per 5 s costs 4.6 bytes per second, tiny against an audio stream. For a rough check: 250 samples per second of 8-channel 24-bit EEG is 6,000 bytes per second. The ADS1299 offers 8 channels at 24 bits and 250 to 16k samples per second.
The failure, as symptom, measurement, fix. The symptom: after eight hours the media chip’s stamps jump by seconds. The measurement: print (c − cref) × b in 64 bits. With b = 310,000 ppb the product exceeds 9.22 × 1018 once c − cref passes 2.97 × 1013 ns, about 8.3 hours. That only happens if cref is stale. The fix: split the gap into whole seconds and a remainder, as above (a Cortex-M compiler has no 128-bit integer), and let holdover flag “lost” long before that point.
On real hardware: on a nRF52840 DK and an STM32 Nucleo joined by a UART, run the layer for ten minutes, pull the cable for 60 s, and plug it back. Plot the error against a shared pulse during and after the gap.
Chapter 8
Follow the timestamps off the wearable into a recorder, and learn which errors a fit removes and which it cannot
The headband now has a clean map from every chip to master time. A phone receives the EEG packets over BLE and the audio packets over another link. A program on a laptop records everything to disk. If that program stamps each packet at the moment it arrives, all your work on the chips is thrown away, because arrival time carries the radio’s delay and the phone’s scheduling.
The recorder must use the stamps the device made. This chapter shows what a downstream tool does with them. We use the Lab Streaming Layer (LSL) as the model, because it is the common open tool for exactly this job, and its time-sync notes are public.
LSL gives every sample a timestamp read from a local monotonic clock, lsl_local_clock(). Each machine has its own. To compare machines, LSL measures the clock offsets by exchanging short UDP packets, similar to NTP, and repeats this every few seconds. A recorder can call time_correction() on an inlet and add the result to that inlet’s timestamps. A flag, proc_clocksync, adds the latest offset automatically. The LSL notes say adding the latest offset is usually enough, because the remaining error is small compared with the raw timestamp jitter.
That is the same shape as our layer. Raw stamps on a local clock, plus a stream of measured offsets, joined later. Our chip-to-master map is one hop. LSL’s machine-to-machine offset is the next hop. The total error is the two hops together. If the errors are independent, they add as a root of squares: 50 µs on the chip and 300 µs on the host hop give √(502 + 3002) = 304 µs. The bigger hop wins, so spend effort there first.
Samples reach the host in packets. A BLE packet might carry ten EEG samples. All ten share one arrival time, though they were taken 4 ms apart at 250 samples per second. Radio retries add random delay on top. A sample’s stamp is then wrong in two ways: a sawtooth from batching and a random wobble from the link.
For a stream with a steady sample rate, there is a better clock than the arrival stamp: the sample count. Sample number n was taken n / fs seconds after sample 0. If you fit a straight line of arrival stamp against sample number, the line puts every sample on an even grid. This is dejitter. LSL offers it as the proc_dejitter flag, which smooths the timestamps of regularly sampled streams; its smoothing settles within a minute or two. The XDF importers (such as pyxdf) do it offline: they fit a line to each stream’s clock offsets, assuming constant drift, and for regularly sampled streams they also fit sample index against timestamp inside each uninterrupted segment.
The fitted slope is a bonus. It is the stream’s real sample rate. The converter has its own crystal, so a nominal 250 samples per second may be 249.99. Over an hour that is a difference of 36 samples, which is 0.144 s. Without the fit that gap becomes part of your timeline error.
Dejitter has a limit, and it matters. It removes the random wobble and the sawtooth. It does not remove a constant delay. If every packet arrives 3 ms after its last sample was taken, the fitted line is 3 ms late for every sample, forever. A fit cannot see a bias that never changes. Only a hardware stamp at the source or a one-time calibration can.
A stream at 250 samples per second reaches the host in packets. Each dot is one sample’s timestamp error. Choose the packet size and link jitter, then switch the dejitter fit on.
Illustrative model: 250 samples per second for 1.2 s, each packet stamped on arrival 3 ms after its last sample plus Gaussian jitter. The fit is least squares of stamp against sample number over all 300 samples. Compare with the LSL notes cited above.
With the fit off, the error ranges across the whole packet: ten samples at 4 ms spacing span 36 ms. With the fit on, the spread collapses to a few tenths of a millisecond, but the whole line sits at a constant offset. That offset is the mean delay: the fixed 3 ms plus half of the packet time. Subtract it once, from a calibration, and you are done.
pythonfrom pylsl import StreamInlet, resolve_byprop, proc_clocksync, proc_dejitter info = resolve_byprop("name", "EEG", timeout=5)[0] inlet = StreamInlet(info, processing_flags=proc_clocksync | proc_dejitter) sample, ts = inlet.pull_sample() # ts: remote timestamp, offset added, jitter smoothed offset = inlet.time_correction() # the current clock offset, if you want it yourself # Our gateway pushes samples with the device's translated stamp (to_master_ns), not arrival time: # outlet.push_sample(x, timestamp=master_ns / 1e9 + host_offset)
The flag names proc_clocksync and proc_dejitter are from the LSL documentation. In the last two lines, the gateway uses the chip’s translated stamp when it pushes into LSL. That keeps the hard-won microseconds. If it left the timestamp blank, LSL would stamp at push time and the arrival jitter would come right back.
The failure, as symptom, measurement, fix. The symptom: the EEG and audio line up in a clap test on the bench but drift apart over a 40-minute recording. The measurement: fit the clap-to-spike gap at the start and end; the gap has grown steadily by tens of milliseconds, a slope. The fix: someone applied a start-of-session offset only and never the skew. Apply the full map, or the offline line fit over all the offsets. The next lesson, Prove the Sync, shows how to test it with a flash and a click.
On real hardware: stream 250 samples per second from an nRF52840 DK over BLE in 10-sample packets, log host arrival times, and fit them against sample number. The slope gives you the true sample rate of the sender.
Chapter 9
Keep the numbers, the checklist and the core code, and see where the sync layer sits in a larger system
Every chip counts the ticks of its own crystal, and crystals differ by tens to hundreds of ppm, so the stamps of the same event disagree and the gap grows in a straight line. A sync pulse captured in hardware gives the offset at one instant. A two-way exchange gives the offset over any serial link from four timestamps, with an error bounded by half the measured round trip. The minimum-delay filter keeps the exchanges that can be trusted. A line fit or a Kalman filter turns them into an offset and a skew, so the chip can map any local tick to master time, and keep doing so in holdover when the link drops. Record raw stamps and a sync log, so a later fit can improve the old data.
| What | Number | Why it matters |
|---|---|---|
| ppm to time | 20 ppm = 72 ms per hour; 310 ppm = 1.116 s per hour | Drift is ppm × 10−6 × seconds |
| nRF52840 LFRC | ±500 ppm when calibrated; much looser if not (Nordic product specification) | Two such chips can differ by 1,000 ppm |
| Wrap periods | 32-bit at 84 MHz: 51.1 s; 24-bit RTC at 32,768 Hz: 512 s | Read more often than the wrap, or count wraps |
| RTC tick | 30.517 µs (prescaler 0, Nordic) | Floor for the always-on chip’s timing |
| Offset and delay | θ = ½[(T2−T1)+(T3−T4)]; δ = (T4−T1)−(T3−T2) (RFC 5905) | Error of one exchange is at most δ / 2 |
| NTP clock filter | 8 samples, lowest delay first (RFC 5905) | Same idea as our minimum-delay filter |
| UART byte at 115,200 baud | 86.8 µs (10 bits) | Fixed wire time of a message |
| Slope noise of a fit | σ / √(T2 N (N2−1) / 12) | More points and longer windows sharpen skew |
| Kalman gain, worked example | K0 = 0.0385, skew 30.4 ppm | A trust slider on each measurement |
| Frozen vs held skew, 300 s outage | 93 ms vs 93 µs (this model) | Keep predicting with the skew |
| Overflow of ticks × ppb in int64 | About 8.3 hours at 310,000 ppb | Split into seconds and remainder, or re-anchor |
c/* the client's whole sync loop in one place (Chapters 3 to 7) */ typedef struct { double theta, delta, p00, p01, p11; } kf_t; /* seconds, s/s, covariance */ static void kf_predict(kf_t *k, double dt, double q0, double q1) { k->theta += k->delta * dt; k->p00 += 2 * dt * k->p01 + dt * dt * k->p11 + q0; k->p01 += dt * k->p11; k->p11 += q1; } static void kf_update(kf_t *k, double z, double r) { double s = k->p00 + r, k0 = k->p00 / s, k1 = k->p01 / s, y = z - k->theta; k->theta += k0 * y; k->delta += k1 * y; k->p11 -= k1 * k->p01; k->p01 -= k0 * k->p01; k->p00 -= k0 * k->p00; } void sync_tick(void) { /* every 5 s, in the sync task */ kf_predict(&kf, 5.0, Q0, Q1); if (window_has_good_exchange(&best)) /* minimum-delay pick, Chapter 4 */ kf_update(&kf, best.theta, best.sigma * best.sigma); on_filter_update(&kf, ticks64_ns()); /* Chapter 7: map + sync log */ }
This lesson is the third of four on time. What Time Is It on a Chip built the crystals and counters. Timestamp at the Pin built the hardware stamp. Here we joined chips with a pulse, an exchange and a filter. Prove the Sync checks the result with a flash and a click. Between chips on an Ethernet network the same job uses PTP (IEEE 1588) and gPTP (802.1AS); a later lesson on deterministic Ethernet covers them.
Sabi describes its firmware task in one sentence: build the multi-MCU time-sync layer that lets the team correlate EEG, audio and camera data downstream. The pieces in this lesson are that layer in model form. A real one adds the link management, the power states of the always-on chip, and the tests that prove the budget.
time_correction(), proc_clocksync, proc_dejitter, XDF line fit). labstreaminglayer.readthedocs.ioTIMx_CCRy) and the Arm Cortex-M4 DWT cycle counter: figures here are from the part’s reference manual and should be re-checked for your exact part.Now press Teach and explain the whole layer from memory: why crystals differ, what a pulse and an exchange each measure, why the smallest delay wins, how a line fit and a Kalman filter differ, and what holdover does. Then go back to the instrument at the top, switch between the three methods, and say which error each one removes.