On-Device Decode and the Rules of Medical Firmware

A tiny classifier on a chip reads brain signals four times a second and guesses what you intend. Learn how it decodes, and the safety rules that stop a wrong guess from hurting anyone.

Build the whole path from a stream of microvolt samples to a command, then wrap it in the isolation, risk and software-class rules that medical firmware must follow.

Watch the decoder alone for a few seconds and count its wrong commands. Switch on the safety gate. Then press Pop an electrode and see which setting survives. After that we build every piece from zero.

You need a feel for a signal that wiggles over time and a little C. We build the rest from zero, and we say plainly where a page is only a model of real hardware.

Built from primary sources: the ADS1299 datasheet, the BCI Competition IV dataset 2a description, an isolator application bulletin on IEC 60601-1, the FDA software premarket guidance and the sources listed in the Field Guide. Part of the Firmware from Zero to Expertise series.

Decode the intent, gate the command

1.0x

This is a model, not a recording. The two channels are synthetic (a 10 Hz rhythm that weakens during intent, plus noise), and the classifier is fitted in your browser on a separate synthetic run. Intent blocks last 2.8 s in every 8 s. Playback runs 3 times faster than real time.

Chapter 0

A Guess Every Quarter Second

See why a chip that reads a body must be built to survive its own mistakes

Picture a person in a powered wheelchair. They cannot use a joystick, so they wear a cap with electrodes. A small circuit board reads the faint electrical signals from their scalp. When the person imagines moving a hand, the board is meant to move the chair forward.

The board does not know what the person thinks. It sees numbers: 250 voltage samples every second, from each electrode, each one a few millionths of a volt. A short program turns a stretch of those numbers into one guess: go or stay. This is called decoding, and the program that makes the guess is a classifier: a function that takes numbers in and returns one label out.

Now count the guesses. This lesson’s decoder makes one every 0.25 seconds, so 4 a second, 240 a minute. Suppose it is right 9 times in 10. That sounds good. It also means about 24 wrong guesses every minute. Each one is a chance for the chair to move when nobody asked.

That arithmetic is the whole reason for this lesson. A decoder will be wrong. You cannot train that away completely, because the brain signal is faint, the electrodes slip and people get tired. So medical firmware has two jobs. The first is to guess well. The second is to make sure a wrong guess cannot hurt anyone.

Two halves of one lesson

The first half is on-device decode: how a small chip, with a few hundred kilobytes of memory and no operating system, turns a stream of samples into a command. We walk the stream, cut it into windows, measure one number that carries the intent, score it with a tiny classifier, and turn scores into steady commands.

The second half is the rules of medical firmware. Three questions drive it. Can the electrical parts hurt the patient? That is patient isolation, governed by the IEC 60601 family of standards. Can the software hurt the patient? That is the software lifecycle standard IEC 62304, with its safety classes A, B and C. And what does the firmware do when something fails? That is the safe state. A standard here means a document that experts agreed on, which regulators then use as a yardstick.

We name the standards but we do not give legal advice. The standards are paid documents, and an exact clause is a thing you read in your own licensed copy. We quote only what we could open in a primary or manufacturer source, and we say when a number is from a vendor note and not from the standard itself.

Feel the stakes first

The same wrong guess costs very different amounts in different products. Pick a product, then pick one of the four things a decoder can do. The read-out tells you what each costs.

Price every outcome

The grid is the decoder’s whole report card. Pick a product, then tap each outcome and read what it costs.

Illustrative. The consequences are written for teaching and are not a hazard analysis of any real product. A real one lives in the manufacturer’s risk file.

Notice what changed between the products. The decoder did not change. The cost of the third outcome changed, from a small annoyance to a person being hurt. That cost, not the accuracy, decides how much protection the product needs. Every rule in the second half of this lesson is a way of asking that question and writing down the answer.

The road ahead

  1. A stream becomes windows: samples, windows, hops and the delay they cost.
  2. One number carries the intent: band power, and how a chip measures it.
  3. A classifier small enough to read: two features, one line, one threshold.
  4. Fitting it into a chip: bytes, cycles and a fixed-point version.
  5. From score to steady command: smoothing, dwell and hysteresis.
  6. When the signal lies: artefacts and the validity gate.
  7. Patient isolation: leakage current, applied parts and the barrier.
  8. The standards map: IEC 60601, ISO 14971, ISO 13485 and friends.
  9. IEC 62304 software classes: A, B and C, and what each demands.
  10. The safe state: watchdogs, deadman timers and fault injection.
  11. Field Guide: numbers, a release checklist, the core code and sources.
A decoder is right 9 times in 10 and decides 4 times a second. What should a medical firmware engineer do first?

Chapter 1

A Stream Becomes Windows

Cut an endless stream of samples into pieces a classifier can judge, and pay the delay that costs

Your board has just booted. An ADS1299 chip (a 24-bit converter built for brain and heart signals, see the signal chain) pulls its DRDY pin low every 4 milliseconds. That pin means “a new reading is ready.” Your firmware answers by clocking in one frame over SPI, as the acquisition lesson showed.

For the 8-channel part, the datasheet says one frame holds 24 status bits plus 24 bits for each of 8 channels: 216 bits, which is 27 bytes. At 250 samples per second (SPS, the sampling rate) that is 27 × 250 = 6,750 bytes every second. The chip supports 250 SPS up to 16 kSPS. We use the slowest rate, because brain rhythms are slow and a slower rate leaves the processor time to think.

This endless run of frames is a stream. A single sample cannot tell you much. One reading of +4.2 microvolts says nothing about whether a rhythm is strong or weak. A rhythm is a pattern over time. So we need a stretch of samples.

The window

A window is the most recent N samples of the stream, held in a buffer. Think of reading a long scroll through a card with a rectangular hole. You can only see what sits in the hole. You decide from that piece, then slide the card along.

How long should the window be? The signal we want to measure is a rhythm near 10 Hz, so one cycle lasts 100 ms, or 25 samples. You need several cycles to judge its strength. A 1-second window holds about 10 cycles. There is a second reason, and it is exact. A window of T seconds can only separate frequencies that differ by about 1/T hertz. A 1-second window gives 1 Hz resolution. A 0.5-second window gives 2 Hz. A shorter window blurs the rhythm into its neighbours.

So a longer window is more accurate. It is also slower. That is the first trade-off of this lesson, and the device below lets you feel it.

The hop

We do not wait for a whole new window before deciding again. We slide the window forward by a fixed step called the hop. With a 1-second window and a hop of 62 samples (0.248 s), each new window shares 188 of its 250 samples with the last one. That is 75% overlap. Overlap gives a fresh decision four times a second while keeping a full second of evidence behind each one.

Each hop costs work. The firmware must measure the window, score it and update the command. If that work takes longer than the hop, the stream backs up and samples are lost. So the hop sets a deadline for your code. Here the deadline is 248 ms, which is very generous for a chip running at tens of megahertz.

The delay

