Acquisition Firmware

An EEG chip hands your microcontroller 250 frames every second. Lose one and nothing complains: the recording just gets 4 ms shorter. A counter byte is how you find out.

Learn how firmware catches every sample from a biopotential chip: the data-ready pin, the SPI read, the DMA transfer, the status bits, and the counter that exposes a loss.

Press Lose a sample a few times with the counter off, and watch the pulse slide earlier with no warning. Then switch the counter on. Then we build, piece by piece, everything that makes that gap visible.

You need a rough idea of what a microcontroller and an interrupt are, and a first look at SPI. We build the rest from zero, and the previous lesson covers what happens before the chip.

Built from the TI ADS1299 datasheet (SBAS499C) and the OpenBCI Cyton data format. Part of the series Firmware from Zero to Expertise. Every device on this page is a model that runs in your browser, not real silicon.

Lose a sample on purpose

Toy data: a slow wave with one sharp pulse, 48 samples at the ADS1299 rate of 250 samples per second (4 ms each). The rate is the chip’s; the wave and the lost positions are illustrative.

Chapter 0

The Sample You Never Saw Missing

See how one lost sample hides inside a recording that looks perfect

Maya studies how a brain answers a flash of light. She wears an EEG cap, a set of electrodes that pick up the tiny voltages on the scalp. A small board reads 8 electrodes 250 times every second and sends the numbers to her laptop. She flashes the screen once a minute and looks for the brain’s response about 100 ms later.

After a 10-minute session the file looks perfect. No error appeared. Every row holds 8 numbers. The plot looks like EEG. But the board dropped 15 frames along the way, and nothing told her. The responses she measured sit 60 ms off from where she thinks they are.

Four words you need

A sample is one number: the voltage of one electrode at one instant. A frame is everything the chip reports for one instant: all 8 samples plus a short status word. At 250 frames per second, a new frame is ready every 4 ms.

Firmware is the program that lives inside the microcontroller (the small chip that runs the board). Its job here is simple to say and hard to do: grab every frame, on time, and pass it on. Think of a conveyor belt that drops a parcel every 4 ms. The worker must catch each one. If a parcel falls, the belt does not stop and does not wait.

Two tools help the worker. An interrupt is a pin that taps the processor on the shoulder and says “now”, so the program does not have to keep checking. DMA (direct memory access) is a helper circuit that copies bytes from a peripheral into memory while the processor does other things. Chapters 2 to 4 build both into a design. The lesson on interrupts and DMA goes deeper, and the one on buses covers SPI wire by wire.

Why the loss is silent

Most recording software gives each row a time from its row number: row 0 is 0 ms, row 1 is 4 ms, row 2 is 8 ms. That is a fair guess when no frame goes missing. When one frame is lost, there is simply no row for it. Every later row then gets a time that is 4 ms too early.

One lost frame gives a 4 ms error. That sounds small. But losses add up, and they never come back. Try the numbers below. The loss rate is a guess you can change, because it depends on how busy the firmware is.

Watch a silent loss add up

The line shows how far every row’s time is off after the minutes you choose. The dashed line is 100 ms, the delay Maya wants to measure. Drag either slider.

10
1

Illustrative loss rates. The frame rate is real: 250 frames per second is the ADS1299 default, so one frame is 4 ms and a minute holds 15,000 frames.

At 1 loss per 10,000 frames, a 10-minute recording holds 150,000 frames and loses 15. The timing error at the end is 15 × 4 ms = 60 ms. At 3 per 10,000 over an hour, the error is more than a second. Nothing in the file shows it.

The fix has two parts. First, make the firmware lose fewer frames: that is the design of Chapters 2 to 4 and 7. Second, make any loss visible and countable: that is the counter of Chapter 6. A system with a few lost frames that it knows about is far better than one with fewer that it cannot see.

The road

  1. One frame: 216 bits, a status word and eight signed numbers.
  2. DRDY and the time budget: how fast SCLK must run.
  3. Reading over SPI: mode, chip select, the keep-out zone.
  4. Interrupt plus DMA: how the bytes reach memory without the CPU.
  5. Status and lead-off: which electrode came loose.
  6. Counter and loss: lose a sample, catch it.
  7. Ring buffer: size it, and see an overrun.
  8. Host packets: header, counter, checksum, bytes per second.
  9. Field guide: numbers, checklist, code, links onward.
A board loses one frame in a 250 frames-per-second stream. The host stamps rows by row number. What happens to the times of all later rows?

Chapter 1

One Frame: 27 Bytes From the Chip

Read 216 bits as a status word plus eight signed 24-bit numbers, and turn them into microvolts

Put a logic analyzer on the chip’s data pin the moment a new reading is ready. You see exactly 216 clock pulses, then silence for the rest of the 4 ms. Those 216 bits are one frame. The firmware’s whole job is to catch that frame, every time, and understand what is in it.

We use the TI ADS1299, an 8-channel, 24-bit converter built for EEG. A frame has a status word first, then one reading for each of the eight channels. Each part is 24 bits, which is 3 bytes. That makes 9 parts of 3 bytes: 27 bytes in all.

The status word and the channels

The status word is the first 24 bits. The datasheet gives its layout: the four bits 1100, then the 8 bits of a register called LOFF_STATP, then 8 bits of LOFF_STATN, then 4 bits copied from the chip’s general-purpose pins. That is 4 + 8 + 8 + 4 = 24 bits. Chapter 5 explains the lead-off bits. For now, note that the first four bits never change. They are a marker you can check.

After the status word come eight channel readings, channel 1 first, each most significant bit first. A reading is a signed 24-bit integer in two’s complement. Two’s complement is how computers store negative whole numbers: the top bit means “negative”. The code 000000 is zero. 000001 is the smallest positive step. FFFFFF is one step below zero. 7FFFFF is the largest positive code and 800000 the most negative. The chip stops at those two codes when the input is too big.

From counts to microvolts

A code is a count of tiny steps. The size of one step, the LSB (least significant bit), depends on two things you choose: the reference voltage VREF (4.5 V on this chip) and the gain of the input amplifier (1, 2, 4, 6, 8, 12 or 24).

1 LSB
The voltage change that moves the output code by one. It is the smallest step you can see.
2 × VREF / Gain
The total input span, from the most negative to the most positive voltage. At gain 24 it is 2 × 4.5 / 24 = 0.375 V.
224
The number of codes a 24-bit word can hold: 16,777,216.

0.375 V / 16,777,216 = 22.35 nV per count (gain 24, VREF = 4.5 V)

