A radio drops packets and never tells you. Number every packet, stamp every sample from a clock you trust, and you can rebuild the exact timeline of a brain recording.
Send eight channels of EEG from a Cortex-M board to a laptop over Bluetooth Low Energy or Wi-Fi, and learn how counters, resends and clock offsets keep every sample at its true time.
Raise the loss slider, then switch the receiver from Arrival order to Counters to Counters + resend. Watch where the last sample lands on the timeline. Then we build each piece from zero: the packet, the counter, the link, the resend, the clock and the offset.
You need to know that a byte is 8 bits and that a radio can lose data. We build the rest from zero.
Built from primary sources: the Lab Streaming Layer time synchronization page, the TI ADS1299 datasheet, Memfault’s BLE throughput primer and the OpenBCI Cyton data format. It follows store-and-forward sync and syncing many MCUs. The radio and the clocks here are models, not real silicon.
A model, not a real radio. The board sends 100 packets of 10 samples each: 250 samples per second for 4 seconds. Each packet is lost at random with the chance you set, from a fixed seed. Resend gives a lost packet up to three more tries.
Chapter 0
See how a recording can look perfect, arrive complete, and still put every sample at the wrong time
A student wears a soft headband with eight electrodes. A small board on the band reads the tiny voltages that her brain makes on her scalp. It sends them by Bluetooth to a laptop. Every five seconds, a screen flashes, and the laptop writes down the time of the flash.
Later she opens the recording. The brain response to each flash should appear 300 milliseconds after it. Instead it appears at 280 ms, then 240 ms, then 190 ms. The response drifts earlier with every flash. Nothing crashed. The file is full. Yet the recording lies.
This lesson is about that lie. It has a small number of causes, and each one has a cheap cure that lives in firmware. If you learn the causes, you can build a stream that tells the truth even when the radio does not.
EEG (electroencephalography) means measuring the electrical activity of the brain through the skin. The voltages are tiny, a few microvolts. The earlier lessons (the microvolt signal chain and acquisition firmware) show how a chip turns them into numbers.
A sample is one reading of all eight channels at one instant. The chip we use as the model, the TI ADS1299, makes 250 samples per second at its slowest setting. Each channel is a 24-bit number, so one sample is 8 × 3 = 24 bytes of data. The datasheet frame also carries 24 status bits, so the chip hands over 216 bits, or 27 bytes, every 4 ms.
A packet is a small bundle of bytes sent as one unit. A stream is a long run of packets that belong together. A timestamp is a number that says when a sample was taken. A timeline is the list of all samples, each at its true time.
A bit is one switch that is on or off. A byte is 8 bits. A 24-bit number has 224 = 16,777,216 possible values. EEG voltages go both up and down, so one bit says the sign, and the range runs from −8,388,608 to +8,388,607. The OpenBCI Cyton page gives the size of one step as 4.5 V divided by the gain and by 8,388,607. At a gain of 24 that is 0.02235 µV per step, so the bytes on the air are counts, and the laptop turns them into volts.
Every chip here runs from a clock: a crystal that vibrates at a steady rate, and a counter that adds one at each tick. The ADS1299 datasheet specifies its 250 samples per second at a clock of 2.048 MHz, so it makes one sample every 2,048,000 / 250 = 8,192 ticks. If the crystal runs a little slow, every tick lasts a little longer, and every sample comes a little late. We will measure how much in Chapter 5.
Think of a courier who carries numbered envelopes across a city. A good courier service makes three promises. First, if an envelope goes missing, the receiver is told which one. Second, each envelope carries the true time it was written, not the time it arrived. Third, the same trip gives the same result twice.
Those three promises are the lesson. A radio breaks the first one all the time. A cheap clock breaks the second. Sloppy firmware breaks the third. Each chapter repairs one promise. The next device shows the whole trip, so you can see where each break can happen.
Five stages carry the data from skin to file. Pick a stage to see its data rate and the way it can hurt the recording. The red mark shows where damage starts.
Rates are exact for the lesson’s design: 250 samples per second, 27 bytes per chip frame (ADS1299 datasheet, 216 bits), 244 bytes per packet and 25 packets per second. Which stage fails, and how often, depends on your build.
Notice that the rate changes along the trip. The chip makes 6,750 bytes per second. The board keeps the 24 data bytes of each sample and adds a short header to each packet. That makes 6,100 bytes per second on the air. The numbers are small. A phone can carry them many times over. So why does anything go missing?
Three symptoms tell you which promise broke. A step: everything after one moment is early by a fixed amount, which means packets were lost and the receiver did not notice. A slope: the error grows steadily with time, which means a clock runs at the wrong speed. A freeze: the display stops for a moment and then jumps, which means a link or a queue held the data back. Each symptom has its own chapter.
Capacity is not the problem. Timing is. A radio link is shared with Wi-Fi, microwave ovens and other people’s earbuds. The student turns her head, and her body blocks the signal for a moment. The phone is busy and does not read its radio for 100 ms. In each case the board keeps making samples every 4 ms and has nowhere to put them.
The link layer of Bluetooth does check every packet and resend it if no acknowledgement comes back. That is real reliability, and Memfault’s throughput primer says so. The same primer warns that stacks can still drop data above the link layer, so you need a reliability layer of your own. That layer is the topic of this lesson.
We will aim for a strong goal. After a bad trip, the recorder should know which samples are missing, how many, and from when to when. Every sample that did arrive should sit within a few milliseconds of its true time, even after an hour. If the board sent a copy twice, the recorder should keep one. If packets arrive in the wrong order, the recorder should put them right.
The goal has a name in the research world. The Lab Streaming Layer (LSL) is an open system for sending time series between programs and computers while keeping their time stamps aligned. Many EEG labs use it. We borrow its ideas in Chapters 5 to 7 and say clearly what we take from its documentation.
By the end you will size a packet for a given MTU and say what the batch costs in delay. You will pick a counter width from the longest outage you allow. You will size a queue and a ring from numbers, not from hope. You will turn a crystal error in ppm into samples, and measure a clock offset with four stamps. And you will choose between Bluetooth, TCP and UDP for a job, with the delay each one adds when a packet is lost. Every one of these is a short calculation, and every one has a device you can move.
Chapter 1
Fit ten samples and a counter into exactly 244 bytes, and see what the batch costs in delay
Your board has a fresh sample every 4 milliseconds. Each sample is 24 bytes. The simplest plan is to send each one the moment it exists. That plan fails at once, and the reason teaches you what a packet is.
A Bluetooth Low Energy link talks in short turns. Phone and board agree on a connection interval, the time between two meetings. Memfault’s primer gives its range as 7.5 ms to 4 s. At each meeting the two sides swap a few packets and go back to sleep. The shortest gap is 7.5 ms, so one packet per meeting gives at most 1000 / 7.5 = 133 packets per second. Sending one sample at a time needs 250.
So we batch. We wait for several samples, put them in one packet, and send them together. The price is delay: the first sample in a batch waits for the others. The skill is to pick a batch that fits the packet size and keeps the delay small.
Data sent from board to phone usually travels as a GATT notification. GATT is the way Bluetooth Low Energy organises data into named values. A notification is the board saying “this value changed, here is the new one” without waiting for a reply. Memfault notes that notifications are the better choice from server to client, because an indication needs a confirmation before the next message.
The size limit comes from the ATT_MTU, the largest message the attribute layer will carry. Its default is 23 bytes. A notification spends 3 of those bytes on its own header, so the default leaves 20 bytes for your data. Twenty bytes cannot hold even one 24-byte sample.
Bluetooth 4.2 added an optional data length extension. It raises the link-layer payload from 27 bytes to 251 bytes (Memfault, citing the specification). A 4-byte L2CAP header sits inside those 251 bytes, which leaves an ATT_MTU of 247. Subtract the 3-byte notification header and you have 244 bytes of your own data per notification. Both phone and board must agree to the larger sizes, so firmware asks for them after the connection opens.
Here is our packet. It is a design choice of this lesson, not a standard. Four header bytes come first, then ten samples.
ctypedef struct __attribute__((packed)) { uint16_t seq; // packet counter, wraps at 65,536 uint8_t n; // samples in this packet (10) uint8_t flags; // bit 0: this is a resend uint8_t data[10 * 24]; // 10 samples x 8 channels x 3 bytes, MSB first } eeg_pkt_t; // sizeof = 2 + 1 + 1 + 240 = 244 bytes
Count the bytes: 2 + 1 + 1 + 240 = 244. The packet fills the largest notification with nothing left over. At 250 samples per second it leaves the board 25 times per second, one every 40 ms, so the board sends 25 × 244 = 6,100 bytes per second.
Why keep the samples as raw 24-bit numbers? Because the board should not guess. The OpenBCI Cyton format does the same: each channel is a signed 24-bit value, most significant byte first. The host turns it into volts. If the top bit of the 24-bit number is 1, the host subtracts 224. For example, the bytes FF F8 00 read as 16,775,168, which becomes 16,775,168 − 16,777,216 = −2,048 counts. At a gain of 24 the Cyton page gives 0.02235 µV per count, so that sample is about −45.8 µV.
Now try the trade yourself. Change the batch size and the negotiated MTU, and watch which packets fit.
The bar is one notification. Purple is the 4-byte header, blue is sample data, the line is the limit. Pick an MTU, then slide the batch size. Red means it does not fit.
Byte counts are exact arithmetic: the payload limit is ATT_MTU minus 3, a sample is 8 channels of 3 bytes, the header is 4 bytes. MTU 185 is the value Memfault reports for most iOS devices from iOS 10. Delay counts only the wait for the batch to fill, not the radio.
Slide to 1 sample with the default MTU. The packet is 28 bytes and the limit is 20, so it does not fit. Slide to the extended MTU and set 10 samples: the bar ends exactly at the line. Add an eleventh sample and it turns red. With the phone MTU of 185 the limit is 182, which holds 7 samples (4 + 168 = 172 bytes), so your design must adapt to whatever MTU the phone grants.
One more choice sits in the layout. The chip’s frame has 24 status bits that report, among other things, which electrodes lost contact (the datasheet builds them from the lead-off bits and four general-purpose pins). Keeping all three status bytes would make a sample 27 bytes. Nine of them plus the header is 247 bytes, three over the limit, so you would send 8 samples per packet (220 bytes) and waste 24 bytes. We instead keep the packet tight and summarise the status of the whole packet in the flags byte. The lesson on acquisition firmware shows how the status bits are read.
The radio pays for each packet too. Memfault budgets 2,500 microseconds of air time for a full 251-byte exchange on the 1 Mbps radio, including the acknowledgement. Our 25 packets per second then use about 25 × 2.5 ms = 62.5 ms of every second, a duty cycle near 6 percent. Half-size packets at twice the rate would use more, because each exchange has fixed costs besides the bytes. The packet that fills the notification is the cheapest per byte.
The first sample in a packet waits for nine more, 9 × 4 = 36 ms, before the packet can even leave. The last one waits no time at all. On average a sample waits about 18 ms. For a recording that is nothing. For a brain-computer interface that reacts to the signal, it is part of the delay budget, and the real-time closed-loop lesson shows why that budget matters.
There is a second cost, in the other direction. A smaller batch means more packets. More packets mean more radio meetings and more energy. The coin-cell lesson (the coin-cell year) shows what that does to battery life. The batch of ten is a middle choice: it fills one packet and keeps the delay under 40 ms.
Chapter 2
Add a counter so the receiver can name the missing packets, and learn why a small counter can hide a big loss
You receive packets numbered 40, 41, 42, 44. You do not need to be told that packet 43 is missing. You see it. A counter turns a silent loss into a visible hole, and that is the whole idea of this chapter.
Think of a book with page numbers. If you turn from page 42 to page 44, you know a page is gone. Without page numbers you would read on and never notice. Our packets carry a page number in their first two bytes, the sequence number. The board adds one for every packet it makes, whether or not the packet gets through.
The receiver remembers the number of the last packet it saw. When a new packet arrives, it asks how far ahead the new number is. If the new number is exactly one more, nothing is lost. If it is two or more ahead, the packets in between are missing.
The “mod” part is there because counters wrap. A wraparound is the jump from the largest value back to zero, like a car odometer rolling over. With a 16-bit counter the numbers go 65,534, 65,535, 0, 1. The formula handles the jump: from 65,535 to 0 gives (0 − 65,535 − 1) mod 65,536 = 0 missing. Good.
Worked example. The last packet was 200 and the next one is 203, with an 8-bit counter. Missing = (203 − 200 − 1) mod 256 = 2. Packets 201 and 202 are gone, and each carried 10 samples, so 20 samples or 80 ms of brain signal are missing.
Here is the catch. The formula only knows the answer up to a multiple of 2b. An 8-bit counter has 256 values. If exactly 256 packets vanish, the next number is the same one you were expecting, and the formula reports 0 missing. The loss is invisible.
How long does that take? At 25 packets per second, 256 packets last 256 × 40 ms = 10.24 s. An outage that long is not rare. A student who walks to the next room can cause it. A 16-bit packet counter does not have this problem for a long time: 65,536 packets last 2,621 s, or 43.7 minutes.
The counter can also count samples instead of packets. That sounds finer, yet it is worse for a small counter. A sample counter that jumps by 10 for each packet wraps at 256 samples, which is 1.024 s. Each lost packet adds 10, so 128 lost packets add 1,280 = 5 × 256, and the counter reads as if nothing happened. That is 5.12 seconds hidden. Try it below.
The ring is every value the counter can hold. The purple mark is the last packet you saw. The yellow mark is the next one to arrive. The arc between them is the loss the receiver reports. Slide the loss, then press Find the blind spot.
Exact arithmetic. The board adds 10 to the sample counter per packet and 1 to the packet counters. Each lost packet is 10 samples and 40 ms. The last seen value is 130 for the sample counter and 200 for the packet counters.
With the 8-bit sample counter, 128 lost packets read as zero missing. With the 8-bit packet counter, the blind spot moves out to 256. With the 16-bit counter, nothing on this slider can hide. The ring makes the idea plain: the receiver only sees where the counter landed, not how many laps it ran.
Here is the unwrapping rule at work. The last accepted packet has unwrapped index 65,535. A packet arrives with sequence number 2. The difference (2 − 65,535) mod 65,536 is 3, so its index is 65,538, and packets 65,536 and 65,537 are missing. Later a packet arrives with sequence number 0 while the newest index is 65,538. The difference (0 − 65,538) mod 65,536 is 65,534, which is more than half the range, so we read it as −2: this is a late packet for index 65,536, and it goes into its old slot. The same two lines of arithmetic handle gaps, copies and late arrivals across the wrap.
Choose the width from a number. Say the longest outage you allow before you stop the recording is 60 s. That is 60 × 25 = 1,500 packets. An 8-bit counter laps at 256 packets, so it fails. A 16-bit counter laps at 65,536 packets, 2,621 s, so it holds with a wide margin. The second clue works the same way. If the counter moved by one packet but 5.12 s passed on the laptop’s clock, then 5.12 / 0.04 = 128 packets of time went by, and 128 does not match 1. The mismatch exposes the hidden lap.
There are three cheap fixes. First, use a wide counter. Two bytes cost 2 of the 244 and give 43 minutes of safety. Second, add a second clue. If the receiver also notes when each packet arrived, it can see that 5 seconds passed while the counter moved by 10. The sample count and the arrival time disagree, and that flags the hidden lap. Third, make the board raise a flag after a long link outage, so a reconnect always starts a new segment.
The receiver must also handle packets that arrive twice or out of order. A simple rule works. Compute the difference as a signed number. If it is between 1 and half the counter range, the packet is new. If it is 0, it is a copy; drop it. If it is a large negative, it is late; place it in its old slot.
Last, the receiver should keep an unwrapped counter: a 64-bit number that adds a full lap each time the small counter rolls over. All later maths, such as sample times, uses the unwrapped value. The small counter on the air is only a convenient way to send the low bits.
Chapter 3
Find the buffer that fills when the radio is slow, and learn why a drop there must still leave a hole in the counter
The student steps behind a thick door. For two seconds the radio link is blocked. The board does not know. It keeps reading the chip every 4 ms and keeps building a packet every 40 ms. Where do those packets go?
They wait in a queue, a line of packets that leave in the order they came. The Bluetooth stack on the board holds a small number of buffers. Your code hands it a packet. The stack sends the packet at the next connection event. If the line is full, your packet has nowhere to go.
Bluetooth Low Energy is not careless. Memfault’s primer states that the link layer is reliable: every packet must be acknowledged, and the sender repeats a packet that is not. This covers a bad moment on the air. A packet that gets garbled is sent again at the next chance.
That repeat costs time, not data. So a bad patch on the air shows up as a longer wait, and the wait shows up as a longer queue. The loss happens above the link layer, when the queue is full, or when the stack on the phone drops what it cannot handle. The primer says plainly that stacks can drop data above the link layer, and that is why we add our own counters.
Here is one connection event, step by step. The two radios wake at the agreed moment. The phone sends a packet, possibly empty. The board answers with one packet from its queue, if it has one. Each side checks the other’s packet and acknowledges it. If more data waits and there is time, they swap another pair. Then both radios sleep until the next event. The board’s code does not run any of this directly; the stack does it, and your code only fills the queue.
Two numbers decide whether the queue stays short. Production is 25 packets per second, set by the chip. Capacity is how many packets the link can carry. At each connection event the two sides can swap some number of packets, and events come once per connection interval. So:
capacity = packets per event × (1000 / connection interval in ms)
Worked example. The interval is 50 ms and the stack sends 1 packet per event. Capacity = 1 × (1000 / 50) = 20 packets per second. Production is 25. The queue grows by 5 packets every second. A queue of 32 buffers is full after 32 / 5 = 6.4 s, and from then on 5 packets per second are dropped. The link is not bad. It is just too slow for this load.
Now allow 2 packets per event. Capacity is 40 per second, which is 15 spare. The queue empties after each short stall. Memfault reports that some older stacks carry only one packet per event, and that iOS devices from iOS 10 support 7 per interval. So you cannot assume the number. You must measure it on the phone you ship for.
The yellow line is how many packets wait in the board’s queue. The shaded band is a 2 s block of the radio at 4 s. Red ticks are packets that found the queue full. Change the interval, the packets per event and the queue size.
A model. The board builds a packet every 40 ms. At every connection event the link takes up to the chosen number of packets from the queue. A packet that arrives to a full queue is dropped. The block stops all events from 4.0 s to 6.0 s. A real stack has its own buffer count; look it up for your SDK.
Leave the interval at 30 ms with 2 packets per event: capacity is about 67 per second, and a 2 s block stacks up 50 packets. A queue of 32 overflows during the block, 19 packets are dropped, and then the queue drains in a fraction of a second. Raise the queue to 64 and nothing is dropped. Then set 100 ms with 2 packets per event: capacity is 20 per second, and the queue never recovers.
Now the key point. When the queue is full, your code must drop a packet. It can drop the oldest or the newest. Both are fine for the stream. What matters is where you assign the sequence number.
Suppose you assign it when you send the packet to the radio. A dropped packet never gets a number. The next packet that does leave gets the next number, and the receiver sees a smooth count. The loss is silent, which is the worst kind.
Now suppose you assign the number when you build the packet, before it enters the queue. A dropped packet still used a number. The receiver sees the jump. Assign the sequence number at creation, never at transmission. That one rule makes every drop above the radio visible.
The symptom of an overfull queue is a recording with holes at regular intervals, or one long hole after a stall. The measurement is the count of failed send calls and the longest time any packet waited, which the device above reports. If the failed calls rise when the interval grows, capacity is the cause. If they rise only during short stalls, queue size is the cause.
Choose the settings by the ratio, not by either number alone. Capacity depends on packets per event divided by the interval. Two packets every 30 ms, one packet every 15 ms and three packets every 45 ms all give 66.7 packets per second. They differ in energy: the 15 ms choice wakes the radio 67 times per second, the 45 ms choice only 22. When the phone allows several packets per event, the longer interval is cheaper in battery for the same capacity, which is the trade that the coin-cell lesson measures.
First, ask for a connection interval and packet count that give at least twice the production rate in capacity. Second, give the queue enough room for your longest expected stall: a stall of 2 s needs 50 packets of 244 bytes, which is 12,200 bytes of RAM. Third, if outages can be longer, move the extra storage to a larger buffer or to flash, as the next chapter and the flash lesson show.
Chapter 4
Keep the last packets in a ring buffer, let the receiver name what is missing, and learn the limit that decides what you can win back
The student walks back into the room after 20 seconds. The link comes up. The laptop now knows, thanks to the counters, that 500 packets are missing. Can the board give them back?
It can, if it kept them. A counter says what is missing. A resend gets it back. This chapter builds the resend and finds the number that limits it.
There are three honest answers to a loss. The first is to accept it: mark the gap and move on. A live display does this. The second is to ask again while the board still holds the packets in RAM. The third is store and forward: write every packet to flash and send it later, as the store-and-forward lesson builds. This chapter covers the second, and the choice among the three at the end.
A ring buffer is a fixed set of K slots used in a circle. The newest packet goes into slot (seq mod K). When the circle is full, the newest packet overwrites the oldest. The board never stops and never grows. At any time, the ring holds the last K packets.
The receiver sends a short message on a second characteristic: “I am missing packets from a to b.” The board looks up each number. If the packet is still in its slot, the board sends it again with the resend flag set. If the slot has been overwritten, the board answers “gone” and the receiver marks that gap as permanent.
c#define K 256 static eeg_pkt_t ring[K]; // 256 x 244 B = 62,464 bytes of RAM static uint32_t next_seq; // unwrapped; the wire carries the low 16 bits void on_packet_built(eeg_pkt_t *p) { p->seq = (uint16_t)next_seq; // number at creation, before any queue ring[next_seq % K] = *p; next_seq++; try_notify(p); // may fail; the ring still has it } void on_nack(uint32_t a, uint32_t b) { // receiver: send me a..b again for (uint32_t s = a; s <= b; s++) { if (next_seq - s > K) { send_gone(s); continue; } // overwritten eeg_pkt_t r = ring[s % K]; r.flags |= 1; // bit 0 = resend queue_after_live(&r); } }
The request itself is small. We use seven bytes: one opcode byte, a 32-bit first sequence number, and a 16-bit count. The board does not trust the host’s numbers blindly. It checks that the range lies below the newest packet it has built, and it limits how many packets it replays at once, so a buggy host cannot starve the live stream.
Two numbers set the limit. The first is the ring size. A ring of K packets holds K × 40 ms of signal. With K = 256 that is 10.24 s, and it costs 256 × 244 = 62,464 bytes of RAM. An outage longer than that loses its oldest part for good, because the ring only keeps the newest packets.
The second number is less obvious. While the board replays old packets, it still makes new ones at 25 per second, and they keep overwriting the ring. The replay must run faster than the ring is being erased. The replay uses the spare capacity: link capacity minus the 25 packets per second of live data. If the spare is less than 25 per second, the oldest packets vanish as fast as you send them, and you recover almost nothing.
Worked example with a ring of 256 and an outage of 10 s. That is 250 packets, which all fit. The link carries 66 packets per second, so spare = 66 − 25 = 41 per second. The replay takes 250 / 41 = 6.1 s, and every packet wins. Now a 20 s outage: 500 packets, of which 244 are older than the ring and gone. Of the other 256, the replay at 41 per second recovers 254 and loses 2 to overwriting. With a link of 50 per second the spare is 25, equal to production, and the replay recovers nothing at all. Try these numbers.
Each thin line is one lost packet, oldest on the left. Green was recovered. Red is gone for good. Change the outage, the ring size and the link capacity.
A model with one rule set: the board replays oldest first at (capacity minus 25) packets per second while live packets keep overwriting the ring. A packet survives if it is sent before 25 per second of production reaches its slot. Ring sizes are packets of 244 bytes; the 1,024-packet ring is more RAM than many small parts have, which is why long outages move to flash.
Set the ring to 64 and the outage to 20 s. The ring keeps only 2.56 s, so 436 of 500 packets are gone. Set the ring to 1,024 and the outage to 30 s: all 750 packets are recovered, but the replay takes 750 / 41 = 18 s, and the 1,024-packet ring needs 249,856 bytes of RAM. The pattern is plain: RAM buys seconds, and spare capacity buys speed.
The third policy needs storage, so do the sum. An hour of the stream is 6,100 × 3,600 = 21,960,000 bytes, about 22 MB. Eight hours is about 176 MB. That is far beyond any RAM ring on a small part, and it is why a long-outage design writes packets to flash first and sends them from there, with the same counters and the same NACK. The ring we built is the fast, small version of that design.
Ask what the stream is for. A live display for a coach can accept gaps; resending old data wastes the radio on numbers nobody watches. A research recording cannot accept gaps, so it needs the resend and, for long outages, storage in flash. A brain-computer interface that moves a cursor needs fresh data first and old data later, or never. Each use picks a different row of the table in Chapter 9.
Chapter 5
Stamp samples from their index, not from the moment they arrive, and learn how a tiny clock error grows into whole samples
Your laptop receives a packet and looks at its watch. It writes 12:00:03.417 next to the ten samples inside. The next packet arrives and gets 12:00:03.441. Easy: stamp each sample with the time it arrived. This plan feels natural, and it is wrong in a useful way.
Ten samples cover 40 ms, yet they all arrive in one burst. Bluetooth delivers packets at connection events, so a packet can wait for the next event, and the wait changes from packet to packet. The stamps wobble by a good fraction of the connection interval. The samples were evenly spaced when the chip made them, and the arrival times erase that fact.
The chip makes one sample every 4 ms, like a metronome. If you number the samples 0, 1, 2 and so on, the number tells you the time: sample n was taken n × 4 ms after sample 0. The metronome is the chip’s own clock, so the spacing is exact in the board’s time. This is why the counter in Chapter 2 does double duty. It finds the missing packets and it gives every sample its place in time.
So the receiver stamps sample n with t0 + n / fs, where fs is the sample rate and t0 is the time of sample 0. The stamps are smooth, with no wobble. Lost packets leave a hole, but the samples on either side keep their true places. That is the second promise of Chapter 0.
The datasheet of the ADS1299 gives its 250 samples per second at a clock of 2.048 MHz. The sample rate is tied to that clock. A real crystal is never perfect. A ppm (part per million) measures how far off it is. A clock that is 50 ppm slow loses 50 seconds in every million seconds.
Worked example. One hour is 3,600 s. At 50 ppm the clock is off by 3,600 × 50 / 1,000,000 = 0.18 s. That is 0.18 × 250 = 45 samples. After one hour, a receiver that assumes exactly 250 samples per second puts every sample 180 ms too early or too late. A 300 ms brain response now looks like 120 ms. The numbers in the story at the start are of this kind.
The 50 ppm here is an illustrative size, not a claim about one part. Crystal tolerance depends on the part and on temperature, so your board needs its own measurement.
Now we have two stamps, and each is flawed in the opposite way. Arrival time has jitter (a random wobble) but it uses the laptop’s clock and never drifts away from it. The counter has no jitter but it uses the board’s clock and drifts. A good receiver takes the good half of each.
The cure is a straight line. Plot arrival time against sample index. The points lie near a line whose slope is the true time per sample, 1/fs as the laptop sees it. Fit the line by least squares, and the wobble averages out. Then stamp each sample from the line. The LSL documentation describes exactly this for offline work: the import tools fit a line through the clock offsets, and for regularly sampled streams they fit sample index against timestamp and recompute the timestamps to remove jitter. LSL calls that dejittering.
A long baseline makes the slope sharp. Suppose sample 0 arrives at 0.000 s and sample 900,000 arrives at 3,600.180 s, each stamp good to ±20 ms. The slope is 3,600.180 / 900,000 per sample, so the true rate is 250 / 1.00005 = 249.9875 samples per second. The two 20 ms errors move the rate by about 0.04 / 3,600 = 11 ppm. After a minute the same error would be 0.04 / 60 = 670 ppm. More time gives a better fit.
The picture shows how wrong each stamp is during one hour. Orange dots are arrival stamps. The purple line is the counter at exactly 250 per second. The green line is the counter with a fitted rate. Turn up the crystal error and the jitter.
A model. One packet every 10 s is plotted (360 in the hour). Arrival error is random, evenly spread over the jitter width, with the fixed part of the delay removed; Chapter 6 shows how to measure that fixed part. The fitted line is a real least-squares fit of arrival time against sample index across all 360 points, recomputed whenever you move a slider.
At 50 ppm and 30 ms of jitter, the purple line climbs to 180 ms in the hour. The dots stay within 15 ms of zero, but they are noisy; no single dot is good enough. The green line stays near zero, with an error under one millisecond, because 360 dots average out. Set the crystal error to 0 and the purple line is as good as the green one. Set the jitter to 60 and the green line still holds, which is the point of fitting.
Firmware can improve the arrival half. A board with a hardware timer can stamp its own packets with its own count, and an input-capture pin can stamp an outside event to a microsecond, as the timestamp-at-the-pin lesson shows. The next chapter turns the board’s own clock reading into laptop time.
Chapter 6
Measure the offset between two clocks with a four-stamp exchange, as the Lab Streaming Layer does, and see what no software can fix
Two people stand in different rooms. Each has a wristwatch. You want to know how far apart the two watches are. You shout “now!” and your friend writes down her time when she hears it. The sound takes time to cross the hall, so her number is a little late, and you do not know how late.
That is the problem of this chapter. Chapter 5 gave every sample a place on the board’s own timeline. The laptop has a different timeline. We need the clock offset: how far the board’s watch is ahead of the laptop’s. The messenger in between is a radio, and the radio takes an unknown time.
The trick is to send a message there and a reply back, and to write down four times. The laptop sends a request and notes its own clock, T0. The board receives it and notes its clock, T1. The board sends a reply and notes T2. The laptop gets the reply and notes T3. T0 and T3 are on the laptop’s clock. T1 and T2 are on the board’s.
Take the offset as board minus laptop. Two lines of algebra give an estimate. If both trips took the same time, the difference T1 − T0 is the offset plus one trip, and T2 − T3 is the offset minus one trip. Average them and the trip cancels.
Worked example. The board’s clock is truly 150.000 s ahead. The request takes 12 ms out, the board answers 1 ms later, and the reply takes 30 ms back, because the return path is slower. T0 = 100.000. T1 = 250.012. T2 = 250.013. T3 = 100.043. Then θ = ((250.012 − 100.000) + (250.013 − 100.043)) / 2 = (150.012 + 149.970) / 2 = 149.991 s. The error is −9 ms. The round trip is δ = (100.043 − 100.000) − (250.013 − 250.012) = 0.043 − 0.001 = 0.042 s.
The error is exactly half the difference between the two legs: (12 − 30) / 2 = −9 ms. This is the hard limit of the method. The estimate cannot be wrong by more than half the round trip, here 21 ms. And if the two legs differ for a fixed reason, no amount of averaging removes it. A hardware pulse shared by both clocks can, which is why the lab world also uses a flash or a click, as the verify-offline lesson shows.
The LSL documentation describes this same design. Each sender stamps samples with its lsl_local_clock(), a clock that counts seconds from an arbitrary start, often boot time. It has no link to the time of day. By default LSL does not change your timestamps. Instead, LSL measures the offset between sender and receiver every few seconds, by exchanging short UDP packets in a way the page calls similar to the Network Time Protocol. A recorder reads the latest offset by calling time_correction() on an inlet.
The LabRecorder program saves the raw timestamps and every offset measurement in an XDF file. Offline tools such as pyxdf then fit a straight line through the offsets, assuming a constant drift, and map all timestamps onto the recording computer’s clock. For online use, the inlet flag proc_clocksync adds the latest offset, proc_dejitter smooths timestamps of regularly sampled streams, and proc_ALL turns both on. The page says the smoothing settles within a minute or two. It gives no number for the accuracy, and neither do we.
Our board is not an LSL node. Its link is Bluetooth, not a network. So the laptop runs a small bridge program. The bridge does the four-stamp exchange with the board over two GATT characteristics, then calls push_sample with the corrected stamps. The ideas are LSL’s; the bytes are ours.
One exchange is noisy, because each trip has a random extra delay. Three simple methods use many exchanges. The first just takes the latest one. The second keeps the last ten and uses the one with the smallest round trip, because a short round trip had little room for the legs to differ; this is the standard trick in NTP-style filters. The third fits a line through all the estimates, which also finds the drift. Compare them on a few minutes of exchanges.
Each grey dot is one exchange: how wrong its offset was. The bright line is the method you pick. The dashed red line is the error from slow return paths, which no method can remove. Change the network noise and the asymmetry.
A model, not LSL itself. One exchange every 5 s for 5 minutes. Each leg takes 5 ms plus a random extra with the mean you set; the return leg adds the fixed slowdown. The true offset grows by 50 ppm. A single exchange is wrong by half the difference of its two legs. “Best of 10” is the NTP-style low-delay filter, our choice for this model; the LSL page does not say which filter it uses.
With noise at 12 ms and no asymmetry, the latest exchange is off by about 9 ms rms after the first two minutes. Best-of-10 is steadier, at about 1.4 ms. The line fit begins wild (two points make any line) and then settles near 1.5 ms. Now raise the asymmetry to 20 ms. Every method sinks to a floor near −10 ms, because the error is built into the path. Averaging cannot find a bias that every sample shares.
With the offset in hand, the final stamp of sample n is its board time, taken from the counter as in Chapter 5, minus the offset at that moment. Every ten seconds the board sends one extra small packet that pairs a sample index with its hardware-captured clock reading. That packet is how the board’s sample counter and its clock are tied together. The laptop then holds a line from sample index to laptop time, and the whole stream lands on one timeline. When a second device joins, it gets its own line, and the many-MCU lesson does that work on the board side.
Chapter 7
Run the whole receiver on one damaged recording and see which flashes land at their true time
The student finishes a 20-second test. During it the screen flashed at 3, 8, 13 and 18 seconds. The link dropped some packets at random. At 7 seconds it also died for a while. The crystal on the board runs a little slow. You must now say, for each flash, where it falls in the recording.
This chapter puts every earlier piece into one receiver. First we write down what it does. Then you break the trip in every way we have met, and you switch each defence on and off.
Steps 1 to 3 give the first promise: nothing is missing without a name. Steps 4 to 6 give the second: every sample sits at its true time. The third promise, the same result twice, follows because the receiver uses only the numbers in the packets and a fixed rule.
Take no random loss and a link that dies for 3 seconds at 7 s. Packet 175 is the first packet after 7.0 s, and 75 packets go missing: 750 samples. The flash at 8 s falls inside the outage. The flash at 13 s comes after it.
A receiver with no counters stamps by arrival order. The 750 missing samples never arrive, so every sample after the outage is stamped 750 × 4 ms = 3.000 s too early. The flash at 13 s lands at about 10 s. The flash at 8 s has no sample at all.
A receiver with counters places every packet by its number. The flash at 13 s lands at 13.000 s, and the flash at 8 s is marked missing. Add the resend, and the ring (256 packets, 10.24 s) still holds the outage, so all 75 packets come back and the flash at 8 s lands at 8.000 s. Both claims are exact arithmetic. Check them below.
The top strip is 500 packets over 20 s: blue arrived, red is lost, green was resent. Below it, four flashes. A white tick is the true time of a flash. The coloured mark is where the receiver puts it. Break the trip with the sliders. Switch the defences on one at a time.
A model. Random loss gives each packet three more tries when Resend is on. The outage starts at 7.0 s. Resend recovers outage packets from a 256-packet ring and a link with 41 spare packets per second, so an outage over 10.24 s loses its oldest part for good. Without counters the receiver cannot ask for anything, so Resend and Clock fit need Counters. Clock fit leaves a residual of under 1 ms (values taken from the hour-long fit of Chapter 5, 30 ms jitter).
Start with everything off, the default recording. Flash 1 is 240 ms early, flash 2 is missing, flash 3 is 3.48 s early and flash 4 is 3.80 s early. Turn on Counters: the shifts vanish, every placed flash sits within 1 ms, and flash 2 is marked missing. Turn on Resend: flash 2 returns. The small error left is the 50 ppm drift, 0.15 ms at 3 s and 0.9 ms at 18 s. Over 20 seconds that is tiny. Over an hour it would be 180 ms, as Chapter 5 showed, so the Clock fit matters for long recordings.
Now push the outage to 12 s. The ring keeps 10.24 s, so the oldest 1.76 s of the outage is gone, and the flash at 8 s is gone with it. No defence can restore it, but the receiver says so out loud, which is what the first promise asks for.
The failures in this chapter each leave a different symptom, so you can tell them apart. If every flash after one point is early by the same amount, packets were lost and the receiver stamps by arrival. The measurement is the step in the error, equal to 4 ms times the lost samples. The fix is counters. If the error grows steadily with time, the clock rate is wrong. The measurement is the slope in ppm. The fix is the fitted rate. If a flash is missing, a packet is gone for good. The measurement is the gap length against the ring size. The fix is a longer ring or flash storage.
Check the default recording by hand. Before the flash at 13 s, the model has lost 87 packets, 75 in the outage and 12 at random. That is 87 × 40 ms = 3.480 s. The device shows flash 3 at 3.48 s early with no counters, plus 0.65 ms of drift. The arithmetic and the device agree, which is how you learn to trust the device.
Counters cannot bring a packet back. They only name it. A resend cannot bring back a packet that left the ring, and it needs spare capacity on the link. The clock fit cannot fix a path that is slower one way, and it needs time: a fit over 20 seconds is much poorer than a fit over an hour, as Chapter 5 showed. Each defence moves one error from hidden to named, or from large to small. None of them makes the link good.
That is why the bench test matters. Inject each fault on purpose, in a known amount, and check that the receiver reports it in the same amount. If you skip 75 packets and the report says 75, you can trust it when you cannot see the cause.
Chapter 8
Compare TCP and UDP on a Wi-Fi link, and see why a promise of order turns one lost packet into a pause
You swap the radio. The board now joins the lab Wi-Fi and sends to the laptop over an IP network. The numbers get larger. A Wi-Fi link carries far more than 6,100 bytes per second, and an IP packet is not held to 244 bytes. The old worries seem to go away.
Some do. Some stay. And a new one appears. This chapter sorts them out.
The two common choices are TCP and UDP. UDP sends a datagram and forgets it. Each datagram is its own unit. If one is lost, the others are unaffected, and nobody is told. A UDP datagram on a typical Ethernet or Wi-Fi network can carry up to 1,472 bytes without being split, which is the usual 1,500-byte IP limit less 20 bytes of IP header and 8 of UDP header. So you could put 60 of our samples in one datagram. The batching cost grows, though: 60 samples is 240 ms of waiting.
TCP gives you a connection that looks like a pipe. Bytes go in at one end and come out at the other, in order, with nothing missing. If a segment is lost, TCP sends it again. This sounds like exactly what we have been building by hand. Do we still need counters?
Yes, we do, for three reasons. First, TCP guarantees the bytes you give to the network stack. It knows nothing about the samples your own code dropped before that, when your queue was full (Chapter 3). Second, a TCP connection can die. When the board reconnects, the new connection starts fresh, and the bytes left in the old socket buffers are gone. A counter that survives across connections reveals that. Third, TCP does not stamp anything, so the clock work of Chapters 5 and 6 is still yours.
There is also a price. TCP promises order: the receiving program never sees byte 1,000 before byte 999. If one segment is lost, the segments after it may have arrived, but the stack holds them back until the lost one is repeated. This is head-of-line blocking, like a line of cars stuck behind one that has stalled.
How long is the hold? TCP’s fast retransmit rule (RFC 5681) repeats a segment after three duplicate acknowledgements, which are the hints that later segments arrived while one was missing. In our stream a packet comes every 40 ms, so three more packets take 120 ms to arrive, plus the time for the acknowledgement to travel back and the repeat to travel forward. On a link with a round trip of 100 ms, the lost packet arrives 270 ms after it left instead of 50 ms, and five packets behind it arrive late as well.
Take one packet loss, the sixth packet of the stream, and watch the delay each packet suffers. With TCP, every packet waits for the repeat. With plain UDP, nothing waits and the lost one never comes, but the counter names it. With UDP plus a resend request, the receiver sees the gap the moment the seventh packet arrives and asks right away; the lost packet comes back late, and no other packet waits.
Each bar is one packet and its delay from the board to the program. Blue is on time. Yellow waited behind a lost packet. Red never arrived. Green is a packet won back. Pick a transport, then change the round trip.
A simplified model, not a TCP simulator. Packets leave every 40 ms. The network adds half the round trip each way. Packet 6 (index 5) is lost. TCP repeats it after three later packets raise duplicate acknowledgements (RFC 5681 fast retransmit) and holds back all later data until the repeat arrives. The model ignores timeouts, window size and Nagle’s algorithm.
At a 100 ms round trip, TCP delays six packets. The lost packet arrives 270 ms after it left, and the next ones wait 230, 190, 150, 110 and 70 ms. Plain UDP delays none, and shows packet 6 as missing. UDP with a resend gets the packet back after 190 ms and delays no other. Raise the round trip to 300 ms and TCP delays eleven packets, the lost one and ten behind it, with a worst delay of 570 ms, while UDP with resend still delays only the lost packet, by 490 ms.
Wi-Fi also changes the cost of each packet. A UDP datagram adds 28 bytes of IP and UDP headers to our 244, about 11 percent, and the network adds its own framing below that. Sending 25 datagrams per second keeps the batch at 36 ms of wait. Larger datagrams would save a little header but would add delay. The same 16-bit sequence number rides in the first two bytes, so the receiver code from Chapter 9 runs unchanged on either link.
A reconnect shows the same lesson from the other side. Say the board was at packet 5,000 when the Wi-Fi dropped, and it rejoined 3 s later. Its TCP socket is new, and the bytes that were in flight on the old one are gone. The first packet on the new connection carries a number 76 higher than the last one the laptop saw, so 75 packets are missing. The counter names exactly what the connection lost, and the ring or the flash can send it again.
For a recording that nobody watches live, TCP is a good choice. Order and repair come free, and a late arrival costs nothing. Add the counter anyway, to catch the drops your own code made. For a live display or a brain-computer interface that moves a cursor, a pause of several hundred milliseconds is a visible freeze. There, UDP with counters, and a resend only for the record, keeps the live path fresh. The real-time closed-loop lesson explains why a fixed delay is acceptable but a surprise delay is not.
Chapter 9
Keep the numbers, the checklist and the core code, then follow the links onward
A radio loses data and does not say so, and a cheap clock drifts without a sound. The cure has four parts. Number every packet when you build it, so each loss leaves a hole. Keep the last packets in a ring buffer and let the receiver ask for what is missing, if the link has spare capacity. Stamp samples from their index, with the rate fitted from arrival times. Measure the clock offset with a four-stamp exchange, as the Lab Streaming Layer does, and know the floor it cannot cross. Then the recorder can say which samples are missing and put every other sample at its true time.
| Item | Number | Where it comes from |
|---|---|---|
| ADS1299 frame | 216 bits = 27 bytes | 24 status bits + 8 channels × 24 bits (TI datasheet) |
| ADS1299 data rate | 250 to 16,000 SPS | TI datasheet, at a 2.048 MHz clock |
| One sample kept | 24 bytes | 8 channels × 3 bytes, signed, most significant byte first |
| Volts per count | 0.02235 µV at gain 24 | OpenBCI Cyton page: 4.5 / gain / (223 − 1) |
| Default ATT_MTU | 23 bytes, 20 of data | Memfault primer; a notification header takes 3 |
| Link-layer payload | 27 bytes, or 251 with the length extension | Memfault primer (Bluetooth 4.2) |
| Largest notification | 244 bytes | 251 − 4 (L2CAP) − 3 (ATT header) |
| Our packet | 4 + 240 = 244 bytes | This lesson’s design: 10 samples and a 4-byte header |
| Packet rate and data rate | 25 per s, 40 ms; 6,100 bytes/s (48.8 kbit/s) | 250 SPS ÷ 10 samples; 25 × 244 |
| Connection interval | 7.5 ms to 4 s | Memfault primer |
| One lap of the counter | 8-bit samples 1.024 s; 8-bit packets 10.24 s; 16-bit packets 2,621 s (43.7 min) | 256 × 4 ms; 256 × 40 ms; 65,536 × 40 ms |
| Crystal error | 50 ppm = 0.18 s per hour = 45 samples | Illustrative size; measure your own part |
| Resend rule | spare = capacity − 25 packets/s, must beat 25 | The ring erases at the production rate |
| Offset from four stamps | θ = ((T1 − T0) + (T2 − T3)) / 2; error at most δ / 2 | NTP-style exchange; LSL measures offsets this way every few seconds |
| LSL names | lsl_local_clock, time_correction, proc_clocksync, proc_dejitter, proc_ALL | LSL time synchronization page |
pythonimport numpy as np class Receiver: def __init__(self): self.last = None # newest unwrapped packet index self.slots = {} # index -> 240 data bytes self.pts = [] # (sample index, arrival time) pairs def unwrap(self, seq16): if self.last is None: return seq16 d = (seq16 - self.last) & 0xFFFF if d >= 0x8000: d -= 0x10000 # negative step: a late packet return self.last + d def feed(self, seq16, data, t_arrive): i = self.unwrap(seq16) if i in self.slots: return [] # a copy: ignore self.slots[i] = data missing = [] if self.last is None or i > self.last: if self.last is not None and i > self.last + 1: missing = list(range(self.last + 1, i)) # send these to the board as a NACK self.last = i self.pts.append((i * 10, t_arrive)) return missing def clock(self): # t = a + b * n, fitted over all arrivals n, t = zip(*self.pts) b, a = np.polyfit(n, t, 1) return lambda sample_index: a + b * sample_index
That is about thirty lines. Add the board side from Chapter 4 (on_nack) and the four-stamp exchange from Chapter 6, and you have the receiver we built, ready to test on the bench.
This lesson is the fourth in the biopotential track. Lesson 1 made the microvolts into numbers, lesson 2 read them from the chip with a counter and loss detection, and lesson 3 cleaned them. Here the numbers leave the board. Lesson 5 moves part of the decoding onto the board and adds the rules of medical firmware.
The Lab Streaming Layer time synchronization page (the clock, offsets, XDF, dejitter and the processing flags). The TI ADS1299 datasheet (the 216-bit frame, the status word and the data rates). Memfault Interrupt, “A Practical Guide to BLE Throughput” (MTU, data length, connection intervals, link-layer acknowledgements). The OpenBCI Cyton data format page (24-bit signed values and the volts-per-count formula). RFC 5681 for TCP fast retransmit. The packet layout, the ring sizes and the toy numbers are this lesson’s own designs, marked as models where they appear.
Now press Present or Teach and explain, from memory, how a recorder finds a lost packet and puts the next flash at its true time. Then go back to the lossy-link instrument at the top and break it on purpose.