Latency here means the time from the brain changing to the command changing. It has four parts. The first is the window itself. When the person begins to imagine a movement, the window still holds mostly old samples. The measured rhythm only crosses the decision line when about half the window is new. That costs about W/2. The second is the wait for the next hop, on average hop/2. The third is the compute time. The fourth is any extra confirmation you add on purpose, which Chapter 5 calls dwell.

Add them up for our defaults. The window is 1.00 s, so W/2 = 0.50 s. The hop is 0.248 s, so hop/2 = 0.12 s. Compute is about 4 ms. Dwell is 3 hops, so two extra waits of 0.248 s add 0.50 s. The total is 0.50 + 0.12 + 0.004 + 0.50 = about 1.1 seconds. This is a rule of thumb, not a law. The simulated rhythm also takes 0.4 s to fade, so the device below reads a little higher. It measures the real delay in the simulation, so you can compare.

One second feels slow. It is slow, and that is a real property of brain-computer interfaces that use this kind of rhythm. A movement imagined in the brain is a slow event. The public BCI Competition IV dataset 2a, for example, asks each person to imagine a movement for several seconds: the cue shows at 2 s, stays 1.25 s, and the person keeps imagining until 6 s.

Slide the window, measure the delay

The blue ribbon is the true intent. Each tick is one decision. The warm bracket is the window that first said go. Change the window and the hop and watch the delay and the memory move.

1.00 s
0.25 s

Synthetic data, two channels at 250 SPS. Delay is the mean time from intent onset to the third go decision in a row, over 8 blocks, with a classifier refitted for each window length. Memory counts two float32 channels. Your own head and cap will differ.

Two things to try. Drag the window down to 0.5 s: the delay falls, but the decoder starts to miss and to guess wrong, because the evidence is thin. Then drag the hop up to 0.5 s: the processor gets more time per decision, but the command arrives late and in coarse steps. There is no setting that is best at everything. You pick a point on a curve, and you write down why.

A 1 s window slides by 62 samples at 250 SPS. How many samples do two neighbouring windows share?

Chapter 2

One Number Carries the Intent

Measure the strength of one rhythm in a window with a loop that fits in a few lines of C

Look at two seconds of EEG from a person at rest and two seconds from the same person imagining a hand movement. To the eye they look the same: a fuzzy line wandering around zero. The difference is hidden in how big one particular wiggle is.

Over the part of the brain that controls movement, a steady rhythm near 10 Hz appears when you are still. It is called the mu rhythm. Reference sources give its range as about 7.5 to 12.5 Hz, with most of the energy between 9 and 11 Hz, and describe an adult’s stable value as 8 to 13 Hz. When you move, or imagine moving, that rhythm gets weaker. The weakening has a name: event-related desynchronization, or ERD. “Desynchronization” means the many neurons that were pulsing together stop doing so, and their shared rhythm fades.

So the signal we want is not a shape. It is a size. A movement-imagery decoder asks one question: how strong is the 8 to 13 Hz rhythm over the motor cortex right now? Strong means rest. Weak means intent.

Power: the size of a wiggle

To measure the size of a signal that swings both positive and negative, we cannot just add the samples. They would cancel to about zero. Instead we square each sample, which makes everything positive, and average. The result is the power. For a pure sine wave of amplitude A, the power is A²/2 per sample, so power tracks the amplitude squared. Halve the amplitude and the power falls to a quarter.

Band power means the power of only one slice of frequencies, here 8 to 13 Hz. To get it you must split the signal by frequency. The textbook tool is the Fourier transform, which asks for each frequency: how much of this sine wave is hiding in my samples? It does this by multiplying the window by a test sine and cosine at that frequency and adding up the result.

Goertzel: one frequency, almost for free

A full FFT finds every frequency. We need six: 8, 9, 10, 11, 12 and 13 Hz. There is a cheaper tool for that, the Goertzel algorithm. It computes one Fourier value using a short recurrence with two numbers of state. For each new sample x it does one multiply and two adds:

s[n] = x[n] + c · s[n−1] − s[n−2], with c = 2 cos(2π f / Fs)

After all N samples, the power at frequency f is s1² + s2² − c · s1 · s2, where s1 and s2 are the last two states. Multiply by (2/N)² to get a number in microvolts squared: a sine of amplitude A then gives exactly A². The loop has no table and no complex numbers, which suits a small chip. Six frequencies on a 250-sample window cost 1,500 multiply-accumulates per channel.

c/* power of one frequency in a window, microvolts squared. x: samples already in uV. */
static float goertzel_power(const float *x, int n, float f_hz, float fs_hz) {
    const float c = 2.0f * cosf(6.2831853f * f_hz / fs_hz);
    float s1 = 0, s2 = 0;
    for (int i = 0; i < n; i++) {
        float s0 = x[i] + c * s1 - s2;        /* one multiply, two adds */
        s2 = s1; s1 = s0;
    }
    float p = s1 * s1 + s2 * s2 - c * s1 * s2;   /* |X(f)|^2 */
    return p * (2.0f / n) * (2.0f / n);              /* sine of amplitude A gives A^2 */
}

A worked example, step by step

Take a clean 10 Hz sine of amplitude 9 microvolts in a window of N = 250 samples at 250 SPS. The window lasts 1 second, so 10 Hz lands exactly on a Fourier bin. The Fourier value has size A × N/2 = 9 × 125 = 1,125. Squared that is 1,265,625. Multiply by (2/250)² = 0.000064 and you get 81, which is 9². Good: the formula gives back the amplitude squared.

Now let ERD halve the amplitude to 4.5 microvolts. The same steps give 20.25. Power fell from 81 to 20.25, a factor of 4.

Firmware does not use that raw number. It takes the natural logarithm. ln 81 = 4.39 and ln 20.25 = 3.01. The difference is 1.386, which is ln 4. The log turns “four times smaller” into a plain subtraction, and that difference stays the same whether your electrode is a little loud or a little quiet. It also makes the spread of values closer to a bell curve, which the classifier in Chapter 3 likes. We average the six bins first, then take the log. That is our feature: one number per channel per window.

One more step comes before all of this. Electrodes carry a steady offset many times larger than the signal. We subtract the window mean first, which costs N adds. Skip it and the offset leaks into every frequency bin.

See the rhythm weaken

Bars show the average power at each frequency from 1 to 40 Hz, for channel C3. The purple band is the 8 to 13 Hz slice the decoder measures. Switch between rest, intent and both.

1.0x

Synthetic C3 channel: a 10.2 Hz rhythm of 9 microvolts at rest that loses half its amplitude during intent, plus noise. Each bar averages 10 whole-state windows of 1 s. The band numbers are measured from those windows.

Now the failure mode. A team trains a decoder on Monday and it works. On Tuesday, with a freshly placed cap, it is useless. The symptom: the decoder says go almost all the time. The measurement: the average log-power at rest has shifted by 0.8, because the skin contact is different, and the classifier’s fixed line now sits on the wrong side of the data. The fix: record a short rest calibration at the start of every session and re-centre the feature before scoring. Band power is a size, so anything that changes the size of every signal, not just the rhythm, will move it.