A worked frame makes this concrete. Say channel 1 sends the three bytes 00 11 94. Join them: 0x001194. The top bit is 0, so it is positive. In decimal, 0x1194 is 4 × 1,024 + 1 × 256 + 9 × 16 + 4 = 4,500. Multiply by 22.35 nV: 4,500 × 0.02235 µV = 100.6 µV. That is a normal size for an EEG signal.

Now channel 2 sends FF EE 6C. Join: 0xFFEE6C. The top bit is 1, so it is negative. To find the size, take 0x1000000 minus 0xFFEE6C, which is 0x1194 = 4,500. So the reading is −4,500 counts, or −100.6 µV. Try these in the device below, and change the gain to see the same voltage use different codes.

Decode a frame

The 27 bytes are what arrives on the wire: three purple status bytes, then eight channels of three orange bytes. Pick a frame and a gain, then pick a channel to see its arithmetic.

24
1

The formula, the status layout, the code range and the gain list are from the ADS1299 datasheet (sections 9.4.4.2 and 9.5.1). The voltages in each frame are illustrative.

Notice the Railed frame. When a channel is pushed past full scale, its code sticks at 7FFFFF. It tells you only “at least this big”. In the Electrode off frame, one status bit also lights up. Chapter 5 shows why that bit matters more than the value.

The same thing in C

Firmware turns three bytes into a signed number with one trick: flip the top bit, then subtract it. It avoids relying on how the compiler shifts negative numbers.

c/* one frame as it arrives: 3 status bytes + 8 channels x 3 bytes */
typedef struct { uint8_t raw[27]; } frame_t;

static inline int32_t s24(const uint8_t *p) {
    int32_t v = ((int32_t)p[0] << 16) | (p[1] << 8) | p[2];
    return (v ^ 0x800000) - 0x800000;   /* 0xFFEE6C -> -4500 */
}
static inline float counts_to_uV(int32_t c) { return c * 0.02235f; }  /* gain 24 */
static inline int marker_ok(const frame_t *f) { return (f->raw[0] & 0xF0) == 0xC0; }

Most firmware does not convert to microvolts at all. It keeps the raw counts, which are exact, and sends them on. The host converts later with the gain it knows. That also avoids a floating-point step inside a 4 ms deadline.

When it goes wrong

Symptom. Negative voltages show up as huge positive numbers, around 16.7 million counts. Or every channel looks like its neighbour.

Measure. Print the raw hex of one frame while the inputs are shorted. A reading of FF EE 6C that prints as 16,772,716 means the sign was never extended. If channel 1 looks like it holds the status word, you started reading at byte 0 instead of byte 3.

Fix. Convert with the s24 function above, and index channel n at byte 3 + 3 × (n − 1). Add a unit test with two frames: one with a small positive code and one with FFFFFF. Both bugs then show up before the board does.

Channel 3 sends the bytes FF FF FF. At any gain, what number does it hold?

Chapter 2

DRDY: The Chip Sets the Clock

Work out how fast SCLK must run and how much time you have to read a frame

You do not ask the ADS1299 for a frame. You wait. Inside the chip, a converter measures the electrodes at a steady pace set by a clock. Each time a new frame is complete, the chip pulls one pin low. That pin is called DRDY, short for “data ready”. It is active low: a falling edge means “a frame is waiting”.

Think of a bakery that bakes a loaf every 4 ms and rings a bell. You cannot make it bake faster. You cannot make the loaf wait. You must walk over when the bell rings and take the loaf before the next one comes out.

Where the pace comes from

The pace has three links. A clock signal on the CLK pin runs at fCLK = 2.048 MHz in the datasheet’s setup. The converter’s modulator runs at half that, fMOD = 1.024 MHz. A three-bit field, DR[2:0] in the CONFIG1 register, picks how many modulator cycles make one output: 64, 128, 256, 512, 1,024, 2,048 or 4,096.

The reset value of CONFIG1 is 0x96, and its DR bits read 110. That means fMOD / 4,096 = 1,024,000 / 4,096 = 250 samples per second (SPS). So 250 SPS is the default, and one period, written tDR, is 4 ms. With DR = 000 the chip runs at 16 kSPS and tDR is 62.5 µs.

How fast must SCLK be?

SCLK is the SPI clock your microcontroller drives. It shifts out one bit per tick. A frame needs 216 ticks: 24 for the status word and 24 for each of 8 channels. All 216 must finish before the next frame arrives, with a small gap for the chip’s own housekeeping. The datasheet gives this as Equation 9.

tSCLK
The time of one SCLK tick. A smaller value means a faster clock.
tDR
The time between two DRDY falling edges. This is the whole time you have: 4 ms at 250 SPS.
4 tCLK
Four periods of the chip’s master clock, the quiet time while the chip updates its output register. At 2.048 MHz it is 1.953 µs.
NBITS × NCHANNELS + 24
The bits to shift: 24 × 8 + 24 = 216.

Work it for 500 SPS. tDR is 2,000 µs. Subtract 1.953 µs: 1,998.05 µs. Divide by 216: 9.25 µs per tick, which is about 108 kHz. The datasheet quotes 110 kHz for this case, so the arithmetic agrees. At the default 250 SPS the floor is about 54 kHz. At 16 kSPS it is about 3.57 MHz.

The ceiling is a different limit. The datasheet asks for an SCLK period of at least 50 ns at 2.7 to 3.6 V on the digital supply, which is 20 MHz. So at 250 SPS you have room to spare: 54 kHz to 20 MHz is a range of more than 300 times. Try the budget below.

Fit the read between two bells

Top: two periods of DRDY (orange ticks) and the time your SPI read occupies (teal). Bottom: the SCLK speed you chose against the minimum the datasheet allows (yellow). Pick a data rate and an SCLK speed.

250 SPS
1 MHz

Data rates, the 216-bit frame, the 4 tCLK term and the 50 ns SCLK limit are from the ADS1299 datasheet with fCLK = 2.048 MHz. The read time shown is 216 ticks of SCLK only: real code adds the chip-select setup and the interrupt delay of Chapter 4.

At 250 SPS and 1 MHz, the read takes 216 µs. That is 5.4% of the 4 ms period. The processor is free for the other 94.6%. Raise the data rate to 16 kSPS at the same 1 MHz and the read, still 216 µs, no longer fits in 62.5 µs. The bar turns red. The frame is simply not read in time, and the next one overwrites it.

What happens if you are late

The datasheet describes no queue of frames. The chip holds one frame in its output register. If you have not read it when the next conversion finishes, DRDY goes high for 4 tCLK and falls again to announce the new frame. The old one is gone. No flag is raised. This is the silent loss from Chapter 0, and the counter in Chapter 6 exists to catch it.

A last number matters on start-up. When you raise the START pin, the first DRDY does not come after one period. It comes after the settling time: 32,777 tCLK at 250 SPS, which is 16.0 ms, four periods. Firmware that counts frames from the START edge must not expect a frame at 4 ms.

