Mains hum is hundreds of times bigger than the brain signal you want. Run one recording through three filters and watch each trade delay against ringing.
Learn where 50 and 60 Hz hum comes from, how a notch filter removes it, what motion and saturation do to a recording, how firmware checks an electrode, and where in the chain to filter.
Pick a filter, then drag the hum drift. Watch the delay and the ringing change for the same recording. Then we build, piece by piece, everything under this one trade.
You need a rough idea of a sine wave (a smooth wave with a frequency) and a little C. We build the rest from zero.
Part of the series Firmware from Zero to Expertise, biopotential track. Built from the TI ADS1299 datasheet (SBAS499C), the Arm CMSIS-DSP documentation and the OpenBCI documentation. Signal-processing grounding: Stanford EE269, see our discrete signals and linear systems lessons.
A model, not a real recorder: a made-up 250 samples per second recording with 10 Hz alpha, 50 Hz hum and one electrode step. Filters are computed live in your browser. Sample rate matches the ADS1299 default of 250 SPS.
Chapter 0
See why a clean recording is rare, and name the four things that spoil one before any filter runs
You stick three electrodes on a friend’s forehead. You plug them into your board. You start the stream, and the plot on your laptop shows a fat, regular wave, as thick as a pencil line. It repeats 50 times each second. It fills the screen. Somewhere under it, 1,000 times smaller, is the brain activity you came to see.
That fat wave is mains hum: the 50 Hz or 60 Hz swing of the wall power. Your friend’s body acts like an antenna and picks it up. The board cannot tell hum from brain. Both are just voltage.
This lesson is about what firmware does next. The firmware is the small program that runs on the microcontroller beside the converter. Its job is to hand clean, honest samples to the rest of the system. By the end you will know why the hum is there, how a filter removes it, and what each filter costs.
Frequency is how many times a wave repeats in one second. The unit is the hertz (Hz). A 10 Hz wave repeats ten times a second. Brain rhythms that EEG (electroencephalography, recording the brain’s electrical activity from the scalp) studies sit roughly between 1 and 30 Hz. Mains hum sits at exactly 50 Hz in most of Europe and Asia, and at exactly 60 Hz in the Americas.
A sample is one reading of the voltage at one instant. A converter takes samples at a fixed sample rate. The board in this lesson takes 250 samples per second (250 SPS), the default of the TI ADS1299, a 24-bit converter built for EEG. A rate of 250 SPS can only show waves slower than 125 Hz, half the rate. So 10 Hz and 50 Hz both fit.
A filter is a small calculation on the stream of samples. It keeps some frequencies and shrinks others. Think of a graphic equaliser on a stereo: you pull one slider down, and one pitch gets quieter. A notch filter pulls down one narrow slider, here 50 Hz or 60 Hz, and leaves the rest alone. The previous DSP lesson built the fixed-point tools for this on a Cortex-M. Here we use them on a signal that is much smaller and much meaner.
Adult scalp EEG is about 10 to 100 microvolts (µV) in size. A microvolt is one millionth of a volt. At gain 24 the ADS1299 can read a step of 22.35 nanovolts (one billionth of a volt) at each count of its 24-bit output. That fine step is why it can see the brain at all. The same sensitivity also sees everything else. Slide the hum below and compare it with the brain on one ruler.
Each bar is a size on a log ruler: every gridline is ten times bigger than the one before. The teal bar is the brain. Drag the hum and watch the gap.
Real: 22.35 nV per count at gain 24 and 4.5 V reference (ADS1299 datasheet, equation 8), full scale ±187.5 mV at gain 24 (±VREF/gain), EEG 10 to 100 µV. Illustrative: the hum range and the 100 mV electrode offset. Real hum depends on the room, the wires and the skin.
At 1 millivolt of hum the gap to a 50 µV brain wave is 20 times. A bad room gives far more. The hum rarely needs a bigger converter. It needs a better plan. That plan has four parts, one per enemy.
The fifth question is not an enemy but a choice. Should the filter run on the microcontroller, or later on the host (the laptop or phone that receives the stream)? Chapter 7 answers it with numbers. Chapter 3 is the centre of the lesson: the same recording through three filters, so you can feel what each one costs.
One rule runs through every chapter. A filter changes the data and cannot be undone. Keep that in mind each time we add one.
Chapter 1
Follow the hum from the wall into the body, and see why two slightly different electrodes turn a harmless shift into a signal
Wave your hand near an unplugged guitar lead and the amplifier buzzes. The buzz is 50 or 60 Hz. Your hand did nothing electrical. It only changed how the lead “sees” the room.
Every wall socket, lamp cable and charger fills the room with a weak electric field that swings at the mains frequency. A human body is a bag of salt water, and it conducts. The field pushes a tiny current through your friend, and that current lifts the whole body to a small voltage compared with the board’s ground. Both electrodes on the head rise and fall together, 50 times a second.
Two names help here. A voltage that is the same on both electrodes is a common-mode voltage. A voltage that is different between them is a differential voltage. The brain makes a differential voltage: one electrode sits near the active tissue and the other does not. The hum, at first, is common-mode.
An EEG amplifier is a differential amplifier. It measures only the difference between its two inputs and ignores what they share. Its ability to ignore the shared part is the common-mode rejection ratio (CMRR), quoted in decibels (dB). A decibel is a way to write a ratio: −110 dB means the output is 10−5.5, about 3.2 millionths, of the shared input.
The ADS1299 datasheet gives a CMRR of −110 dB at minimum and −120 dB typical, measured at 50 Hz and 60 Hz. A shared hum of 0.5 V would then leave only 0.5 V × 3.2 × 10−6, or 1.6 µV, at the output. That is small against a 50 µV brain wave. So why is the hum still huge on a real recording?
Each electrode touches skin through its own contact impedance: how hard the skin makes it for current to flow, measured in ohms. Impedance is resistance that also depends on frequency. One electrode may sit on oily skin and the other on a dry patch. Their impedances differ by a few kilohms.
The amplifier input is not perfect either. It has a very high but finite input impedance to ground. The ADS1299 datasheet gives 1,000 MΩ at DC and 20 pF of input capacitance. At 50 Hz the capacitor has a reactance of 1 / (2π × 50 × 20 pF) = 159 MΩ. Together the two give about 157 MΩ at 50 Hz.
Now each electrode forms a voltage divider: its own contact impedance on top, the amplifier input impedance to ground below. Equation 1 shows what reaches each input.
This follows from each divider giving Vcm × Zin / (Zin + Z), which is close to Vcm × (1 − Z / Zin) when Z is far smaller than Zin. Subtract the two inputs and the Vcm term cancels, leaving the line above. This is our own derivation, and the device below computes it live.
0.5 V × 10 kΩ / 157 MΩ = 31.8 µV (mismatch of 10 kΩ, body hum of 0.5 V, illustrative)
That is 31.8 µV of false signal from a mismatch of only 10 kΩ. The amplifier’s own CMRR leaves 1.6 µV. So the electrode mismatch leaks 20 times more than the chip does. The skin, not the silicon, sets the hum floor.
Two bars show the hum that reaches the output. The dashed line is a 50 µV brain wave. Drag the mismatch up and watch which bar wins. Then switch on the bias drive.
Real: CMRR −110 dB minimum at 50 and 60 Hz, input impedance 1,000 MΩ DC and 20 pF (ADS1299 datasheet). Illustrative: the body hum voltage, and the bias drive is modelled as a flat 20 times cut in body hum. The real bias loop depends on its gain and on the cables.
The symptom is easy to spot. The 50 Hz wave grows when the cable swings or when the subject touches a lamp. It may be different on each channel.
The measurement is a short test. First record 4 seconds with both inputs of a channel tied to the same electrode, so the mismatch is zero. Then record 4 seconds on the skin. Compute the size of the 50 Hz component in each (Chapter 6 shows the Goertzel sum that does this in a few lines of C). If the shorted channel is quiet and the skin channel is loud, the leak is the mismatch.
The fixes follow from the equation, one per term. Lower Vcm with the bias drive, a circuit that senses the shared voltage and pushes an opposite voltage back through an extra electrode, as the first lesson of this track showed. Lower the mismatch by cleaning and abrading the skin and by seating every electrode firmly. Raise Zin by keeping the amplifier input unloaded. Keep the cables short and away from power cords. Firmware helps by measuring the mismatch, which is Chapter 6.
On real hardware. Board: an ADS1299 board on an STM32 Nucleo. Repeat this: record 4 seconds with the two inputs tied together, then 4 seconds on your forearm. Compare the 50 or 60 Hz size.
Chapter 2
Build a filter that deletes one frequency by adding two old samples, then fix its flaw with feedback and see the price you pay
Suppose a recording holds only hum, a pure 50 Hz wave, sampled at 250 SPS. That is five samples per cycle. The wave repeats exactly every five samples. Could you cancel it with arithmetic on the last few samples?
Yes. Take today’s sample. Add the sample from two steps ago. Subtract the middle sample, scaled by a number. For a wave of the right frequency, the scaled middle sample equals the sum of the outer two, and the answer is zero at every step.
A zero of a filter is a frequency where the output is exactly zero. For hum at frequency f0 and sample rate fs, let ω0 = 2π f0 / fs. This is the angle the wave turns each sample. At 50 Hz and 250 SPS, ω0 = 2π × 50 / 250 = 1.2566 radians, which is 72 degrees per sample. Then use this rule:
Why zero? A cosine obeys cos(a) + cos(a − 2ω) = 2 cos(a − ω) cosω. Put a = ω0n and the identity says the outer samples add up to exactly the scaled middle sample. So the rule subtracts the wave from itself.
This three-sample rule is a poor notch. Its dip is very wide, and it changes the size of every other frequency by a different amount. A 10 Hz alpha wave would come out with a different height. We want a narrow dip with flat gain elsewhere.
The fix is feedback: use the filter’s own past outputs too. Add two terms that depend on y[n−1] and y[n−2]. They create poles, frequencies where the filter would blow up if nothing held it back. We place the poles at the same angle as the zeros but slightly inside the unit circle, at a distance r from the centre, with r just below 1. Near the notch, pole and zero cancel each other, so the response is flat. Right at f0, the zero wins and the output is zero.
The result is a biquad, a filter with two zeros and two poles, written in five numbers:
y[n] = g (x[n] − 2c x[n−1] + x[n−2]) + 2rc · y[n−1] − r2 · y[n−2] (c = cosω0; g keeps DC gain at 1)
Work it for f0 = 50 Hz, fs = 250 SPS, r = 0.95. First c = cos(72°) = 0.30902. The DC gain before scaling is (1 − 2c + 1) = 1.38197 on the zero side, and (1 − 2rc + r2) = 1 − 0.58714 + 0.9025 = 1.31536 on the pole side. So g = 1.31536 / 1.38197 = 0.95180. The five coefficients are then b0 = 0.95180, b1 = −0.58825, b2 = 0.95180, with feedback terms +0.58714 and −0.90250.
The price is memory. The poles keep a little of the past alive, so a sudden event rings. Each sample the ring shrinks by the factor r. After n samples it is rn, which falls to 1/e (37%) in 1 / (−ln r) samples. For r = 0.95 that is 19.5 samples, or 78 ms. The width of the dip is about (1 − r) × fs / π, which is 3.98 Hz. A narrower dip means a longer ring. You cannot have both. Try it.
Left: the unit circle, with the two zeros (hollow, on the circle) and the two poles (filled, inside). Right: the gain in decibels from 0 to 125 Hz. Drag the pole radius toward 1.
Computed live from the five coefficients at 250 SPS. The dip width is the measured −3 dB width of the gain curve, and the ring time is 1 / (−ln r) samples, both derived in this chapter. A model of the filter, not a measurement on a chip.
The five numbers come from a few lines of C, run once at start-up or at design time. Poles close to the circle need exact coefficients, so most firmware keeps them in 32-bit floating point on parts with a floating-point unit (STM32L4 and similar), or in Q31 fixed point as the fixed-point DSP lesson showed. Arm’s CMSIS-DSP library takes them in the order b0, b1, b2, a1, a2, and its equation adds the feedback terms. A design tool that writes y = ... − a1·y[n−1] needs its a1 and a2 negated first, as the CMSIS-DSP documentation warns.
/* Notch coefficients for CMSIS-DSP: { b0, b1, b2, a1, a2 }, feedback with plus signs. */ #include <math.h> void notch_coeffs(float f0, float fs, float r, float out[5]) { float w = 2.0f * 3.14159265f * f0 / fs; float c = cosf(w); float g = (1.0f - 2.0f*r*c + r*r) / (2.0f - 2.0f*c); /* DC gain = 1 */ out[0] = g; out[1] = -2.0f * c * g; out[2] = g; out[3] = 2.0f * r * c; /* a1, plus-sign form */ out[4] = -r * r; /* a2, plus-sign form */ }
At 250 SPS, a1 = 2r cosω0 is 0.587, below 1 in size. At 16 kSPS and 50 Hz, cosω0 is 0.9998, so a1 is 1.90 for r = 0.95 and climbs toward 2 as r nears 1. A Q31 number holds values below 1, so CMSIS stores the coefficients halved and sets postShift = 1, which doubles them again after the multiply. The documentation gives this exact trick with its own example.
The failure shows up two ways. The symptom is a small 50 Hz wave left over, or a 50 Hz ring after every jump. The measurement is the step response: feed in a step and count the samples until the output settles within 2% of its end value. The fix is to choose r for your own limit on ringing, not for the deepest dip. The ADS1299’s built-in sinc3 filter does not help here, because its zeros fall at the data rate and its multiples, 250 Hz and up, not at 50 Hz.
On real hardware. Board: STM32 Nucleo with an ADS1299 board, or a signal generator into any ADC input. Repeat this: feed a 50 Hz sine at 250 SPS through the biquad and log the output amplitude for r = 0.9 and r = 0.99.
Chapter 3
Run the same samples through an IIR notch, a linear-phase FIR and a moving average, and score each on delay, ringing and damage
Two engineers disagree. One says: “Use the two-pole notch. It is five multiplies, and the answer arrives at once.” The other says: “Use the long FIR. It never bends the wave.” A third says: “Average five samples. It costs almost nothing.” All three are right about something. The only honest way to decide is to run the same recording through all three.
Latency is how late the filtered wave arrives. For a wave of one frequency, we call it the group delay: how many samples the filter shifts that wave. A closed loop, such as a brain-computer interface that drives a cursor, feels every millisecond of it.
Ringing is the wobble a filter leaves after a sudden change. We test it with a step, a jump from one level to another and then staying there, like an electrode that shifts on the skin. A perfect filter would pass the step cleanly. Ours wobble for a while. We call the time until the output stays within 0.5% of its end value the settle time.
Two more scores keep us honest. Hum left is how much of the hum survives. We compute it from the filter’s gain at the true hum frequency, which can drift a little from 50.00 Hz. Damage is how much the filter changes frequencies we want to keep. We read it at 10 Hz (alpha) and 25 Hz (beta).
A. The IIR notch is the biquad of Chapter 2, with r = 0.95. IIR stands for infinite impulse response: because of feedback, a single pulse never fully dies, it only fades. Cost per sample: five multiplies and four stored values per channel. Its delay at 10 Hz is 0.08 samples, or 0.3 ms. Its dip is narrow, so a hum that drifts by 0.2 Hz is cut by only 20 dB instead of fully.
B. The linear-phase FIR has 41 taps, designed by subtracting a windowed band-pass from a single pulse. FIR stands for finite impulse response: with no feedback, a pulse is gone after 41 samples. Linear phase means every frequency is delayed by the same amount, so the waveform keeps its shape. The price is that the delay is (41 − 1) / 2 = 20 samples, which is 80 ms at 250 SPS. Cost: 41 multiply-adds per sample per channel. Its notch is wide, so drift hardly matters: −65 dB at 50.2 Hz.
C. The moving average replaces each sample by the average of the last N. If N samples fill exactly a whole number of hum cycles, the hum averages to zero. At 250 SPS and 50 Hz, one cycle is 5 samples, so N = 5 works. Cost: one add and one subtract per sample, using a running sum. Delay: (5 − 1) / 2 = 2 samples, or 8 ms. Damage: it also pulls down the wave you want, by 0.56 dB at 10 Hz and 3.78 dB at 25 Hz.
Now the experiment. The recording is made up: a 10 Hz alpha wave, a smaller 25 Hz wave, a little noise, 100 µV of hum, and a 150 µV electrode step. The dashed line is the truth, the recording without hum. Switch the filter, change the mains frequency, then drag the drift.
Top: the raw recording. Bottom: the filter output (solid) against the hum-free truth (dashed). The chips below score the filter. Try 60 Hz with the average, and try the drift.
A model: the recording, the hum and the step are made up and seeded, so they repeat on every visit. The filters are real and run in your browser at 250 SPS. The drift range is exaggerated to make the effect visible. Sharpness moves the IIR pole radius from 0.80 to 0.995, or the FIR half-length from 10 to 60 taps each side.
Start with the IIR notch. Its delay is almost nothing, yet its settle time is long: 216 ms at r = 0.95. The wobble peaks near 10 µV on a 150 µV step, and it lasts. Drag the sharpness up and it lasts longer. Drag the drift and the hum comes back.
The FIR flips the trade. It delays everything by 80 ms. Once the step arrives it settles in 140 ms from the step, and the wobble has the same shape before and after the main edge, because the filter is symmetric. The FIR also shrugs off drift.
The average is the cheapest and the fastest to settle, 16 ms, but it bends the wave you want. At 60 Hz it fails in a more basic way. One cycle of 60 Hz is 4.17 samples at 250 SPS. N must be a whole number, so N = 4, and the zero lands at 62.5 Hz, not 60. The hum is cut by only 27 dB. The ADS1299 data rates (250, 500, 1,000, 2,000, 4,000, 8,000 and 16,000 SPS) are all multiples of 50 Hz, but none is a multiple of 60 Hz, so this average suits 50 Hz mains only.
| Filter | Delay at 10 Hz | Settles after a step | Gain at 25 Hz | Gain at 50.2 Hz | Cost per sample |
|---|---|---|---|---|---|
| IIR notch, r = 0.95 | 0.3 ms | 216 ms | −0.02 dB | −20 dB | 5 multiplies |
| Linear FIR, 41 taps | 80 ms | 140 ms | −0.01 dB | −65 dB | 41 multiply-adds |
| Average of 5 | 8 ms | 16 ms | −3.78 dB | −47 dB | 1 add, 1 subtract |
Computed in this page’s engine, 250 SPS, notch at 50 Hz. Settle time is the time until the output stays within 0.5% of the end level of a unit step. The cost column counts operations, not measured cycles.
Ask which resource you cannot spare. If it is time, as in a closed loop where every millisecond between brain and cursor counts (see real-time closed-loop BCI), choose the IIR and pay for it in ringing. If it is waveform shape, as in an offline study of the timing of a response, choose the linear FIR and accept the delay, or run it later on the host where delay is free. If it is cycles and power, the average wins, as long as the sample rate divides the mains frequency.
The cycle cost is small anyway. Eight channels at 250 SPS through a 41-tap FIR is 8 × 250 × 41 = 82,000 multiply-adds a second. On a 64 MHz Cortex-M4 that does one per cycle, that is 0.13% of the processor. The real cost of a long filter is the 80 ms of delay, not the arithmetic.
The failure mode has a clear fingerprint. The symptom: after every pop, the trace carries a 50 Hz burst for a fifth of a second (IIR), or the cursor reacts 80 ms late (FIR), or beta waves look weak (average). The measurement: a step test and a gain-at-25-Hz test on the bench, before any subject is involved. The fix: change the sharpness knob, or change the filter, or move the filter to the host.
On real hardware. Board: STM32 Nucleo with the ADS1299 board, or a function generator into the ADC. Repeat this: log a 10 Hz sine plus a 50 Hz sine at 250 SPS. Run each filter and measure the output delay with a scope on a GPIO toggled at the filter start and end.
Chapter 4
Learn why a notch cannot fix a moving electrode, and how a high-pass filter and a pop gate trade smearing against drift
Your friend nods. For half a second the trace slides upward by a few hundred microvolts, then settles somewhere new. A minute later a cable tugs, and the trace jumps like a cliff edge. Neither event is brain. Neither event is at 50 Hz. A notch does nothing for them.
An electrode does not touch the skin directly. Between metal and skin sits a thin layer of gel and sweat, and a small voltage lives across it, called the half-cell potential. When the electrode shifts, the layer changes thickness and the voltage changes with it. Only that one electrode changes, so the amplifier sees a real difference. A momentary jump from such a change is an electrode pop. A slow slide, from sweat or from skin stretch, is baseline wander. Both are kinds of motion artefact.
Traditional EEG amplifiers high-pass the signal early, so the large offset never reaches the converter. The ADS1299 datasheet describes the opposite design. Its 24-bit converter lets the signal stay DC-coupled, meaning no capacitor blocks the slow part. The datasheet says this works because the small EEG can be measured on top of a significant DC offset. It also notes the bias amplifier keeps the common-mode voltage inside the supply rails, which allows the DC coupling.
So the offset and the wander arrive in your data. Removing them is firmware’s job, or the host’s. The tool is a high-pass filter: it passes fast changes and blocks slow ones. The simplest high-pass is the DC blocker:
Worked example. Pick fc = 0.5 Hz at 250 SPS. Then a = 1 − 2π × 0.5 / 250 = 0.98743. A step of 150 µV enters. The output jumps with it, then decays by the factor a each sample: 150 µV, 148.1, 146.2, and so on. It falls to 1% of the step when an = 0.01, so n = ln(0.01) / ln(0.98743) = 364 samples. That is 1.46 seconds. The time constant is 1 / (2π fc) = 0.32 s.
Here is the trade. A high corner (say 5 Hz) kills the wander and recovers from a pop in 0.15 s, but it also cuts the 1 to 4 Hz waves you may want. A low corner (0.05 Hz) keeps those but lets the baseline swim and keeps the pop’s tail for 15 seconds. Clinical displays commonly high-pass at 0.5 to 1 Hz (typical display settings, from the general EEG reference). Many research systems pick lower.
Top: the raw recording with a slow slide and one pop. Bottom: the output of a one-pole high-pass. Drag the corner. Then switch on the pop gate, which takes the jump out of the filter’s input.
A model: the recording, a 300 µV 0.15 Hz slide and one 150 µV jump at 1.0 s that stays are made up. The high-pass is the real one-pole DC blocker above, run at 250 SPS in your browser. The gate threshold (60 µV in one sample) is illustrative; a real one is tuned on real recordings.
A single pop is short, but a high-pass remembers it. The tail of the filter output is a slow decaying curve that looks like activity. The fix is to catch the pop before it gets in. Compare each sample with the one before. If the change is larger than a threshold no brain could make, the sample is a pop. The firmware then does two things. It sets an artefact flag in the packet so the host knows this stretch is unreliable. And it subtracts the jump from everything that follows, so the filter sees a smooth baseline and its state never stores the pop.
/* One-pole DC blocker with a pop gate. Floats for clarity; zero-initialise the struct. */ typedef struct { float a, xr1, xe1, y1, corr; uint8_t flag; } hp_t; float hp_step(hp_t *h, float x, float pop_uv) { float dx = x - h->xr1; /* raw change since last sample */ h->flag = (dx > pop_uv || dx < -pop_uv); /* tell the host */ if (h->flag) h->corr += dx; /* take the jump out of what follows */ float xe = x - h->corr; float y = xe - h->xe1 + h->a * h->y1; h->xr1 = x; h->xe1 = xe; h->y1 = y; return y; }
The gate has its own cost. It removes every jump above the threshold, including a real one. A genuine large spike, or a stimulation pulse, would vanish from the filter too. Keep the flag, so the host knows what was cut, and set the threshold well above anything the brain does. Because corr only grows, reset it when a session starts.
The failure mode, as symptom, measurement and fix. The symptom: a smooth, slowly decaying hump after each movement, which can look like a real slow brain wave. The measurement: line up the hump with the accelerometer or with the artefact flag, and check whether it appears with every nod. The fix: raise the corner a little, add the gate, and always keep the raw stream so you can re-run with other settings (Chapter 7).
On real hardware. Board: an ADS1299 board on an STM32 Nucleo, two electrodes on your forearm. Repeat this: log 30 seconds while you lift and lower your arm three times. Run the DC blocker at 0.5 Hz and again at 0.05 Hz and compare the recovery time.
Chapter 5
Compute the converter’s window at each gain, see how offset and hum eat it, and learn to spot a clipped sample in firmware
A subject starts to sweat during a long session. The electrode offset creeps up. Nothing looks wrong for an hour. Then the trace goes flat on top, like a wave with its peaks sliced off, and the data in those slices is gone for good.
Every converter has a window: the range of input voltage it can measure. Outside it, the output sticks at its largest or smallest code. We call that saturation or clipping. A filter cannot undo it. Information that never reached the converter cannot come back.
The datasheet gives the full-scale input as ±VREF / gain, with VREF = 4.5 V. One count of the 24-bit output is the full span divided by 224: 1 LSB = (2 × VREF / gain) / 224. At gain 24 the window is ±187.5 mV and one count is 22.35 nV. At gain 1 the window is ±4.5 V and one count is 536.4 nV.
That suggests a rule. Higher gain gives finer counts but a smaller window. The datasheet’s noise tables show the other side of the trade. At 250 SPS the input-referred noise is 1.08 µV RMS at gain 1, 0.31 at gain 4, 0.20 at gain 8, 0.16 at gain 12 and 0.14 at gain 24 (Tables 1 to 4). RMS means the typical size of the noise. Against a 10 µV minimum EEG, even 0.31 µV is quiet. So a lower gain costs little noise and buys a large window.
The window must hold three things at once: the electrode offset (the half-cell DC from Chapter 4), the hum that leaked through (Chapter 1), and the signal itself. Treat it as a budget. Spend it in that order.
peak = offset + humpeak + signalpeak ≤ VREF / gain
Worked example. Gain 24, so the window is 187.5 mV on each side. The subject’s offset is 150 mV and the hum is a 50 Hz wave of peak 80 mV (both illustrative, a bad contact). The sum is 230 mV, which is 42.5 mV over. The positive peaks clip when 150 + 80 sin θ > 187.5, so when sin θ > 37.5 / 80 = 0.469. That happens for 34.5% of every hum cycle. The EEG on top is lost for a third of the time.
Drop the gain to 8. The window becomes 562.5 mV. The same 230 mV fits with 332 mV spare, and noise rises from 0.14 to 0.20 µV RMS. The recording is now clean enough to filter.
The two dashed lines are the window edges. The trace is offset plus hum. Parts that leave the window turn red. Raise the offset until it clips, then lower the gain.
Real: window ±VREF/gain with VREF 4.5 V, one count (2×VREF/gain)/224, noise at 250 SPS from ADS1299 Tables 1 to 4 (gain 1: 1.08, 2: 0.57, 4: 0.31, 6: 0.23, 8: 0.20, 12: 0.16, 24: 0.14 µV RMS). Illustrative: the offset and hum sizes. The PGA also saturates inside the chip, within 200 mV of the supply rails, so the real limit can arrive before the converter’s.
Each channel arrives as three bytes in two’s complement, a way to write negative numbers in binary. The datasheet’s code table says an input at or above full scale reads 7FFFFFh, and an input at or below negative full scale reads 800000h. So a code at either end, or one count from it, is the signature of clipping. The same read also gives the scale: 4.5 V / gain / (223 − 1) volts per count, the formula OpenBCI documents for its ADS1299 boards (0.02235 µV per count at gain 24).
/* 3 bytes from the ADS1299 -> signed counts -> microvolts, plus a clip flag. */ static inline int32_t sx24(const uint8_t *p) { int32_t v = ((int32_t)p[0] << 16) | (p[1] << 8) | p[2]; if (v & 0x800000) v -= (1 << 24); /* sign extend */ return v; } static inline int is_clipped(int32_t v) { return v >= 0x7FFFFE || v <= -0x7FFFFF; /* one count from either rail */ } float counts_to_uv(int32_t v, float gain) { return v * (4.5f / gain / 8388607.0f) * 1e6f; }
What do you do with the flag? Three habits keep the data honest. Set a bit in the packet, so the host can drop the stretch. Do not feed a clipped sample into an IIR filter: reload its state with the last good value, or the flat top will ring. And count clipped samples per second, so a slow climb in the count warns you long before the trace looks bad.
The failure mode, as a sequence. The symptom: flat tops, and a notch that rings after each one. The measurement: the share of samples at the rails per second, and the mean of the trace, which shows the offset. The fix: lower the gain, improve the contact, power the bias drive, and let the firmware report a clip counter.
On real hardware. Board: an ADS1299 board on an STM32 Nucleo. Repeat this: set gain 24, build a resistor divider that puts a 200 mV difference across the two inputs (keep both inputs inside the supply rails), and read the codes. Then lower the gain step by step and note when the code leaves the rail.
Chapter 6
Push a tiny known current through each electrode, read the voltage it makes, and turn it into an impedance with a Goertzel sum
A technician presses eight electrodes onto a cap and asks: “Are they all touching?” You cannot tell from the plot. A loose electrode with a lot of hum looks much like a good electrode with a lot of brain. The board must ask each electrode.
The question is simple. Ohm’s law says voltage equals current times impedance, V = I × Z. Push a known current I through the electrode, measure V, and divide. The ADS1299 includes the circuit for this. The datasheet calls it lead-off detection and adds that it is really “electrode-off” detection. The basic principle is to inject an excitation current and measure the voltage.
The DC method pushes a steady current and uses a comparator, a circuit that says yes or no to “is this voltage above a limit?”. A bit per input lands in two registers, LOFF_STATP and LOFF_STATN, and rides along in the 24-bit status word at the start of every sample frame. That word is the bits 1100, then LOFF_STATP, then LOFF_STATN, then four GPIO bits. It tells you which electrode fell off, at no cost, in real time.
The AC method gives a number, not just a yes or no. The chip alternately sources and sinks a current at a fixed frequency, chosen as 7.8 Hz or 31.2 Hz. The excitation sits inside the band you record. It travels through the channel and is digitised with everything else. Firmware then measures its size and gets the impedance. The current has four settings: 6 nA, 24 nA, 6 µA or 24 µA. The datasheet gives the current accuracy as ±20%, and the comparator threshold accuracy as ±30 mV. So treat the answer as an estimate good to about a fifth.
A worked number. Take 24 nA and a good electrode of 10 kΩ. The voltage is 24 nA × 10 kΩ = 240 µV. For a poor electrode of 100 kΩ it is 2.4 mV. For 1 MΩ it is 24 mV. Now try 24 µA on 100 kΩ: that is 2.4 V, far outside the gain-24 window of 187.5 mV from Chapter 5. The estimate would be junk. So you pick a current that keeps the voltage inside the window for the electrodes you expect.
The excitation arrives mixed with brain, hum and noise. We want its size at one known frequency. You could take a full FFT, but that computes every frequency and we need one. The Goertzel algorithm computes one frequency with a two-term recursion and one multiply per sample. For a block of N samples at sample rate fs, the target frequency f lands on bin k = N f / fs. The recursion is s[n] = x[n] + 2cos(2πk/N) · s[n−1] − s[n−2]. At the end, power = s12 + s22 − 2cos(2πk/N) s1 s2, and the amplitude is (2/N) × √power.
Choose N so that k is a whole number, or the tone leaks into neighbouring bins. At 250 SPS, 31.25 Hz repeats every 8 samples. With N = 64 that is 8 whole cycles, so k = 64 × 31.25 / 250 = 8. A 64-sample block lasts 0.256 s. For hum, N = 125 gives k = 25 at 50 Hz and k = 30 at 60 Hz, both whole numbers, so one block length serves both mains frequencies.
Last step: the excitation is a square wave of height ±I, so its fundamental has amplitude 4I/π, about 1.27 I. So Z = amplitude / (1.27 I). This is our own model of the datasheet’s description. The real chip’s digital filter trims the tone by a few percent, so calibrate against a known resistor, such as 10 kΩ, at the start.
Top: 64 samples of one channel, with brain, noise and the excitation tone. Bottom: the true impedance (white tick) against the Goertzel estimate (coloured, with a ±20% band). Drag the impedance up and pick a current.
A model: gain 24 (window ±187.5 mV), 250 SPS, 31.25 Hz excitation, 20 µV alpha, 3 µV noise (seeded). Real: the four currents, the ±20% accuracy and the two excitation frequencies (ADS1299 datasheet). Our model: a fundamental of 4I/π, resistive electrode, no digital-filter droop. The “limit” mark at 20 kΩ is a value you choose; the datasheet gives none.
/* Goertzel: amplitude of one frequency in a block of N samples. k must be a whole number. */ float goertzel_amp(const float *x, int N, int k) { float c = 2.0f * cosf(2.0f * 3.14159265f * k / N); float s1 = 0, s2 = 0; for (int n = 0; n < N; n++) { float s = x[n] + c * s1 - s2; s2 = s1; s1 = s; } float p = s1*s1 + s2*s2 - c*s1*s2; return (2.0f / N) * sqrtf(p); } /* Z in ohms from the 31.25 Hz tone: volts at 4I/pi. Block: N = 64, k = 8 at 250 SPS. */ float z_from_tone(const float *x_volts, float i_amps) { return goertzel_amp(x_volts, 64, 8) / (1.2732f * i_amps); }
The tone also has a cost. It sits in the band and lands in the recording. Run it as a one-time or periodic check before the session, not during it, or filter it out afterward. Do not leave it on while you study 31 Hz brain rhythms.
The failure mode, in order. The symptom: one channel shows far more hum than its neighbours, or the plot wanders. The measurement: the impedance of that electrode, and the hum amplitude from a Goertzel block of 125 samples. The fix: press, clean and re-seat the electrode, then measure again. Record the impedance with the data, so the analyst can see how good the contact was.
On real hardware. Board: an ADS1299 board on an STM32 Nucleo. Repeat this: set AC lead-off at 31.2 Hz and 24 nA, and wire known resistors of 1 kΩ, 10 kΩ and 100 kΩ in place of electrodes. Compare your Goertzel estimates with the true values.
Chapter 7
Add up the delay that every stage puts between the brain and the answer, and learn which jobs must live in firmware
Two teams share a bench. The firmware team says: “Send clean data. The phone app stays simple.” The app team says: “Send raw data. We will filter it ourselves.” Both want the same outcome. They differ on one thing: who can still change their mind later.
The host is whatever receives the stream: a laptop, a phone, a recorder. A filter on the host can change tomorrow with a software update. A filter in firmware changes only when you reflash every board. And a filter, once applied, cannot be taken off. That is why the OpenBCI GUI always stores unfiltered data to file, even when it shows filtered traces on screen. The filters are a view, not the record.
The default rule: send raw, tag with flags, filter on the host. The raw stream from the ADS1299 is small. Each sample frame is 216 bits, which is 27 bytes: 3 bytes of status plus 8 channels of 3 bytes. At 250 SPS that is 27 × 250 = 6,750 bytes a second, or 54 kbit/s. That fits a Bluetooth LE link with room to spare.
Four jobs cannot wait for the host. Each one has a reason:
Everything else is host work: the choice between 50 and 60 Hz, the band-pass range, a notch whose width you want to tune per subject, and offline filtering that looks forward in time. A zero-phase filter runs a filter forward and then backward over a saved recording, so the delay cancels. It needs future samples, so it can only run offline. That is a strong reason to keep the raw data.
The delay from brain to host is a sum of small waits. Each stage has its own number, so draw them as one bar.
One bar, five stages. The white line is your budget. Switch the filter, pack more samples per packet, and slow the radio. Watch which stage grows.
Real: 27 bytes per frame and the 3 × tDR settling of the sinc3 filter (ADS1299 datasheet); filter delays from this lesson’s engine at 10 Hz; Bluetooth LE allows intervals from 7.5 ms. Illustrative: the host buffer (fixed 10 ms), the budget and the choice to count a full interval of radio wait. A model, not a measurement of any link.
Try the default. With the IIR, 8 samples per packet and a 15 ms interval, the total is about 6 + 0.3 + 28 + 15 + 10 = 59 ms. Packing is the biggest piece, not the filter. Cut the packet to 2 samples and you save 24 ms. That is a free win only if the radio can afford more packets, which costs power (the subject of the stream-it-reliably lesson). Switch to the FIR and the filter alone eats 80 ms.
If you do filter in firmware, do not lose track of what you did. Put a small config identifier in the stream header. It names the filter, its corner frequencies, and the firmware version. Months later, an analyst can undo or repeat it.
/* Stream header, sent at start and whenever the config changes. */ typedef struct __attribute__((packed)) { uint8_t fmt_ver; /* header layout version */ uint8_t adc_gain; /* 1,2,4,6,8,12,24 */ uint16_t sample_rate; /* 250 */ uint8_t notch_hz; /* 0 = off, 50 or 60 */ uint8_t notch_r_q8; /* pole radius, r * 256 */ uint8_t hp_corner_cHz; /* high-pass corner in 0.01 Hz units, 0 = off */ uint8_t flags; /* bit0 raw also sent, bit1 pop gate on */ uint32_t fw_git; /* firmware build id */ } stream_hdr_t;
The failure mode, in order. The symptom: a result nobody can reproduce, or a 50 Hz notch applied to data recorded in a 60 Hz country. The measurement: look for a peak at the other mains frequency, and check whether the header names a filter. The fix: raw-first, the header above, and a flag that says whether raw data was also sent.
For the packet format, counters and lost-packet recovery, see streaming EEG reliably. For the decoder that runs after these filters, see on-device decode and safety.
On real hardware. Board: an nRF52840 DK as the radio, or any BLE board, fed from an ADS1299 board. Repeat this: toggle a GPIO at the moment a sample is ready and another when the host app prints it, and measure the gap with a logic analyser or a scope while changing the packet size.
Chapter 8
Keep the numbers, the order of work and the core code on one page, and see where to go next
The whole lesson fits in one sentence. A biopotential channel records the brain plus everything else, so firmware first protects the data (window, contact, flags), then cleans only what it must (a notch, a high-pass), and keeps a raw copy so the cleaning can be redone. Every filter you add trades delay against ringing against damage, and you measure that trade on the bench, not by guessing.
| Quantity | Value | Source |
|---|---|---|
| Adult scalp EEG size | about 10 to 100 µV | Wikipedia, Electroencephalography |
| ADS1299 data rates | 250 SPS to 16 kSPS (250, 500, 1,000, 2,000, 4,000, 8,000, 16,000) | ADS1299 datasheet, Table 1 |
| Gain settings | 1, 2, 4, 6, 8, 12, 24 | ADS1299 datasheet |
| Full-scale input | ±VREF / gain, VREF 4.5 V, so ±187.5 mV at gain 24 | Datasheet; division is ours |
| One count at gain 24 | 22.35 nV (0.02235 µV) | Datasheet equation 8; OpenBCI Cyton docs |
| CMRR at 50 and 60 Hz | −110 dB minimum, −120 dB typical | ADS1299 datasheet |
| Input impedance | 1,000 MΩ at DC (500 MΩ with lead-off current on), 20 pF | ADS1299 datasheet |
| Noise, gain 24, 250 SPS | 0.14 µV RMS; 1 µV peak to peak in 0.01 to 70 Hz | ADS1299 datasheet, Table 4 |
| Converter bandwidth at 250 SPS | 65 Hz (−3 dB), so 50 and 60 Hz hum arrive | ADS1299 datasheet, Table 1 |
| Sinc3 settling | 3 × tDR, 12 ms at 250 SPS; notches at the data rate | ADS1299 datasheet |
| Lead-off currents | 6 nA, 24 nA, 6 µA, 24 µA; accuracy ±20% | ADS1299 datasheet |
| AC lead-off tones | 7.8 Hz or 31.2 Hz (fCLK / 218 or fCLK / 216), or fDR / 4 | ADS1299 datasheet, LOFF register |
| Status word | 24 bits: 1100, LOFF_STATP, LOFF_STATN, 4 GPIO bits | ADS1299 datasheet |
| Frame size, data rate | 216 bits (27 bytes); 6,750 bytes a second at 250 SPS | Datasheet; product is ours |
| Mains frequency | 50 Hz or 60 Hz; in continental Europe the target is adjusted by up to ±0.01 Hz so the daily average is exactly 50 Hz | Wikipedia, Utility frequency |
| Notch width and ring | width about (1 − r) fs / π; ring 1 / (−ln r) samples | Derived in Chapter 2 |
/* One ADS1299 frame (27 bytes) through the whole chain. Uses sx24, is_clipped, counts_to_uv, hp_step (Chapter 4-5) and CMSIS-DSP biquads (Chapter 2). Eight channels, 250 SPS. */ #include "arm_math.h" #define NCH 8 static arm_biquad_casd_df1_inst_f32 notch[NCH]; static float notch_state[NCH][4]; /* 4 values per stage, per the CMSIS doc */ static float notch_coef[5]; /* b0 b1 b2 a1 a2, plus-sign feedback */ static hp_t hp[NCH]; static float last_good[NCH]; void pipeline_init(float mains_hz) { notch_coeffs(mains_hz, 250.0f, 0.95f, notch_coef); for (int c = 0; c < NCH; c++) { arm_biquad_cascade_df1_init_f32(¬ch[c], 1, notch_coef, notch_state[c]); hp[c].a = 1.0f - 2.0f * 3.14159265f * 0.5f / 250.0f; /* 0.5 Hz corner */ } } void on_frame(const uint8_t f[27], float out_uv[NCH], uint8_t *flags) { uint32_t st = ((uint32_t)f[0] << 16) | (f[1] << 8) | f[2]; if ((st >> 20) != 0xC) { *flags |= 0x80; return; } /* framing lost: ask for a resync */ uint8_t loff_p = (st >> 12) & 0xFF, loff_n = (st >> 4) & 0xFF; *flags = (loff_p | loff_n) ? 0x01 : 0x00; /* any electrode off */ for (int c = 0; c < NCH; c++) { int32_t v = sx24(&f[3 + 3 * c]); float uv = counts_to_uv(v, 24.0f); if (is_clipped(v)) { uv = last_good[c]; *flags |= 0x02; } /* keep it out of the filter state */ else last_good[c] = uv; float y = hp_step(&hp[c], uv, 60.0f); if (hp[c].flag) *flags |= 0x04; /* pop */ arm_biquad_cascade_df1_f32(¬ch[c], &y, &out_uv[c], 1); } }
postShift.Now press Teach and explain one electrode, from memory: where its hum comes from, what a notch trades, why a pop smears, how the window clips, how the board asks for impedance, and which filters belong on the device. Then go back to the three-filter instrument at the top and see each trade for yourself.