ERD halves the amplitude of the 10 Hz rhythm. By what factor does its band power fall?

Chapter 3

A Classifier Small Enough to Read

Turn two band-power numbers into one score with a straight line you can print on a page

Each window now gives two numbers: the log band power at electrode C3 and at electrode C4. These are two spots over the left and right motor cortex. Plot every window as a dot, with C3 on one axis and C4 on the other. The rest windows form a cloud. The intent windows form a second cloud, shifted toward lower power. The clouds overlap a little, because the brain is noisy.

A classifier is a rule that says which cloud a new dot belongs to. The simplest rule is a straight line. Dots on one side get the label go, dots on the other side get stay. This is a linear classifier. It is small enough to print on one page: three numbers.

Where the line comes from

We want the line that separates the clouds best. Linear discriminant analysis, or LDA, gives one in closed form, with no training loop. It uses only averages and spreads.

  1. Average each cloud. μ0 is the mean dot of the rest windows. μ1 is the mean dot of the intent windows.
  2. Measure the spread. Σ is the covariance of the dots around their own cloud centres, pooled over both clouds. It says how wide the clouds are and which way they lean.
  3. Find the direction that separates the centres relative to the spread. w = Σ−1(μ1 − μ0). A direction along which the clouds are wide gets a small weight. A direction along which they are narrow gets a large one.
  4. Put the line half way between the centres. b = −½ w · (μ0 + μ1).

The score of a new dot f is then s = w · f + b. A positive score means closer to the intent cloud. If the clouds are bell-shaped with equal spread and equal frequency, s is exactly the log-odds of intent, and the probability is 1 / (1 + e−s). Those are strong assumptions, so treat the probability as a rough guide, and not as a promise.

A worked example, every step

Use toy numbers, labelled illustrative. Rest centre μ0 = (2.5, 2.5). Intent centre μ1 = (1.4, 2.0). Say the two features are independent, with variances 0.16 for C3 and 0.25 for C4, so Σ is a diagonal table.

Step 1, the direction. Subtract the centres: (1.4 − 2.5, 2.0 − 2.5) = (−1.1, −0.5). Divide each by its variance: w = (−1.1 / 0.16, −0.5 / 0.25) = (−6.875, −2.0). Both weights are negative, because lower power means intent. C3 gets the bigger weight, because C3 carries the stronger and cleaner change.

Step 2, the offset. Add the centres: (3.9, 4.5). Then w · (3.9, 4.5) = −26.8125 − 9.0 = −35.8125. Half of the negative is b = +17.906.

Step 3, score a new window with features f = (1.6, 2.3). s = −6.875 × 1.6 − 2.0 × 2.3 + 17.906 = −11.0 − 4.6 + 17.906 = 2.306. The probability is 1 / (1 + e−2.306) = 1 / (1 + 0.0997) = 0.909. The decoder is fairly sure of go.

That is the whole model. Three numbers (w0, w1, b), two multiplies and two adds per decision. On a Cortex-M4 that is a few dozen cycles. The hard part is not running it. The hard part is knowing when to trust it.

The threshold is a dial on the cost of mistakes

We said go when s > 0. Nothing forces that. Say go only when s > 2, and the decoder fires less often. It misses more real intents, but it makes fewer false ones. Say go when s > −1, and the opposite happens. The threshold moves the line parallel to itself, and it trades two kinds of error:

Chapter 0 told you which error costs more. For a wheelchair, a false go is the dangerous one. You will want a high threshold, and you accept a decoder that sometimes needs a second try.

Move the line, price the mistakes

Each dot is a 1 second window the classifier never saw during fitting. Filled dots are rest. Rings are intent. Dots on the warm side of the line get go. Drag the threshold.

0.00

Synthetic data. The line is fitted by LDA in your browser on a 160 s calibration run (seed 7). The dots come from a separate 160 s run, so the numbers are honest held-out numbers for this model of the signal, not for a real person.

Two failure modes deserve names. The first is a trap in the metric. Intent is on only 35% of the time in our run. A decoder that always says stay is right 65% of the time and does nothing useful. Accuracy hides this, so quote sensitivity and false-go rate together. The second is overfitting: a model that scores 99% on the data it was fitted to and 80% a week later. The symptom is a gap. The measurement is to hold back a separate run, or a separate day, and score it only once. The fix is a simpler model or more data.

You may wonder about deep learning. A compact convolutional network such as EEGNet (Lawhern and colleagues, arXiv:1611.08024) was designed for several kinds of EEG-based interface and for small training sets. It can replace the two features and the line. On a chip it brings the memory and quantisation questions of running a network on a Cortex-M. The next chapter counts those costs for our small model, and the same method applies to a bigger one.

You raise the threshold on a wheelchair decoder from 0 to +2. What happens?

Chapter 4

Fitting It Into a Chip

Count the bytes and cycles of the whole decoder, then shrink the arithmetic to whole numbers

You have a working idea on a laptop. Now you must put it on a board the size of a matchbox, powered by a small battery, with no operating system to lend you memory. Before you write code, you do arithmetic. Two questions decide whether it fits: how many bytes, and how many cycles?

Three real parts make good yardsticks. The Nordic nRF52840 is a Cortex-M4 with a floating-point unit at 64 MHz, with 1 MB of flash and 256 KB of RAM. The ST STM32L476RG is a Cortex-M4F at up to 80 MHz with 1,024 KB of flash and 128 KB of SRAM. The ST STM32F401RE runs at 84 MHz with 512 KB of flash and 96 KB of SRAM. Flash holds your program and constants and survives power-off. SRAM holds your variables and buffers and is lost at power-off. SRAM is the scarce one.

Bytes: the window buffer

The window buffer is the biggest item. Its size is channels × samples × bytes per sample. The ADS1299 delivers 24-bit samples, which do not fit a 16-bit word, so the usual choices are a 32-bit integer or a 32-bit float, both 4 bytes. For 2 channels and a 250-sample window that is 2 × 250 × 4 = 2,000 bytes. For all 8 channels it is 8,000 bytes. On a 128 KB part, 8,000 bytes is 6% of the memory. That is fine. A longer window, a wider network or a second buffer for the radio changes the picture quickly.

The buffer is a ring buffer: an array where the write position wraps from the end back to the start, so the newest N samples are always there and nothing is copied. A DMA engine (the driver lesson covers the pattern) fills it in the background while the processor sleeps.

Cycles: the work per hop

A cycle is one tick of the processor clock. At 64 MHz there are 64 million per second. The decoder must finish its work inside one hop, 248 ms, or about 15.9 million cycles. Count what the work needs, per channel:

  1. Remove the mean. About 2 cycles per sample: 500 cycles.
  2. Goertzel for 6 bins. The Cortex-M4 has a single-cycle 32-bit multiply-accumulate; with loads and loop work we assume about 4 cycles per sample per bin: 6 × 250 × 4 = 6,000 cycles.
  3. Finish the bins. A few dozen cycles each: about 200.