DR[2:0]RatetDRMinimum SCLK
110 (default)250 SPS4,000 µs54 kHz
101500 SPS2,000 µs108 kHz
1001 kSPS1,000 µs216 kHz
0112 kSPS500 µs434 kHz
0104 kSPS250 µs871 kHz
0018 kSPS125 µs1.76 MHz
00016 kSPS62.5 µs3.57 MHz

When it goes wrong

Symptom. The firmware records cleanly at 250 SPS. At 2 kSPS the file is full of repeated values and holes.

Measure. Put a scope on DRDY and SCLK. Time one read from the first tick to the last, and compare it with the 500 µs between DRDY edges. Peripheral clocks are often divided in powers of two. Say the SPI block runs from 80 MHz and your prescaler is 256: SCLK is 80 / 256 = 312.5 kHz. At 2 kSPS the floor is 434 kHz, so the read takes 216 / 312.5 kHz = 691 µs, longer than the 500 µs period.

Fix. Choose the next prescaler up: 128 gives 625 kHz and a 346 µs read, which fits. Recompute the floor whenever you change the data rate, and add an assert that compares the two at start-up.

At 1 kSPS, what is the slowest SCLK that still reads a full 216-bit frame between two DRDY edges?

Chapter 3

Reading a Frame Over SPI

Pick the SPI mode, hold chip select, and stay out of the four-clock keep-out zone

The bell has rung. DRDY fell. Now you must walk over and take the frame. The walk is a SPI transfer (Serial Peripheral Interface): a short conversation on four wires. Your microcontroller is the controller and drives the clock. The ADS1299 is the peripheral and answers.

The four wires are simple. CS (chip select) is a pin you pull low to say “I am talking to you now”. SCLK is the clock, one tick for every bit. DOUT carries bits from the chip to you. DIN carries bits from you to the chip. It is like reading a book aloud with a metronome: CS is “listen”, SCLK is the beat, and each beat moves one bit.

Which edge to trust

Every SPI link needs an agreement: on which clock edge does the sender change a bit, and on which edge does the receiver look at it? The agreement has two settings. CPOL is the level the clock rests at. CPHA says whether the receiver samples on the first edge of each tick or the second. Together they make four SPI modes.

The ADS1299 datasheet states its choice under the timing diagram: CPOL = 0 and CPHA = 1. The clock rests low. The chip changes DOUT on each rising edge, and it holds the bit steady through the falling edge. So you sample on the falling edge. Its table gives the numbers: DOUT is valid at most 17 ns after the rising edge (at 2.7 to 3.6 V), and stays valid at least 10 ns after the falling edge.

That 17 ns is the key. If you sample on the rising edge, you look at the moment the chip is still changing the bit, and you see the old one. Every bit arrives one position late. Try it below, and watch the first four bits, the 1100 marker, turn into something else.

Pick the sampling edge

The first 16 bits of the status word, as the chip sends them. Teal marks show where your controller looks. Choose a mode and an SCLK speed, then compare the byte you decoded with the byte the chip sent.

4 MHz

The 17 ns and 10 ns figures and CPOL = 0, CPHA = 1 are from the ADS1299 datasheet (sections 7.6, 7.7 and Figure 1). The bits are the first two status bytes of the Electrode off frame from Chapter 1. Your board’s wiring and input delays add to the 17 ns, and this model leaves them out.

Mode 0 samples at the rising edge and gets 0x60 0x40 instead of 0xC0 0x80. The four-bit marker reads 0110, not 1100. A frame check on the marker (Chapter 5) would catch this on the very first frame. The SPI mode is the first thing to check when a bring-up shows garbage that looks almost right.

The rules for chip select

Chip select does more than choose a chip here. The datasheet says CS must be low before the transfer starts and stay low for the whole read. If CS goes high, the chip’s serial port resets. That has a direct cost: a driver that toggles CS after every byte, as some software SPI helpers do, cuts the 27-byte frame into pieces. The chip restarts from the first bit each time.

Three small times matter. After CS falls, wait at least 6 ns before the first SCLK tick (tCSSC, at 2.7 to 3.6 V). After the last tick, wait 4 tCLK, about 2 µs, before raising CS (tSCCS). And leave CS high for at least 2 tCLK between reads (tCSH). A DMA transfer of all 27 bytes with CS held in software meets all three easily.

Streaming mode and the zeros you send

The chip has two ways to deliver data. In RDATAC (read data continuous) mode, each DRDY simply makes a frame available, and you clock it out with no command. It is the power-up default. In RDATA mode, you send a read command for every frame. RDATAC suits a logger whose registers are set once. That is our case.

SPI is full duplex: every tick moves a bit both ways. To receive 27 bytes you must also send 27 bytes. In RDATAC mode, the chip expects DIN to stay low for the whole read, so you send 27 bytes of 0x00. That value is the chip’s no-operation command.

Setup follows a fixed order. The chip wakes in RDATAC, and in that mode only one command works: SDATAC (0x11), stop continuous reads. Send it first. Then write the registers with WREG (0x40 plus the register address). Then raise START, or send the START command (0x08). Then send RDATAC (0x10). Between the bytes of a multi-byte command the chip needs 4 tCLK, 1.95 µs, to decode. At 4 MHz one byte takes 2 µs, so back-to-back bytes already meet that. At 16 MHz they do not, and you must pause.

c/* STM32 HAL (L4 family): SPI mode 1, software CS, MSB first */
hspi1.Init.Mode           = SPI_MODE_MASTER;
hspi1.Init.CLKPolarity    = SPI_POLARITY_LOW;      /* CPOL = 0 */
hspi1.Init.CLKPhase       = SPI_PHASE_2EDGE;       /* CPHA = 1 */
hspi1.Init.NSS            = SPI_NSS_SOFT;          /* we drive CS ourselves */
hspi1.Init.DataSize       = SPI_DATASIZE_8BIT;
hspi1.Init.FirstBit       = SPI_FIRSTBIT_MSB;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32; /* 80 MHz / 32 = 2.5 MHz */

/* bring-up order from the datasheet */
cmd(0x11);                      /* SDATAC: leave RDATAC so commands work */
wreg(0x01, 0x96);              /* CONFIG1: 250 SPS */
cmd(0x08);                      /* START */
cmd(0x10);                      /* RDATAC: frames now follow each DRDY */

The keep-out zone

One more rule, from the RDATAC section. Around each DRDY pulse the datasheet draws a keep-out zone of 4 tCLK (it calls the time tUPDATE), and says: do not read data during this time. The chip is moving the new frame into its output register. If you start clocking inside that zone, you may read half old data and half new. It is a rare bug that appears only when the interrupt is very fast.