Two channels cost about 2 × 6,700 = 13,400 cycles. The log of each feature and the classifier add roughly 200. Call it 13,600 cycles. At 64 MHz that is 0.21 ms. The hop is 248 ms. The processor is busy for 0.09% of the time and asleep for the rest. These cycle counts are our estimate; the device below lets you vary them, and the real number comes from a measurement, not a guess.

That result is a surprise to most newcomers, and it is the main lesson of this chapter. For a band-power decoder, compute is not the bottleneck. The cost sits in the other places: the SPI transfer of each frame (216 bits, which at a 4 MHz clock take 54 microseconds, a clock rate we picked for illustration), the radio, and the time the chip spends awake. Good firmware sleeps between hops and lets the DMA and the ADC’s DRDY line wake it.

Budget the decoder

Pick a chip and a sample format, then change the channels, bins and window. The top bar is RAM. The bottom bar is the share of each hop the processor is busy.

2
6
1.0 s

Clock speeds and memory sizes are from the part pages (nRF52840 product page, STM32 family table). Cycle costs (2 per sample for the mean, 4 per sample per bin) and the 32 KB reserved for other firmware, 2 KB for the stack and 256 B of decoder state are illustrative assumptions.

From floats to whole numbers

The nRF52840 and both STM32 parts above have a single-precision floating-point unit, so float code is fast there. A smaller core, such as a Cortex-M0+, has none. Float maths then runs in software and is much slower. Medical firmware also likes arithmetic you can bound exactly. So many teams use fixed point: whole numbers with an agreed scale.

The idea is to pick a scale, here 4,096 (212, called Q12), and store x as round(x × 4096). The classifier from Chapter 3 becomes: w0 = round(−6.875 × 4096) = −28,160, w1 = −8,192, b = 73,344. The features f = (1.6, 2.3) become 6,554 and 9,421. Multiply and add in a 32-bit integer: −28,160 × 6,554 + −8,192 × 9,421 = −261,737,472. That is inside the 32-bit limit of about 2.1 billion. Shift right by 12 to remove the extra scale: −63,901. Add b: 9,443. Divide by 4,096 for a reader: 2.3054. The float answer was 2.3060. The error is 0.0008, far below any threshold we use.

Notice what we had to check: that the product cannot overflow. If a feature could reach 100 instead of 2.3, the product would pass 2.1 billion and wrap to a wrong, possibly opposite, number. That bug gives no error message. It simply flips a stay into a go. So fixed-point code needs a stated range for every value and a test at the edges. Chapter 10 returns to this as a reason for range checks.

The failure story for this chapter is a classic. A developer puts float window[2][250] as a local variable inside the function that handles the new window. That is 2,000 bytes on the stack. The code works on the bench. In the field, an interrupt arrives while the function runs, the stack grows past its limit, and the chip hits a hard fault. The symptom is a random reset. The measurement is the stack high-water mark. The fix is a static buffer and a memory-protection guard, as in the stack, heap and MPU lesson. If you want to go on to int8 networks, see INT8 in firmware.

For the band-power decoder on a 64 MHz Cortex-M4F, what takes most of the energy and time budget?

Chapter 5

From Score to Steady Command

Turn a jittery score into a command that starts slowly, stops fast and never stutters

The classifier gives a score four times a second. Plot those scores and you see a line that wobbles around the threshold. Wire it straight to a motor and the chair twitches: go, stay, go, go, stay. The decoder is not broken. Its evidence is noisy and neighbouring windows overlap, so the score hovers near the line whenever the brain is undecided.

The fix is a small state machine between the score and the actuator. It has three tools, each with an everyday picture.

  1. Smoothing. Blend each new score with the running value: y = y + α(s − y). With α = 0.5, each new score counts for half. It is a low-pass filter. Think of a heavy flywheel: a quick bump barely moves it.
  2. Dwell. Require D scores in a row above the threshold before the command turns on. It is like a lift button that needs a firm press: one accidental brush does nothing.
  3. Hysteresis. Use two thresholds. Turn on above ton, turn off only below toff, with toff lower. The band between them is a dead zone where the state does not change. A thermostat does the same so the heater does not click on and off at exactly 20 degrees.

A worked example, sixteen hops

Take these illustrative scores, one per hop, four seconds in all. Hops are counted from 0, so the first score is hop 0: −1.2, 0.4, −0.3, 0.8, 1.2, 0.9, 1.5, −0.2, 1.0, 1.4, 1.1, −0.6, −1.0, −0.8, 0.3, −0.9. The person truly intends from hop 3 to hop 10.

Rule A: go when the score is above 0. The states are 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0. The command flips 8 times. It has a false go at hop 1 and another at hop 14, and a dropout in the middle of the real intent at hop 7.

Rule B: add a dwell of 3, so the command turns on after three scores above 0 in a row, and turns off the moment a score is not above 0. Now the command turns on at hop 5 and off at hop 7, then on at hop 10 and off at hop 11. It flips 4 times. The false go events are gone. The cost is a delay: the real intent began at hop 3 and the command arrived at hop 5, two hops late. Then it was lost at hop 7 for one weak score.

Rule C: dwell of 3, turn on above 0.5, turn off only below −0.5. The command turns on at hop 5, stays on through the weak score at hop 7, and turns off at hop 11. It flips twice, once each way. The dwell cost the same two hops of delay at the start. The score of −0.2 at hop 7 fell inside the dead zone and was ignored.

Slow to start, fast to stop

Look at which direction each tool delays. Dwell delays the start. Hysteresis keeps the command on through weak scores, which delays the stop. In a safety design these are not equal. Starting late costs a moment of patience. Stopping late can cost an injury. So medical firmware makes the two directions asymmetric: it is slow and careful to start, and quick to stop. In practice that means a few rules:

Chapter 10 pushes this one step further: the stop must also work when this code has crashed.

c/* One step of the command state machine, called once per hop (about 4 Hz). */
typedef struct { bool on; uint8_t run; float y; } cmd_t;

bool cmd_step(cmd_t *c, float score, bool data_ok,
              float alpha, float t_on, float t_off, uint8_t dwell) {
    c->y += alpha * (score - c->y);                 /* smoothing */
    if (!data_ok || c->y < t_off) {                 /* fast stop: no dwell on the way down */
        c->on = false; c->run = 0;
    } else if (!c->on) {                              /* slow start: dwell above t_on */
        c->run = (c->y > t_on) ? c->run + 1 : 0;
        if (c->run >= dwell) c->on = true;
    }
    return c->on;
}

Tune the gate on a real-looking run

The warm line is the decoder score, one point per hop, over 40 seconds. The blue ribbon is the true intent. The strip below is the command. Red marks a command with no intent behind it.

0.00
0.00
1 hop
1.0

Synthetic scores from the Chapter 3 classifier on a 40 s test run (5 intent blocks). A command counts as right if some intent occurred in the 1 s before it started. A block counts as missed if no command overlaps it. Delay is onset to command start, averaged.

Try these. Start at the defaults (no dwell, no hysteresis, no smoothing): count the red marks. Raise the dwell to 3 and watch them fall. Raise the hysteresis gap and see the command stay on through short dips. Then push the dwell to 6: the red marks vanish, but the delay grows and the decoder starts to miss whole blocks. The same dial that buys safety costs usability, and you cannot buy one without paying the other.

A wheelchair decoder is tuned to be calm. Which design is right for the stop path?

Chapter 6

When the Signal Lies

Catch bad input before the classifier turns it into a confident, wrong command

The wheelchair user turns their head, and the cap shifts. One electrode lifts off the scalp. The amplifier now sees an open wire, which carries almost no 10 Hz rhythm at all. Your decoder measures the band power, finds it tiny, and decides that the mu rhythm has collapsed. That is exactly what intent looks like. So it says go, and it says it with a very high score.

This is the most important failure in the lesson, so read it twice. A classifier does not know what a good signal looks like. It knows only the two clouds it was fitted on. Any input, however absurd, lands somewhere on the plane, and the classifier answers. A dead electrode lands far on the intent side. The farther from the line, the more confident the answer. Confidence is not validity.

Validate first, decode second

The cure is a validity gate: a set of cheap checks on the raw window, run before the classifier, that answer one question. Is this window the kind of data the decoder was built for? If the answer is no, the decoder does not run and the command goes to its safe value. Think of a pilot who checks the instruments before trusting the autopilot.

The first line of defence lives in hardware. The ADS1299 has lead-off detection: it can drive a small excitation current through each electrode connection and watch for a change that means the wire is open. The result comes back in the 24 status bits at the front of every frame, as two fields called LOFF_STATP and LOFF_STATN, one bit per input. Read them every frame. They are free, and they tell you about the electrode itself, not about a guess from the numbers.

The second line is software. These checks run on the window and catch faults the chip cannot see:

  1. Flat line. After removing the mean, the window’s root-mean-square value is tiny. The amplifier’s own noise is about 1 microvolt peak to peak (a datasheet figure, for a 70 Hz bandwidth); a connected electrode on skin shows tens of microvolts. Our gate calls anything under 1.5 microvolts rms flat.
  2. Stuck code. Every sample in the window has the same raw value. The ADS1299 output clips at 7FFFFFh for a positive input beyond full scale and at 800000h for a negative one, so a saturated channel repeats one code. This also shows as a flat line, but you want the separate message “saturated,” since the repair differs.
  3. Big swing. The window’s peak-to-peak value exceeds 110 microvolts, far more than a mu rhythm can make. A blink or a cable tug does this.
  4. Muscle noise. Power between 35 and 55 Hz is high. Jaw and neck muscles make broadband noise that brain rhythms do not.

All four use numbers you already compute. The mean and the min and max cost one pass over the window. The muscle check reuses the Goertzel loop from Chapter 2 at a few higher frequencies.

The price of a strict gate

The gate is not free. Every rejected window is a decision the decoder does not make. A blink lasts about a third of a second yet spoils a whole 1-second window, and, because windows overlap, several hops. If the gate is too strict, the decoder is deaf for much of the time and the user cannot drive. If it is too loose, a bad window gets through. Set the limits from data, and then watch the rejection rate in the field. If more than a fifth of windows are rejected, the cap needs fixing, not the code.

The rejection is also information to show. A lit “check electrodes” indicator turns an invisible fault into a visible one, and a user who sees it will adjust the cap.

Break the input, watch the verdict

The window below comes from a person at rest, so the right answer is stay. Pick a fault to inject, then switch the gate on and off.

Synthetic window, scored by the Chapter 3 classifier. Fault sizes are illustrative: a 140 microvolt blink bump, 45 microvolts rms of muscle noise, a flat 0.25 microvolt line, and a constant full-scale code. Gate limits are the four listed above. Real faults vary a great deal.

Here is the failure story in the usual three beats. Symptom: during a long session the chair creeps forward by itself for about a second, once or twice an hour. Measurement: the log shows each event began with a window whose rms was under 1 microvolt, and the score was above +6. Fix: add the flat-line check and the lead-off bits to the gate, make the gate force the command off, and add a counter for rejected windows so the event is visible in the next log.

One more thought for later chapters. The gate itself is software. If the gate has a bug, you have no gate. For anything that can hurt a person, a good design adds a barrier that does not depend on this code at all. Chapters 9 and 10 explain why standards ask for that.

An electrode comes off the scalp. Why can the decoder fire go with a very high score?

Chapter 7

Patient Isolation

Keep a fault in the wall socket from finding a path through the person wearing your board

Your board has two lives. On the bench it streams to a laptop over USB. The laptop plugs into the wall. Meanwhile a person wears the cap, and the cap’s electrodes connect to the board’s analog input. Follow the wires: person, electrode, board ground, USB cable, laptop, mains. You have just built a path from a human body to the mains supply, and it is made of ordinary parts doing their job.

Most of the time nothing happens. The danger is the day a fault appears elsewhere, for example a worn laptop charger that puts a fraction of mains voltage on its output ground. Now there is a voltage along your path, and what moves through the body is a current. Current, not voltage, is what a body feels. At small values you notice a tingle. At larger values muscles seize. So the design question is how to make sure the current through the patient stays tiny, even when something else has failed.

Leakage current, and why the barrier is a capacitor

Patient leakage current is the current that can flow from the part touching the patient to earth. The cure is to isolate the patient side: build a barrier that blocks direct electrical connection between the patient-side circuit and everything else, while letting signals and power cross by other means. Signals cross as light or as magnetic fields. Power crosses through a transformer.

No barrier is perfect. Two conductors facing each other across a gap always form a small capacitor. A capacitor passes alternating current. The current it passes follows a simple law:

I = 2π × f × C × V

Here f is the mains frequency, C the capacitance across the barrier and V the mains voltage. Work it for a European supply (230 V, 50 Hz) and a barrier of 100 picofarads, a plausible order of size for a transformer plus several isolators. 2π × 50 × 100×10−12 × 230 = 7.2 microamps. Make the barrier ten times larger, 1 nanofarad, and the current is 72 microamps. Make it ten times smaller and it is 0.72 microamps. The current scales in a straight line with C, so every extra picofarad you add is a small tax on safety. This is a model for intuition. The standard defines exact test set-ups and measuring networks, and a real test replaces this arithmetic.

Applied parts and the limits

IEC 60601-1 is the general standard for the basic safety and essential performance of medical electrical equipment. Any part that touches the patient on purpose is an applied part. The standard sorts applied parts into three types by how well they are isolated and where they may touch the body.

Reported patient leakage limits, in normal condition and with a single fault, are 100 and 500 microamps for types B and BF, and 10 and 50 microamps for type CF. A single fault condition means one protective measure has failed or one abnormal state has occurred. The standard requires the device to stay safe even then. That idea is the heart of the whole standard: not “nothing will break” but “when one thing breaks, the patient is still safe.”

Which type your product claims is a decision made in the product’s risk file, together with the particular standard for its kind of equipment. For EEG equipment the family has a particular standard, IEC 60601-2-26. We do not claim here which type an EEG cap must be.

Size the barrier