A safe habit, which is this lesson’s own design choice and not a datasheet rule: begin the read at least 2 µs after the DRDY edge. Chapter 4 shows that interrupt latency on a Cortex-M often covers part of that gap already.

When it goes wrong

Symptom. The marker check fails on about one frame in a thousand. The rest are perfect.

Measure. Trigger the scope on a marker failure and look at the time between the DRDY edge and the first SCLK tick. On a fast part the interrupt can be quicker than 2 µs. The read then starts inside the 4 tCLK keep-out, while the chip updates its output register.

Fix. Delay the start of the read by about 2 µs, with a short busy-wait or a timer compare. The delay costs almost nothing against a 4 ms period. Keep the marker check on in the shipping firmware, as the alarm that tells you when a fix stops working.

You set the SPI controller to CPHA = 0 and every status byte decodes as 0x60 instead of 0xC0. What is the most likely reason?

Chapter 4

From Pin Edge to Buffer: Interrupt Plus DMA

Let the pin interrupt start the transfer and let the DMA engine move the bytes

DRDY falls. What should the microcontroller do? There are three honest answers, and they differ in how much of the processor each one eats.

The first is polling: a loop that reads the DRDY pin again and again. It is like standing at the oven door. It works, and it wastes the whole processor. The second is an interrupt: the DRDY pin is wired to an external-interrupt input (EXTI on STM32 parts). When the pin falls, the hardware pauses whatever code is running, jumps to a handler function, and comes back afterwards. Your main code never watches the pin.

Inside that handler you can read all 27 bytes by hand, one SPI byte at a time. That is the second design. The third design starts the transfer and leaves. DMA (direct memory access) is a small engine on the chip that copies data between a peripheral and memory without the processor. You tell it “move 27 bytes from the SPI receiver to this buffer”. It does so while the processor runs other code, then raises a second interrupt when done.

The cost in time

Take SCLK at 4 MHz. One frame is 216 bits, so the read lasts 216 / 4 MHz = 54 µs. If the handler copies bytes itself, the processor is busy for those 54 µs. At 250 SPS that is 54 / 4,000 = 1.35% of the time: fine. At 16 kSPS the period is 62.5 µs, so the copy takes 86% of the processor. Nothing else gets done.

With DMA, the handler does only a few steps: pull CS low, point the DMA at the buffers, start it, return. Say that takes about 3 µs. A second short handler runs at the end to raise CS and store the frame. Together that is roughly 6 µs of processor work per frame, about 10% at 16 kSPS. These handler times are illustrative. Measure yours with a pin and a scope.

DMA saves processor time. It does not save latency. The 54 µs still pass on the wire. This is the point of the next device.

Delay the interrupt

Three lanes over two DRDY periods: the DRDY edge, the processor, and the SPI read. Grey is other code that holds off interrupts. Choose a design and a data rate, then lengthen the block until a frame is lost.

0 µs

Illustrative timing: SCLK at 4 MHz (a 54 µs read), about 3 µs of handler work to start DMA and 3 µs to finish it. The read must end 4 tCLK (1.95 µs) before the next DRDY. Real values depend on your clock, bus and priorities.

Set 16 kSPS and leave the block at zero. The CPU design keeps the processor busy for most of every period, and the DMA design leaves it nearly free. Now raise the block to 20 µs. Both designs lose a frame. The delay moved the start of the read, and the read no longer fits before the next edge.

The latency budget

This gives a rule. Interrupt latency is the time from the DRDY edge to the first instruction of your handler. Its worst case is the longest stretch where something else keeps interrupts off or runs at a higher priority. The budget is simple:

worst latency ≤ tDR − read time − 4 tCLK (250 SPS, 4 MHz: 4,000 − 54 − 2 = 3,944 µs)

At 250 SPS the budget is generous: almost 4 ms. A flash write, a display refresh or a Bluetooth event fits inside it. At 16 kSPS and 4 MHz it is 62.5 − 54 − 2 = 6.5 µs, and almost any other interrupt breaks it. That is why high rates call for a faster SCLK, a higher interrupt priority for DRDY, and short critical sections everywhere else.

For EEG at 250 to 1,000 SPS you have wide slack. The risk is rarer: a long, unusual block. A flash erase can stall code fetches for milliseconds on some parts (check your part’s reference manual). A logging call that prints over a slow UART can do the same. You will not see those in a short test. A counter will find them in a long one.

The code

cstatic const uint8_t tx_zero[27];        /* 27 x 0x00: the no-op stream for RDATAC */
static frame_t rx_dma;                      /* the DMA lands the 27 bytes here */

/* 1) DRDY fell: EXTI interrupt. Keep this tiny. */
void HAL_GPIO_EXTI_Callback(uint16_t pin) {
    if (pin != DRDY_Pin) return;
    CS_LOW();
    HAL_SPI_TransmitReceive_DMA(&hspi1, (uint8_t *)tx_zero, rx_dma.raw, 27);
}

/* 2) DMA finished all 27 bytes: second interrupt. */
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *h) {
    wait_4_tclk();                 /* datasheet: 4 tCLK (about 2 us) after the last SCLK */
    CS_HIGH();
    ring_push(&rx_dma);          /* Chapter 7: hand the frame to the main loop */
}

HAL callback names differ between STM32 families, and some have separate rising and falling EXTI callbacks, so check your own HAL. The shape stays the same everywhere. The first handler must do almost nothing. The second must copy the frame out before the next one overwrites rx_dma. Chapter 7 removes that copy by pointing the DMA at the ring itself. The lesson on drivers and state machines shows the same split between a thin handler and non-blocking work, and interrupts and DMA covers priorities and entry cost.

When it goes wrong

Symptom. Frames are lost in clusters, and only when the radio is connected or the display updates.

Measure. Use the spare-pin trick from the note below. Capture many DRDY edges and plot the delay from each edge to the pin rising. The average looks fine. The worst case, the tail, is what loses frames. Find the code that runs when the spikes happen.

Fix. Give the DRDY interrupt a higher priority than the radio or display code. Shorten any section that turns interrupts off. Move heavy work out of handlers and into the main loop. The budget from this chapter turns the fix into a number: every blocker must fit inside it.

At 16 kSPS with SCLK at 4 MHz, another interrupt holds off yours for 20 µs. What happens?

Chapter 5

The Status Word and Lead-Off

Check the 1100 marker and learn which electrode came loose, in every frame

Twenty minutes into a session, one electrode on a cap peels away from the scalp. The channel does not go quiet. It swings to a wild value, or it picks up room hum, or it sticks at the top of its range. On a graph you might think the person blinked. A good device does not guess. The chip tells you, inside every frame, which electrodes it believes are off.