Pick a mains supply and a part type. Drag the barrier capacitance. The bar shows the leakage current on a log scale against the limits.

100 pF

Model for intuition: I = 2 pi f C V, a mains-voltage source behind a plain capacitor. IEC 60601-1 defines its own test circuits and measuring networks. Limits are the manufacturer-note figures for patient leakage, normal and single fault. Check the licensed standard for any real design.

Means of protection, creepage and clearance

The standard counts protection in “means.” One means of patient protection (MOPP) is one layer of insulation or other barrier that protects the patient. A circuit that touches a patient often needs two such means, so that a single failure still leaves one. A means of operator protection (MOOP) protects the person operating the equipment and has smaller numbers. The table gives a vendor’s summary for a 250 V working voltage.

ProtectionTest voltageMinimum creepage
1 MOOP1,500 V rms2.5 mm
2 MOOP3,000 V rms5 mm
1 MOPP1,500 V rms4 mm
2 MOPP4,000 V rms8 mm

Source: NVE application bulletin AB-2, a vendor note that summarises the standard. Other vendor notes add a minimum clearance of 5 mm for 2 MOPP at 250 V working. Two definitions: creepage is the shortest path along a surface between two conductors, as a spark or contamination would crawl. Clearance is the shortest path straight through air.

Two details in that note matter to a layout engineer. First, IEC 60601 does not allow interpolation: you cannot pick a creepage between two table rows. Second, exposed metal on the package is subtracted from the creepage. The note says the tie bar of an ordinary package takes off about 0.5 mm, so a package with about 8.1 mm between pins gives about 7.4 mm. That is why isolators for 2 MOPP come in special wide packages.

How the barrier is built on an EEG board

Two things must cross the barrier. Signals: the SPI lines to the ADS1299 (SCLK, DIN, DOUT, CS), the DRDY line and any START or reset lines. These pass through digital isolators. Power: the ADS1299 needs an analog supply of 4.75 to 5.25 V and a digital supply of 1.8 to 3.6 V, from the datasheet. These come from an isolated DC-DC converter whose transformer carries energy but no direct connection. A battery-powered board that streams by radio removes the wire to the mains-powered computer, and the radio is a barrier by itself. While the battery charges from USB, that wire returns, and the design must handle it.

Now the failure story. Symptom: the design passes the bench tests but fails the high-voltage test, arcing at 4,000 V. Measurement: the arc marks show it jumped across the board under the isolator. Fix: a ground pour from the MCU side ran under the isolator and came within 1 mm of the patient side. Cut a keep-out gap, and in a bad case a milled slot, across the full width of the barrier.

Why do leakage numbers grow when you add isolators and converters across the barrier?

Chapter 8

The Standards Map

Learn which document answers which question, and how a hazard becomes a requirement and a test

You finish the isolation design and a colleague asks, “Is that covered by 62304?” You pause. Standards have confusing names, and a newcomer can drown in the numbers. The trick is to stop memorising numbers and ask of each document: what question does it answer?

A standard is a written agreement among experts on how to do something. Following it is usually voluntary in law, but a regulator such as the US Food and Drug Administration (FDA) or an EU notified body uses recognised standards as a yardstick for whether a device is safe enough. So in practice a standard is a shared checklist of what “good” means, and a way to show a reviewer that you did it.

Eight documents, eight questions

Two more words, in plain terms. Basic safety is freedom from unacceptable risk caused by the equipment’s own hazards, such as shock or fire. Essential performance is the performance of a function whose loss or degradation would itself cause unacceptable risk. For a wheelchair decoder, “the command is off when the data is invalid” is a good candidate for essential performance. Deciding which functions are essential is a job for the risk file, not for this lesson.

The thread that ties them: a hazard becomes a test

ISO 14971 gives the process in outline. You list the hazards, which are sources of possible harm. You describe a hazardous situation, where a person is exposed to the hazard. You estimate the harm and how likely and severe it is, and decide whether the risk is acceptable. If it is not, you reduce it. The standard gives an order of preference for risk controls: first design the hazard out, then add protective measures such as guards, interlocks or alarms, and only then use information such as warnings and training. Then you check what risk is left and keep watching after release.

Run our decoder through it. The hazard is unintended motion. The hazardous situation is a dead electrode producing a confident go (Chapter 6) while the chair is moving near people. The harm is a collision. The controls, in the preferred order: a motor-current and speed limit in hardware that the decoder cannot override (design the hazard smaller); the validity gate and a deadman timeout (protective measures); a warning in the manual (information). Each control gets a requirement, and each requirement gets a test, such as “with the electrode removed, the command is off within 300 ms, 20 trials out of 20.” That chain, hazard to control to requirement to test, is called traceability, and it is what an auditor will look for.

The regulators ask for it too. The FDA’s June 2023 guidance on premarket submissions for device software functions splits submissions into a Basic and an Enhanced documentation level. Enhanced applies when a failure or flaw of any device software function could present a hazardous situation with a probable risk of death or serious injury, judged before risk controls are counted. The guidance also says to consider the chance that the device is compromised by weak cybersecurity. And it names a Declaration of Conformity to the FDA-recognised version of IEC 62304 as one way to cover development practices. Read the guidance itself for the details: it is free.

Which document answers this?

Read the question. Tap the document that answers it. You get one try on each of the eight cards.

The mapping of questions to documents follows the scope lines in the sources listed in the Field Guide. A real project reads each licensed standard for the exact clauses.

The failure story is common in young teams. Symptom: an audit asks “why is the dwell 3 hops?” and nobody can say. Measurement: a search of the design documents finds the number in code and nowhere else. Fix: every safety-relevant constant gets a line in the risk file with the hazard it serves and the test that checks it. Fixing the number would be easy. Showing why it is right is the real work.

A team lists hazards, estimates harm, picks controls and checks the leftover risk. Which document is the process from?

Chapter 9

IEC 62304 Software Classes

Work out how much process your code must carry, and see how a hardware limit can lower the bar

Two teams write firmware that moves a motor. One writes a toy robot arm for a classroom. The other writes the controller for a powered wheelchair. Should both teams keep the same pile of review records, test plans and design documents? Obviously not. The toy needs little. The chair needs a lot. IEC 62304 turns that common sense into three levels.

The standard is called Medical device software: software life cycle processes. It says how to plan, build, test, release, maintain and fix software for a medical device. The rule that sets how much of it applies to you is the software safety class: A, B or C.

The three classes

Since Amendment 1 (2015) the class depends on what harm the software could still cause after risk controls outside the software are counted. In plain words:

Notice what is missing: probability. Amendment 1 does not let you argue that a failure is rare. For classification, treat the chance that the software fails as certain, then ask how bad the result would be. This is stricter than it sounds, and it is on purpose: nobody can measure the true failure rate of software with confidence.

What each class asks of you

The more severe the class, the more activities you must do. One summary of the standard lists them like this. Class A needs software requirements (clause 5.2) and software release (5.8), and, since Amendment 1, system tests. Class B adds the software architecture (5.3) and verification (5.5 to 5.7). Class C adds detailed design (5.4). The development lifecycle itself runs through planning, requirements analysis, architectural design, detailed design, unit implementation and verification, integration and integration testing, system testing, and release. Around it sit maintenance, risk management, configuration management and problem resolution.