That message lives in the first three bytes of the frame, the 24-bit status word from Chapter 1. Time to read it properly.

Four fields in 24 bits

The datasheet gives the layout: 1100, then LOFF_STATP, then LOFF_STATN, then four general-purpose-pin bits. In C they come out with shifts and masks. Bit 23 is the first bit that arrives.

BitsFieldWhat it holds
23 to 20markerAlways 1100 (0xC). A cheap check that you are aligned.
19 to 12LOFF_STATPOne bit per channel for the positive input (IN8P_OFF at the top, IN1P_OFF at the bottom). 1 means electrode off.
11 to 4LOFF_STATNThe same, for the negative input of each channel.
3 to 0GPIOFour bits copied from the chip’s GPIO data register, bits 7 to 4.

Every EEG channel measures the difference between two electrodes. That is why each channel has a positive input (P) and a negative input (N), and why there are two status registers. If either is off, the channel is bad.

The marker is a free check

The first four bits never change. So the very first thing your code does with a frame is test them. If the top nibble is not 0xC, something is wrong with the transfer: the wrong SPI mode (Chapter 3), a CS glitch, a read that started at the wrong byte. A random garbage frame passes this test one time in 16, so it is a smoke alarm, not a proof. Count the failures. A small number that grows over a long session points at wiring or noise.

How the chip knows an electrode is off

The datasheet describes two methods. In DC lead-off, a tiny current (or a 10 MΩ resistor) gently pulls one input toward the supply and the other toward ground. A connected electrode sits on the skin, so the skin’s conductive path holds the input near the signal. A disconnected input has nothing holding it, so it floats to the rail. A comparator watches each input against a threshold. The threshold is the COMP_TH field of the LOFF register: 95% of the supply on the positive side, and 5% on the negative side, at the reset value of 000.

The current is set by ILEAD_OFF: 6 nA, 24 nA, 6 µA or 24 µA. In AC lead-off, the chip instead drives a small alternating current at 7.8 Hz or 31.2 Hz and the host measures its size in the data to get the electrode impedance. The next lesson uses that for an impedance check.

Two rules from the datasheet matter for firmware. First, the status bits are only valid for a side whose sense bit is set in LOFF_SENSP or LOFF_SENSN. Without them, ignore the status bits. Second, a bit set in STATP or STATN tells you which side is off. The channel’s own value only tells you that something is off.

Unplug an electrode

Press the P and N buttons to peel off one side of a channel. Watch the 24 status bits, and the channel’s trace. Then switch the lead-off sense bits off.

P side
N side

The word layout, the register names and the rule that status bits are valid only with the sense bits set are from the ADS1299 datasheet (9.4.4.2, 9.6.1.9, 9.6.1.12). The traces are a toy: a real off channel may rail, or pick up hum, depending on the setup.

Peel off IN3N and the word becomes C0 00 40. Now turn the sense bits off and the same electrode reads as clean: the word goes back to C0 00 00. The chip is not wrong. You asked it not to look. A bring-up bug where lead-off never reports anything is almost always a missing sense bit.

What firmware does with it

Three rules keep things simple. Never drop a frame because a lead is off: the other seven channels are fine, and a missing frame would break the count. Pass the two status bytes on to the host unchanged, so the software that analyses the recording can mark the bad stretch. And never decide on a single frame. A real electrode that is just on the edge of the threshold may flicker.

The last four bits are worth a mention. They copy the state of up to four chip pins into the frame. If you wire an event line, such as a stimulus trigger, to one of those pins, its level travels with the sample. Check on your bench exactly when the chip samples the pin, before you rely on it for timing.

ctypedef struct { uint8_t marker, statp, statn, gpio; } status_t;

static inline status_t parse_status(const uint8_t *r) {
    uint32_t s = ((uint32_t)r[0] << 16) | (r[1] << 8) | r[2];
    return (status_t){ s >> 20, (s >> 12) & 0xFF, (s >> 4) & 0xFF, s & 0xF };
}
/* bit n of statp/statn set: channel n+1 has that electrode off */
static inline uint8_t bad_channels(status_t s) { return s.statp | s.statn; }

/* datasheet example: DC lead-off on all channels */
wreg(LOFF,       0x00);   /* 95%/5% thresholds, 6 nA, DC (the reset value) */
wreg(CONFIG4,    0x02);   /* PD_LOFF_COMP = 1: comparators enabled */
wreg(LOFF_SENSP, 0xFF);
wreg(LOFF_SENSN, 0xFF);

When it goes wrong

Symptom. Lead-off never reports anything, even with an electrode in your hand. Or the flags blink on and off on a lead that is almost loose.

Measure. Stop continuous reading with SDATAC, then read back LOFF_SENSP, LOFF_SENSN and CONFIG4 with RREG. The sense registers reset to 0x00, so a missing write leaves them silent. Log how many frames each flag stays on.

Fix. Write the three registers from Chapter 5 during bring-up. On the host, call a lead bad only after its flag has held for a stretch, such as 250 frames in a row (one second at 250 SPS). Report the stretch, not each flicker.

The status word is C0 20 00. What does it say?

Chapter 6

Lose a Sample, Catch It

Add a counter, read the gap across wrap-around, and fill the hole honestly

The ADS1299 does not number its frames. A frame has a status word and eight channels, and that is all. If one frame never reaches you, the next one looks exactly like it would have anyway. So the number has to come from your firmware.

The idea is old and simple: a sequence counter. Give every frame a number that goes up by one. The host checks that each number is one more than the last. A jump means frames were lost, and the size of the jump says how many. It is the same trick a bank uses when it numbers cheques.

Where you count matters

The first idea is to add one each time you read a frame. This fails in the way that matters most. A frame you never read never adds one. The counter goes 5, 6, 7 straight through the hole. It counts what you caught, not what the chip made.

So you must count the chip’s events: the DRDY edges. The second idea is to add one inside the DRDY interrupt handler. That is better: if the handler runs but the read fails (a DMA error, a full buffer), the counter still moves and the next frame shows a jump. But there is a hole here too. An interrupt pin has one pending flag. If something holds interrupts off for two whole periods, two DRDY edges arrive and only one interrupt fires. The counter moves by one for two frames.

The third idea closes that hole by counting in hardware. Many microcontrollers have a timer that counts pulses on a pin with no help from the processor (on STM32 parts this is a timer in external clock mode; check your part). Wire DRDY to it, and read the count inside the handler. Every edge is counted, whatever the software was doing. Compare the three below.

Lose a sample, catch it

Top row: the 16 DRDY edges the chip made. Middle row: the frames your firmware read, each stamped with the counter you chose. Bottom row: the gaps the host finds by checking each number. Lose some samples, then try each counter.

Toy stream of 16 frames. Lose a read: the interrupt runs but the transfer fails. Hold off the interrupt: two edges arrive during one pending interrupt, so the first frame is overwritten before any code sees it. Which counter sees which loss follows from where it counts; real systems mix both failures.

Count frames read, and neither loss shows: the numbers stay in a perfect row. Count interrupts, and a lost read shows as a jump of one, but a held-off interrupt still hides. Count in hardware, and both show. The lesson is a rule worth keeping: count the thing that happens at the source, not the thing that arrives at the sink.

Reading the gap, across wrap-around

A one-byte counter holds 0 to 255, then wraps to 0. The check must work across the wrap. Use unsigned subtraction: the gap is (seq − prev − 1) in 8-bit arithmetic. With prev = 255 and seq = 0: 0 − 255 − 1 = −256, which is 0 in 8 bits, so no gap. With prev = 255 and seq = 1: 1 − 255 − 1 = −255, which is 1 in 8 bits, so one frame is lost.

A small counter has a blind spot. If exactly 256 frames vanish, the counter is back where it started and the check sees no gap. At 250 SPS that is 256 × 4 ms = 1.024 s: a one-second blackout would pass. A 16-bit counter stretches the blind spot to 65,536 × 4 ms = 262 s. A host timestamp on each packet (Chapter 8) covers the rest.

cstatic uint8_t  prev_seq;
static uint32_t lost_total;

void on_frame(const slot_t *s) {
    uint8_t gap = (uint8_t)(s->seq - prev_seq - 1);   /* correct across 255 -> 0 */
    if (gap) {
        lost_total += gap;
        emit_placeholders(gap);                         /* keep one row per sample */
    }
    prev_seq = s->seq;
    emit_frame(s);
}

What to do with a hole

Finding a loss is half the job. The other half is deciding what the recording contains in the gap. The honest choice is a placeholder: a row with a “lost” flag and no invented numbers. Row count and timing stay right, and the analysis software can choose to fill the gap or skip it. The hero at the top of the page draws a ring and a dashed line at each placeholder for this reason.

Also count. A lost-frame counter in the stream header, sent every second, tells you the health of the link with no extra work. A device that loses 15 frames in 150,000 (the Chapter 0 example) reports a ratio of one in ten thousand. Now you can compare two firmware versions by number.

The first frame after START needs care. The counter has no earlier frame to compare with, so set prev_seq to seq − 1 on the first frame, or you will report a false loss.

When it goes wrong

Symptom. The host reports a loss in the very first packet of every run. Or after a restart it reports a gap of 200 frames that did not happen.

Measure. Print the first three sequence numbers after each START and each host reconnect. The hardware counter holds whatever it counted before, so the first frame carries an arbitrary number.

Fix. Treat the first frame after START as the baseline: set prev_seq to its sequence minus one. On the host, treat a gap larger than a sensible limit, such as one second of frames, as a restart. Log it as a restart, and do not add it to the lost-frame total.

A frame is lost because the DMA transfer failed, but the DRDY interrupt did run. Which counters show a jump of one?

Chapter 7

The Ring Buffer and the Overrun

Size the buffer between the interrupt and the main loop so a slow loop cannot lose frames

The frames now arrive on time, one every 4 ms, caught by an interrupt and moved by DMA. But the rest of the program is not so steady. The main loop packs frames, writes to a Bluetooth stack, blinks a light, and sometimes waits 30 ms for a radio event. The frames do not wait for it.

Something must sit between the steady producer and the uneven consumer. That something is a ring buffer, also called a circular buffer: a fixed array of slots that the producer fills in order and the consumer empties in order, both wrapping from the end back to the start. Picture a sushi belt with a fixed number of plates. The chef (the interrupt) adds plates. The diner (the main loop) takes them. If the diner falls asleep, the plates pile up until the belt is full.

Two indices and one rule

A ring needs two numbers. head is where the producer writes next. tail is where the consumer reads next. Each side changes only its own number. This matters. With one writer per index, no lock is needed on a single-core chip, and the interrupt never has to wait for the main loop.

A neat way to track fullness is to let both indices count up forever and take the slot as index & (N−1), which works when N is a power of two. Then head − tail is the number of frames waiting. It is empty at 0 and full at N. Unsigned arithmetic stays correct when the numbers wrap around 232.

What to do when it is full

Sooner or later the ring fills. The interrupt cannot wait, and it must not overwrite a slot the consumer is reading. The simplest policy is to drop the newest: do not store the incoming frame, and add one to an overrun counter. The sequence counter of Chapter 6 then shows the gap, so the loss is known. The other policy, dropping the oldest, means the interrupt moves the consumer’s tail. Two writers on one index is a race. Avoid it.

The DMA needs somewhere to write even when the ring is full. A clean trick is a spare slot, a “trash” slot, which the DMA targets when there is no room. The bytes land harmlessly and the overrun counter moves up by one. The code below does this, and it also removes the copy from Chapter 4: the DMA writes straight into the ring slot.

How big?

The ring must hold every frame that arrives during the longest stall of the consumer. If the main loop can stall for S ms, then the frames to store are S / 4 at 250 SPS. A 100 ms stall brings 25 frames, so a ring of 16 loses 9, and a ring of 32 loses none. Use the next power of two, then add margin, because the worst stall is the one you have not measured yet.

Memory is the cost. A slot holds the 27-byte frame and a 1-byte sequence number: 28 bytes. A ring of 32 uses 896 bytes and rides out a stall of up to 128 ms at 250 SPS (32 × 4 ms). At 16 kSPS the same ring survives only 2 ms.

Stall the main loop

Each square is a slot in the ring. Frames arrive every 4 ms while the main loop is stuck. Choose the size of the ring and the length of the stall, then press the button and watch the ring fill.

16
100 ms

Arithmetic model at 250 SPS, one frame per 4 ms, a ring that is empty when the stall starts, and a consumer that drains everything once the stall ends. The 28-byte slot is the 27-byte frame plus a 1-byte sequence number. Stall lengths are illustrative.

Try 8 slots against a 100 ms stall: 25 frames arrive, 8 fit, and 17 are lost, which is 68 ms of data. Move to 32 slots and nothing is lost. The ring is the cheapest insurance in the whole design. Its price is a few hundred bytes of RAM.

c#define RING_N 32                        /* power of two */
typedef struct { uint8_t seq; uint8_t raw[27]; } slot_t;   /* 28 bytes */

static slot_t ring[RING_N], trash;
static volatile uint32_t head, tail, overruns;   /* head: ISR only. tail: main only. */