Two more rules shape real firmware. The first is segregation. Parts of the software may carry different classes only if you can justify that they are separated, with weak or no coupling between them, and the justification comes from the architecture. Calling a function in another module, inheriting from it, or catching its exceptions all count as coupling. Without that justification, the highest class applies to the whole system. So firmware engineers put the safety gate and the stop path in one small module, with its own memory region and few dependencies. Then only that module carries the heavy process, and the radio stack and the user interface do not. The memory region is enforced by the memory protection unit; see the stack, heap and MPU lesson.

The second rule is about SOUP, software of unknown pedigree or provenance: code you did not write and cannot fully inspect. A real-time operating system, a vendor HAL, a DSP library and a neural-network runtime are all SOUP. The standard sets a risk-based model for when it is acceptable, plus testing to support your reasons for using it. In practice you list each item, pin its version, read its published bug list for anything that touches the safe path, and test what you rely on.

The outside control: why hardware matters

Here is the most useful idea in the chapter. An external risk control measure is one that sits outside the software. It need not be outside the product. Usually it is hardware: a mechanical limit, a motor speed limit, a fuse. If such a measure brings the risk to an acceptable level, the software may fall to class A. But there is a catch. A software monitor that watches another software module in the same system does not count. If both fail for the same reason, nothing is left.

Run our wheelchair through it, in steps. Step 1, the hazard: unintended motion. Step 2: can the software contribute? Yes, a false go would do it. Step 3: is there an outside control? Suppose a hardware limiter caps the speed at a slow walking pace and cuts motor power if a hand-held deadman switch is released. Step 4: after that control, is the leftover risk acceptable? That is a judgment made in the risk file with evidence. If yes, the decoder may be class A. If not, and a collision could cause serious injury, it is class C. The same code can sit in either class depending on what hardware surrounds it. That is a design choice, and an expensive one to ignore.

Classify the software

Pick a preset, or set the three inputs yourself. The class follows the Amendment 1 logic. The list shows what that class asks of you.

Illustrative reasoning only. The presets show how the logic runs and are not a classification of any real product. In a real project the risk file decides the class, with evidence that an outside control is effective. Activity lists follow a published summary of IEC 62304 with Amendment 1.

The failure story. Symptom: a reviewer rejects a claim of class A. Measurement: the file names a “software watchdog” as the external control, and it runs on the same chip as the decoder. Fix: either add a control that does not depend on that software, such as a hardware limiter, or classify the software higher and carry the extra process. Both fixes are honest. The one thing you cannot do is count a software monitor as outside the software.

A team classes its decoder as A because “a second software task checks the first one”. What is wrong?

Chapter 10

The Safe State

Design the stop so that it still works when the decoder, the gate and the RTOS have all stopped working

The decoder task runs a retry loop. A rare bug turns it into an infinite loop. At that moment the last command was go. The task is stuck, but the motor-control timer that your code configured is a piece of hardware, and it does not know the code has hung. It keeps generating the last pulse width it was given. The chair keeps rolling, driven by a program that no longer runs.

This is the most common way a stuck program becomes a physical hazard. Peripherals keep their last setting. So the design question is not “how do we stop when everything works?” It is “how do we stop when the software that would stop us is gone?”

The safe state

The safe state is a condition in which the product cannot cause harm. For a chair it is motors off and brakes on. For a stimulator it is output current zero. The rule of fail-safe design is simple: the safe state is what happens when nobody does anything. Danger must need a continuous effort. If the effort stops, whatever the reason, the system falls into safety by itself.

Five mechanisms carry this idea. Each guards against a different kind of failure, and none replaces another.

  1. Deadman timeout in hardware. The motor driver enable pin is held up by a one-shot timer. Every valid command re-arms it for, say, 300 ms. If no fresh command arrives in time, the timer lapses and the enable drops. No software runs in that path. It catches a hung program.
  2. Independent watchdog. A counter driven by its own clock that resets the chip unless the firmware “kicks” it before it runs out. Kick it from the main loop only after every stage has shown a sign of life since the last kick. Never kick it from a timer interrupt: the interrupt keeps running when the main loop is stuck, and the watchdog never fires. STM32 parts offer an independent watchdog and a window watchdog, and other chips such as the nRF52840 have their own. It catches a hang and restarts the chip.
  3. Plausibility checks in software. The sample counter from the ADC frames must go up by one each time. Scores must stay in a sane range. Commands must not flip faster than a human could. This catches data that is wrong but alive. A deadman cannot see it, because the program is still sending fresh commands.
  4. Boot self-test. At start, check the checksum of the program and of the classifier weights, and refuse to enable output if they do not match. This catches a corrupt or tampered model before it ever acts.
  5. Hardware run limit. A cap that the hardware enforces, such as a maximum continuous run of 10 seconds before a hand action is needed. It bounds the harm from any fault nobody foresaw.

Also, make the outputs safe during reset and boot. Many microcontroller pins float as inputs after reset, so the motor enable could drift high. A pull-down resistor on that line makes off the default while the chip starts.

c/* Main loop: kick the watchdog only if every stage reported alive since the last kick. */
#define ALIVE_ACQ   (1u << 0)   /* a new ADC frame arrived, counter went up by 1 */
#define ALIVE_DECODE (1u << 1)   /* a window was scored */
#define ALIVE_GATE   (1u << 2)   /* the validity gate ran */
#define ALIVE_ALL    (ALIVE_ACQ | ALIVE_DECODE | ALIVE_GATE)

static volatile uint8_t alive;

void main_loop_tick(void) {
    /* ... acquire, decode, gate: each ORs its bit into alive ... */
    if ((alive & ALIVE_ALL) == ALIVE_ALL) {
        wdt_kick();          /* a stuck stage means no kick, so the chip resets */
        alive = 0;
    }
}

void send_command(bool go, bool data_ok) {
    if (go && data_ok)
        deadman_rearm_ms(300);   /* hardware one-shot holds enable high for 300 ms */
    /* no else branch: with no re-arm, the hardware lets the enable fall by itself */
}

A worked time budget

Put numbers on it with illustrative values. The chair moves at 0.5 m/s. The decoder hangs just after sending go. With no protection, the command stays latched for ever. With only the watchdog at 1 s, the chip resets after 1.02 s (1 s plus an assumed 20 ms for the reset), and the chair travels about 0.5 × 1.02 = 51 cm. With the 300 ms deadman added, the enable drops at 0.30 s and the chair travels 0.5 × 0.30 = 15 cm. With a 10 s hardware run limit as the last backstop, even a fault that nothing else sees ends within 10 s, 5 m at the same speed, which is the reason to choose a smaller limit if you can.

Look at which protection catches which fault. The device lets you switch each one on and off and see the exposure time for four faults.

Inject the fault, time the stop