/* DRDY handler: choose where the DMA writes, with no copy afterwards */
static slot_t *dma_target(void) {
    slot_t *s = (head - tail >= RING_N) ? &trash : &ring[head & (RING_N - 1)];
    if (s == &trash) overruns++;
    s->seq = (uint8_t)edge_count_hw();    /* Chapter 6: count at the source */
    return s;
}
/* DMA-complete handler: publish the slot */
static void dma_done(slot_t *s) { if (s != &trash) head++; }

/* main loop */
static bool ring_pop(slot_t *out) {
    if (tail == head) return false;
    *out = ring[tail & (RING_N - 1)];
    tail++;
    return true;
}

On a part with a data cache, such as a Cortex-M7, the DMA buffer must sit in memory the cache does not hold, or you must invalidate the cache lines before reading. Without that, the main loop can read stale bytes. The lesson on interrupts and DMA covers circular and double buffering in more depth.

When it goes wrong

Symptom. Rare frames carry wrong bytes, but the checksum of the packet still passes. Or the overrun counter keeps climbing slowly for hours.

Measure. Record the ring’s high-water mark, the largest fill level seen so far, and print it once a second. A mark that keeps near the top means the consumer is too slow on average. A mark that sits low with rare spikes points at a stall. On a Cortex-M7, stale bytes point at the data cache.

Fix. For a slow consumer, speed it up or lower the data rate. A bigger ring only delays the problem. For spikes, size the ring from the longest stall plus margin. For the cache, place the ring in memory the cache does not hold, or invalidate each slot before reading it.

The main loop can stall for 60 ms at 250 SPS. What is the smallest power-of-two ring that holds every frame?

Chapter 8

Packing Frames for the Host

Wrap frames in a header, a counter and a checksum, and budget the bytes per second

The frames are in the ring. Now they must reach the laptop, over a serial cable, a USB port or a radio. All three carry bytes in a row and nothing more. A byte stream has no marks between packets. If the receiver joins late, or one byte goes missing, how does it know where a packet starts?

It needs three things. A sync byte at the start of every packet, so the receiver can find the beginning again. A sequence number, from Chapter 6, so the receiver can count what is missing. And a checksum at the end, a small number computed from the other bytes, so the receiver can tell a damaged packet from a good one.

A packet, byte by byte

This lesson uses a 30-byte packet. It is a design example, not a standard. It holds one sync byte (0xA0), one sequence byte, the 3 status bytes, the 24 channel bytes, and one checksum byte. Together: 1 + 1 + 3 + 24 + 1 = 30.

The OpenBCI Cyton board uses the same shape. Its packets begin with the byte 0xA0, carry one sample-number byte and 24 bytes of EEG for 8 channels, then 6 auxiliary bytes and a footer byte, for 33 bytes in all (OpenBCI documentation). It has no status word. Two designs, made apart, share the same shape: a header to find, a number to count, the data. The problem forces that shape.

The checksum here is the sum of bytes 1 to 28, kept to 8 bits. It is the simplest possible. A real design would use a CRC (cyclic redundancy check), which catches more kinds of damage, but the idea is the same.

Why each part is needed

The sync byte alone is not enough. The value 0xA0 can also appear inside the data: a channel byte can be anything from 0x00 to 0xFF. A receiver that trusts every 0xA0 may lock onto the wrong spot. The checksum fixes that. If the 30 bytes after a candidate 0xA0 do not add up, the receiver slides forward one byte and tries again.

The rule is: sync to find it, checksum to trust it, sequence to count it. The device below runs three real receivers on a real byte stream. The stream has 8 packets. Packet 4 holds an 0xA0 in its data on purpose. Switch on the faults and compare the receivers.

Damage the stream

The bar is the 240 bytes that leave the board: blue sync, teal sequence, orange data, purple checksum. Below are the 8 packets as the receiver sees them. Choose a receiver and switch on the faults.

The receivers run for real on a seeded byte stream built in your browser: 8 packets of 30 bytes with a sum-of-bytes checksum, and a 0xA0 placed inside packet 4. The fault positions are illustrative; the shape is the OpenBCI-style layout, not their code.

With the first receiver and the dropped byte on, every packet after packet 3 is cut in the wrong place and is garbage, and nothing says so. With sync only, the receiver finds the next 0xA0, but it accepts damaged packets and false starts. With sync and checksum, only the damaged packets are lost. The sequence numbers of the survivors then show exactly which ones: that is Chapter 6 doing its job.

How many bytes per second?

The packet size sets the load on the link. At 250 SPS, 30 bytes per packet is 7,500 bytes per second. A serial line in the common 8N1 format sends 10 bits for every byte (start bit, 8 data bits, stop bit), so that is 75,000 bits per second. The next standard baud rate above that is 115,200. The line is then 65% full.

RateBytes per secondSerial bits per secondSmallest standard baud
250 SPS7,50075,000115,200 (65% full)
500 SPS15,000150,000230,400 (65% full)
1 kSPS30,000300,000460,800 (65% full)
4 kSPS120,0001,200,0002,000,000 (60% full)

A radio link adds its own limits on packet size and rate. The lesson on streaming it reliably takes those on, with retransmits and timestamps. For aligning several devices, see many MCUs, one timeline, and for logs that must survive a dropped connection see store-and-forward.

cvoid build_packet(uint8_t out[30], const slot_t *s) {
    out[0] = 0xA0;                          /* sync */
    out[1] = s->seq;                        /* sequence: Chapter 6 */
    memcpy(&out[2], s->raw, 27);           /* 3 status + 24 channel bytes, raw counts */
    uint8_t sum = 0;
    for (int i = 1; i < 29; i++) sum += out[i];
    out[29] = sum;                        /* checksum over bytes 1..28 */
}

When it goes wrong

Symptom. The host shows bursts of checksum errors whenever someone touches the USB cable. Or the host misses bytes during a heavy screen redraw, and the errors have no pattern.

Measure. Count rejected packets, resync events and bytes skipped, once a second, on the host. Count bytes on the board’s side too. If both sides agree, the damage happened on the wire. If the host saw fewer bytes, its own input buffer overflowed.

Fix. For wire damage, rely on the slide-one-byte receiver and the sequence gaps. For a host overflow, read the port in a thread of its own with a larger buffer, and never in the same loop as drawing. Report the counts to the user as a link health figure.

A receiver sees the byte 0xA0 inside the data of a packet and starts a false packet there. What stops it from accepting the false packet?

Chapter 9

Field Guide: Acquisition Firmware on One Page

Keep the numbers, the checklist and the core code, and see where to go next

The one-paragraph summary

The ADS1299 makes a frame of 27 bytes at a steady rate and signals it with the DRDY pin. Your firmware answers with a short interrupt that starts a DMA read over SPI mode 1, with CS held for all 216 bits. It checks the 1100 marker, reads the lead-off bits from the status word, and stamps a sequence counter that counts DRDY edges at the source. A ring buffer sized for the longest stall hides the uneven main loop. A sync byte, the sequence and a checksum carry each frame to the host, which can then find every lost sample.

The numbers that matter

WhatNumberWhy it matters
One frame216 bits = 27 bytes (24 status + 8 × 24)The size of every DMA transfer
Status word1100, STATP (8), STATN (8), GPIO (4)Marker check and lead-off in every frame
Code range7FFFFF to 800000, two’s complementThe chip clips at these codes
One count22.35 nV at gain 24, VREF 4.5 V; full scale ±187.5 mVCounts to microvolts
Default rate250 SPS (DR = 110), tDR = 4 ms; range 250 SPS to 16 kSPSThe time you have per frame
Master clock2.048 MHz; 4 tCLK = 1.95 µsThe keep-out and decode time
SCLK floor54 kHz at 250 SPS, 216 kHz at 1 kSPS, 3.57 MHz at 16 kSPSFrom Equation 9 of the datasheet
SCLK ceiling20 MHz (tSCLK ≥ 50 ns at 2.7 to 3.6 V)Do not go faster
SPI modeCPOL 0, CPHA 1; DOUT valid within 17 ns of the rising edgeSample on the falling edge
First frame after START32,777 tCLK = 16.0 ms at 250 SPSDo not expect a frame at 4 ms
CommandsSDATAC 0x11, RDATAC 0x10, START 0x08, STOP 0x0A, RESET 0x06The bring-up sequence
Lead-offthresholds 95% / 5% at reset; 6 nA to 24 µA; AC at 7.8 or 31.2 HzWhat sets the off flags
Counter blind spot8 bits: 1.024 s; 16 bits: 262 s (at 250 SPS)When a gap looks like no gap
Ring slot28 bytes; 32 slots = 896 bytes = 128 ms at 250 SPSStall tolerance for the RAM
Host packet30 bytes; 7,500 bytes/s at 250 SPSLink load, 65% of 115,200 baud

The terms

TermPlain meaning
DRDYThe chip’s pin that falls when a new frame is ready.
FrameStatus word plus 8 channel readings for one instant.
RDATACRead-data-continuous mode: clock out each frame with no command.
EXTIA pin interrupt on an STM32 part.
DMAA circuit that copies bytes into memory without the processor.
Sequence counterA number that rises by one per frame, counted at the source.
Ring bufferA fixed array filled and emptied in order, wrapping at the end.
OverrunA frame that arrived with no free slot.
ChecksumA small number computed from a packet, to detect damage.

The checklist

  1. Compute the SCLK floor for your data rate from the datasheet, and pick a speed between it and 20 MHz.
  2. Set SPI mode 1 (CPOL 0, CPHA 1) and hold CS low for all 27 bytes.
  3. Bring up in order: SDATAC, write the registers, START, RDATAC.
  4. Keep the DRDY handler tiny: CS low, start DMA, return.
  5. Check the 1100 marker in every frame and count the failures.
  6. Count DRDY edges in hardware and stamp the sequence number at the source.
  7. Size the ring as the worst stall divided by tDR, rounded up to a power of two, plus margin. Drop the newest and count overruns.
  8. Keep raw counts and pass the status bytes on unchanged.
  9. Frame the packet with a sync byte, the sequence and a checksum. Slide one byte on a bad checksum.
  10. Test by breaking it: stall the main loop, unplug a lead, and check that your counters match a logic analyzer.

The core as code

c/* acquisition.c: ADS1299 over SPI mode 1, DRDY interrupt, DMA into a ring, 8-bit hardware sequence */
static const uint8_t tx_zero[27];
static slot_t ring[RING_N], trash;
static volatile uint32_t head, tail, overruns;
static slot_t *cur;

void HAL_GPIO_EXTI_Callback(uint16_t pin) {                    /* DRDY fell */
    if (pin != DRDY_Pin) return;
    cur = (head - tail >= RING_N) ? &trash : &ring[head & (RING_N - 1)];
    if (cur == &trash) overruns++;
    cur->seq = (uint8_t)edge_count_hw();                         /* count at the source */
    CS_LOW();
    HAL_SPI_TransmitReceive_DMA(&hspi1, (uint8_t *)tx_zero, cur->raw, 27);
}
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *h) {            /* 216 bits done */
    wait_4_tclk(); CS_HIGH();
    if (cur != &trash) head++;
}
void main_loop_step(void) {
    slot_t s;
    while (ring_pop(&s)) {
        if ((s.raw[0] & 0xF0) != 0xC0) marker_errors++;      /* Chapter 5 */
        on_frame(&s);                                          /* gap check: Chapter 6 */
        build_and_send_packet(&s);                             /* Chapter 8 */
    }
}

Where this sits in the field

This lesson is the digital half of an EEG front end. The previous lesson covers everything before the converter: electrodes, the amplifier and the bias drive. The analog front end lesson in the BCI series goes further on the analog side. Once frames arrive reliably, interference and filters cleans them, streaming it reliably sends them over lossy links with timestamps, and on-device decode and safety adds the rules of medical firmware. For what the host does next, see filtering neural signals and real-time closed loop.

Keep going

The general tools used here are taught elsewhere: interrupts and DMA, buses on the wire, drivers, HALs and state machines, and for the register-level view of the same ideas on one board, embedded real-time systems and hardware interfacing. For the starting point of any firmware, see from vector table to main.

Sources used

  1. Texas Instruments, ADS1299 datasheet (SBAS499C, revised January 2017). ti.com/lit/ds/symlink/ads1299.pdf. Source of the frame format, status bits, timing tables, Equation 9, data-rate table, lead-off registers, commands and the SPI mode.
  2. OpenBCI, Cyton data format. docs.openbci.com/Cyton/CytonDataFormat. Source of the 0xA0 header, sample number, 24 EEG bytes, 6 auxiliary bytes, footer and 33-byte packet used as a comparison.
  3. The STM32 HAL function names in the code are from ST’s HAL drivers. Names and callback forms differ between families, so check the driver manual for your part. Handler times and loss rates on this page are labelled illustrative where they appear.
The takeaway. A recording is only as honest as its counter. Count at the source, catch the frame with a short interrupt and DMA, size the ring for the worst stall, and every loss becomes a number you can see.

Open Teach to explain the gap detector on a whiteboard, or Sparks for the short cards. Then go back to the hero, lose a sample, and say why each counter sees it or does not.

Acquisition Firmware (fw-bio-02)
Read the ADS1299 datasheet · Back to Gleams