Each bar is how long a wrong go stays live after a fault. Switch protections on and off. Tune the two timeouts.

300 ms
1000 ms

Illustrative model. Chair speed 0.5 m/s, a 20 ms reset time after the watchdog fires, a plausibility check that acts within one 0.25 s hop, and a boot self-test that stops a corrupt model before any output. The pattern is real; the numbers are not from a product.

Prove it by breaking it

A safe state you have never triggered is a belief, not a fact. The method is fault injection: add switches to a test build that cause each fault on purpose, a hang, a skipped counter, a flipped bit in the weights, and measure the time to the safe state, each time, in an automated test. The testing lesson shows how to run such tests without the board, and then on it. The fail-safe lesson goes deeper into watchdogs and safe-state design.

The model and the program are code too. If someone can change them, they can defeat all of the above. Secure boot and signed updates keep a bad model off the device. The FDA guidance in Chapter 8 asks submissions to consider how weak cybersecurity could compromise device function.

Failure story. Symptom: in the lab the chair rolled on for two seconds after a firmware crash, though a watchdog was fitted. Measurement: the watchdog was being kicked from a 100 Hz timer interrupt, which kept running after the main loop locked up. Fix: kick it from the main loop only, gated by the alive bits above, and add the hardware deadman so the stop no longer depends on a reset at all.

Your decoder is alive but a bug makes it send go with fresh data every hop. Which protection catches it?

Chapter 11

Field Guide

Keep the numbers, the checklist, the core code and the sources on one page

The lesson in one paragraph. A medical decoder takes a stream of microvolt samples, cuts it into 1-second windows every 0.25 seconds, measures the band power of the 8 to 13 Hz rhythm on two channels, scores the two log powers with a three-number linear classifier, and turns scores into a command that starts slowly and stops fast. Because the classifier answers even for garbage, a validity gate checks the window first. Because every part can fail, the patient side is isolated, the software is classed by the harm it could still cause after outside controls, and the output falls to a safe state in hardware when nobody refreshes it.

The numbers and terms

ItemValueWhere it comes from
ADS1299 frame, 8 channels216 bits = 27 bytes (24 status bits + 8 × 24 bits)ADS1299 datasheet
Sample period at 250 SPS4 ms; rate range 250 SPS to 16 kSPSADS1299 datasheet
ADS1299 noise and CMRR1 µV peak to peak (70 Hz bandwidth); −110 dBADS1299 datasheet
One ADC code, gain 24, VREF 4.5 V2 × 4.5 / 24 / 224 = 22.35 nVDatasheet equation, our arithmetic
Mu rhythm band8 to 13 Hz (7.5 to 12.5 Hz in some sources)Reference article on the mu wave
Window, hop, overlap250 samples, 62 samples (0.248 s), 75%This lesson’s choice
Window buffer, 2 channels, float322,000 bytesOur arithmetic
Patient leakage, normal / single faultB, BF: 100 / 500 µA. CF: 10 / 50 µAManufacturer note on IEC 60601-1
2 MOPP4,000 V rms test, 8 mm creepage at 250 V workingVendor application bulletin
IEC 62304 classesA: no harm. B: no serious harm. C: serious harm or deathPublished summary, Amendment 1
FDA Enhanced documentationFailure could present a hazardous situation with probable risk of death or serious injury, before controlsFDA guidance, June 2023
Public motor-imagery dataset9 people, 4 tasks, 22 EEG channels, 250 Hz, 288 trials per sessionBCI Competition IV, dataset 2a
Deadman example300 ms, about 15 cm at 0.5 m/sIllustrative

The release checklist

Tick what your build has proved, not what you intend. The read-out names what is still missing.

Check before you ship

    A teaching checklist drawn from this lesson, not a regulatory submission list. Your risk file and the licensed standards define the real one.

    The core code

    c/* One hop of the decoder. Uses goertzel_power (ch 2), cmd_step (ch 5), send_command (ch 10). */
    typedef struct { float w[2], b; } lda_t;           /* three numbers, fitted offline, signed with the firmware */
    
    static bool window_valid(const float *x, int n, uint32_t lead_off_bits) {
        if (lead_off_bits) return false;                          /* hardware says an electrode is open */
        float mn = x[0], mx = x[0], sum = 0, ss = 0;
        for (int i = 0; i < n; i++) { sum += x[i]; if (x[i] < mn) mn = x[i]; if (x[i] > mx) mx = x[i]; }
        float mean = sum / n;
        for (int i = 0; i < n; i++) ss += (x[i] - mean) * (x[i] - mean);
        if (mx == mn)                  return false;                /* stuck code */
        if (sqrtf(ss / n) < 1.5f)   return false;                /* flat line, microvolts rms */
        if (mx - mn > 110.0f)        return false;                /* swing: blink or cable tug */
        return true;                                             /* the muscle-band check goes here too */
    }
    
    void decode_hop(const float *c3, const float *c4, int n, uint32_t lead_off,
                    const lda_t *m, cmd_t *cmd) {
        bool ok = window_valid(c3, n, lead_off) && window_valid(c4, n, lead_off);
        float score = 0;
        if (ok) {
            float f3 = logf(band_power(c3, n) + 1e-3f);              /* mean of 8..13 Hz goertzel_power */
            float f4 = logf(band_power(c4, n) + 1e-3f);
            score = m->w[0] * f3 + m->w[1] * f4 + m->b;
        }
        bool go = cmd_step(cmd, score, ok, 0.6f, 0.5f, -0.5f, 3);
        send_command(go, ok);                                    /* the hardware deadman does the rest */
    }

    Where it sits, and where to go next

    This lesson closes the biopotential track. The signal chain explains how microvolts reach the converter. Acquisition firmware shows the DRDY, SPI and DMA path, with packet counters. Interference and filters covers mains hum and filtering. Streaming covers the radio link. For the analog front end and filtering on the research side, see the BCI analog front end, filtering neural signals and real-time closed loop.

    For the machine-learning side, go to a network on a Cortex-M, INT8 in firmware and the sensor-to-feature pipeline. The line we fitted is the one from Fisher’s discriminant. For the safety side, go to fail-safe and functional safety, testing firmware, secure boot, bootloader and OTA and stack, heap and MPU. For actuators and timing in robots, see sensor and actuator integration.

    Sources

    None of this is legal or regulatory advice. The IEC and ISO standards are licensed documents. We quoted numbers from manufacturer and secondary summaries and said so each time. Before you design to a clause, read it in your own copy.

    The takeaway. A decoder will be wrong. Medical firmware is the craft of deciding in advance what happens then: isolate the patient so a fault elsewhere finds no path, check the data before trusting the answer, start slowly and stop fast, and let hardware fall to the safe state when nobody holds it up. Then write down the hazard, the control and the test, so someone else can check your work.

    Now press Teach and explain, from memory, how one window becomes a command and what stops a wrong command from hurting someone. Then go back to the decoder at the top, pop an electrode with the gate off and on, and say which Chapter 6 check caught it.

    On-Device Decode and the Rules of Medical Firmware
    Previous in the track · Back to Gleams