A microphone sends 16,000 numbers a second, but a model wants 1,960. Cut the stream into windows, boil each to 40 numbers, and keep the delay and the battery in budget.
Learn how a small chip turns a raw stream from a microphone or a motion sensor into the input of a neural network, and what each choice costs in milliseconds and microamps.
Pick a sensor, then drag the window and the hop. Watch the delay, the busy time and the average current move together. Then we build the pipeline piece by piece: the ring that holds samples, the windows, the taper, the features, the cycle count, the deadlines and the sleep.
You need a little C and the idea of a sample (one number a sensor reports at one instant). We build the rest from zero. Earlier in the series: IMU FIFO and timestamps, fixed-point DSP on a Cortex-M and rings, queues and drops (a later lesson in the real-time track).
Built from primary sources: the TensorFlow Lite Micro micro_speech example, the UCI HAR dataset, the CMSIS-DSP reference and the nRF52840 product specification. Every source is listed in the Field Guide.
A model, not a measurement. Cycle counts come from operation counts at 12 cycles per FFT butterfly (illustrative; measure yours with the DWT counter, Chapter 7). The model call takes an illustrative 8 ms (microphone) or 1 ms (motion). The CPU draws 52 µA per MHz at 64 MHz and sleeps at 1.5 µA, both from the nRF52840 product specification; sensor current is not counted. The 30 ms window and 20 ms hop are the TensorFlow Lite Micro micro_speech settings.
Chapter 0
Follow one second of sound from the microphone to the model, and see why every stage in between exists
Picture a small earbud that waits for you to say “yes”. A microphone inside it never stops listening. The battery is tiny, and the chip is a Cortex-M4F running at 64 MHz with 256 kB of RAM. The chip must hear the word, decide, and react before you notice a delay.
The microphone sends 16,000 numbers every second. Each number is one sample: the air pressure at one instant, stored as a 16-bit integer. That is 32,000 bytes a second, and it never pauses. The neural network that spots the word does not want that stream. It wants a fixed block of 1,960 numbers.
This lesson is about everything between the two. We call it the feature pipeline: the firmware that collects samples, cuts them into pieces, boils each piece down to a few numbers, and hands the result to the model on time. The model is the famous part. The pipeline is where most of the bugs, the milliseconds and the microamps live.
The TensorFlow Lite Micro project ships a keyword example called micro_speech. Its settings file gives the whole plan in a few lines. The audio rate is 16,000 samples per second. A frame covers 30 ms of sound, and a new frame starts every 20 ms. Each frame becomes 40 numbers. The model looks at the last 49 frames, which is 40 × 49 = 1,960 numbers. It answers with four scores: silence, unknown, yes and no.
Count what that does to the data. One second of sound is 16,000 samples, or 32,000 bytes. One second of frames is 50 frames of 40 one-byte numbers, or 2,000 bytes. The pipeline throws away 94% of the bytes and keeps what the model needs. It also turns a stream with no end into a block with a fixed shape, and a fixed shape is what a network can read.
Each stage has a reason. The ring buffer remembers the recent past while new samples keep arriving. The window picks a short stretch to look at. The transform turns that stretch from a list of pressures into a list of pitches. The filterbank squeezes the pitches into 40 bands, spaced the way ears hear them. The model then works on a picture of sound over time. Step through the stages below and read the shape at each one.
Each box is one stage of the pipeline for the microphone. Drag the stage slider, or press Play, and read the shape of the data at the lit stage. The bar under each box shows how many bytes per second pass through it.
The 16 kHz rate, the 30 ms frame, the 20 ms stride, the 40 numbers per frame, the 49 frames and the four labels are the settings of the TensorFlow Lite Micro micro_speech example. The 512-point transform size is the next power of two above 480 samples. Sample width (16 bits in the ring, 8 bits per feature) and the ring size are our choices for this model.
Look at the bytes-per-second bars. They stay level through the ring and the window, because the same samples flow through. They jump at the transform, where each frame becomes 257 floating-point values. The big drop is the filterbank: 257 values become 40 one-byte numbers. After that point the data is small enough to stack 49 frames in about 2 kB of RAM.
Every choice in the pipeline spends from three budgets at once. The first is delay: how long after something happens in the world the model can know about it. The second is CPU time: how many cycles each hop needs, out of the cycles the chip has. The third is energy: how much charge leaves the battery. A longer window can make the features better and the delay worse. A shorter hop can make the delay better and the energy worse. No setting wins all three, which is why the hero at the top lets you turn the knobs and watch all three move.
A latency budget is a number the product sets. An earbud might need to react in 100 ms. A fall detector on a wrist might allow a second. The engineer’s job is to add up the delays of every stage and check that the sum fits under the number. This lesson gives you the parts to add up.
Suppose you feed raw samples to the model one at a time. The model needs a block, so you must collect a block anyway. Suppose you recompute everything for each new sample. At 16,000 samples a second, a transform of 12,000 cycles (an illustrative count; Chapter 7 derives it) runs 16,000 times a second, which is 192 million cycles a second. The chip only has 64 million. The pipeline would be late from the first second.
So the pipeline does the opposite. It keeps a ring of recent samples. It lets samples pile up until a hop is complete. It then does one block of work and sleeps until the next hop. The rest of this lesson builds that design, one piece at a time, and measures each piece.
Chapter 1
Learn what a sensor hands the chip, how many bytes that is, and why the firmware takes samples in blocks
Suppose your code asks the microphone, “What is the air pressure now?” The microphone cannot answer on demand. A sampling clock inside the converter decides when each measurement happens. Your firmware does not pull samples. It receives them, on the clock’s schedule, whether it is ready or not.
The sample rate, written fs, is how many samples arrive each second. The gap between two samples is the sample period, 1 / fs. At 16,000 samples a second the period is 62.5 µs. A motion sensor that reports 50 times a second has a period of 20 ms. Everything in this lesson, from the ring to the deadline, is arithmetic on these two numbers.
Multiply three things: the rate, the number of axes (separate channels measured at once), and the bytes per sample. A microphone has one channel. An accelerometer has three: x, y and z. Both usually give 16-bit integers, which take 2 bytes.
microphone: 16,000 × 1 × 2 B = 32,000 B/s accelerometer: 50 × 3 × 2 B = 300 B/s
Those two figures differ by a factor of about 100. The microphone fills 64 kB of RAM in two seconds. The accelerometer needs 218 seconds to do the same. That one comparison explains why audio pipelines fight for every cycle and motion pipelines fight for every microamp.
The integers are not yet physical units. A 16-bit accelerometer set to a ±2 g range spreads 4 g over 65,536 steps. One step, the LSB (least significant bit), is 4 / 65,536 = 61 µg. The raw value 16,384 therefore means about 1 g. Keep the integers inside the pipeline and apply the scale once, late, because integer maths is cheap and floating-point conversion on every sample is not.
A first design is easy to imagine. The converter finishes a sample and raises an interrupt, a signal that makes the CPU stop what it is doing and run a short function called the interrupt service routine (ISR). The ISR stores the sample. At 16,000 samples a second that is 16,000 interrupts a second.
Each interrupt costs cycles even if the ISR does nothing: the CPU saves its registers, jumps, runs, restores and returns. Say that costs 200 cycles (an illustrative figure; you will measure your own). Then 16,000 interrupts spend 3.2 million cycles a second, 5% of a 64 MHz chip, just on entering and leaving. The chip also can never sleep, because it wakes every 62.5 µs.
The fix is DMA, direct memory access. A small separate engine copies samples from the peripheral into a RAM array with no CPU help. The CPU is told only when a block (a fixed run of samples) is full. If the block holds 160 samples, the interrupt rate falls from 16,000 a second to 100.
Real firmware usually fills a buffer of two blocks and gets two interrupts: one at the half-way mark and one at the end. While the DMA fills the second half, the CPU reads the first. This is the double buffer or ping-pong that the audio DMA lesson builds in detail. Motion sensors do the same job inside the sensor. They keep a FIFO (first in, first out queue) and raise a pin at a chosen watermark, as the IMU FIFO lesson shows.
A block has a cost too. The first sample in a block waits until the last sample arrives before the CPU sees any of them. With 160 samples at 16 kHz that wait is 160 × 62.5 µs = 10 ms. A bigger block saves interrupts and adds delay. A smaller block cuts delay and burns cycles. Try it.
Each tick is one sample. Each arrow is an interrupt that tells the CPU a block is ready. The teal bracket is how long the first sample of a block waits. Drag the block size from 1 to the largest.
The wait is exact: block size divided by the sample rate. The entry cost assumes 200 cycles for each interrupt on a 64 MHz Cortex-M4F, an illustrative figure for saving and restoring registers; measure yours with a pin toggle or the cycle counter (Chapter 7).
For the earbud, 128 samples at 16 kHz means a wait of 8 ms and 125 interrupts a second, an entry cost of 0.04% of the CPU. Drop to one sample per block and the same device spends 5% of the chip just entering interrupts. Rise to 1,024 and the wait grows to 64 ms, which eats most of a 100 ms budget before any maths starts.
Here is how the receive side looks in C on an STM32 part with an I2S peripheral and the ST HAL driver. The DMA fills dma_buf forever. Each callback marks one half as ready and does nothing else.
c#define BLOCK 128 /* samples per block: 8 ms at 16 kHz */ static int16_t dma_buf[2 * BLOCK]; /* two blocks: DMA fills one, the CPU reads the other */ static volatile uint8_t ready_half = 0xFF; /* 0 or 1 when a block is ready, 0xFF otherwise */ void audio_start(void) { HAL_I2S_Receive_DMA(&hi2s2, (uint16_t *)dma_buf, 2 * BLOCK); /* circular DMA, runs until stopped */ } void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *h) { ready_half = 0; } /* first half is full */ void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *h) { ready_half = 1; } /* second half is full */
Chapter 2
Build a buffer that always holds the newest samples, learn why it needs headroom, and see what happens when the consumer runs late
Think of a notebook with 1,024 lines that you fill one number per line. When you reach the last line, you go back to line one and write over the oldest number. You never turn the page and you never copy anything. At any moment the notebook holds the newest 1,024 numbers. That is a ring buffer, also called a circular buffer.
The pipeline needs exactly this. The sensor keeps writing. The feature code wants “the newest 480 samples” whenever a hop is complete. The slow way is to keep a plain array and shift it left on every sample. Shifting 480 samples 16,000 times a second moves 7.7 million values a second for nothing. The ring moves no data. It moves one number, the position of the write.
A ring is an array of N slots plus a head, the slot where the next sample goes. To write, store the sample at the head, then add 1 to the head. When the head reaches N it wraps back to 0. In C that is head = (head + 1) % N. The reader keeps its own marker, the tail, the oldest sample it has not yet used.
There is a famous trap. If head equals tail, is the ring empty or completely full? Both cases look the same. Embedded Artistry’s write-up on circular buffers names this problem and gives two fixes: waste one slot so that full never equals empty, or keep a separate flag. The flag adds a variable that both sides touch, which then needs a lock.
There is a cleaner fix. Do not wrap the indexes at all. Let head and tail be 32-bit counters that only ever count up, the total samples written and read. The number waiting is head - tail, and unsigned subtraction stays correct even when the counters overflow. Find a slot with counter & (N - 1). That mask works only when N is a power of two (512, 1024, 2048), which is why ring sizes are almost always powers of two. A mask is one cycle. A modulo can cost many.
The counter design also helps with threads and interrupts. The producer, an ISR or a DMA callback, writes only head. The consumer writes only tail. Neither writes the other’s variable, so one producer and one consumer need no lock. The same source notes that the queue is safe because the producer only changes the head. On a single-core Cortex-M you must still mark the shared counters volatile (or use C11 atomics), and store the data before you publish the new head.
Take N = 1,024 slots of 16-bit samples. That is 2,048 bytes and holds 64 ms of audio. After 3,000 samples have arrived, head is 3,000. The newest 480 samples start at counter 3,000 − 480 = 2,520. The slot is 2,520 & 1,023 = 472, and the last one is at 2,999 & 1,023 = 951. The window sits in slots 472 to 951 with no wrap.
Now wait until head is 1,200. The start counter is 720, in slot 720. The 480 samples run past slot 1,023, so they wrap. The first part is slots 720 to 1,023, which is 304 samples. The second part is slots 0 to 175, which is 176 samples. Total 304 + 176 = 480. The reader copies in two pieces, or just lets the index mask do the wrap in the loop. Features need a window array anyway, because the taper (Chapter 4) writes a new array, so the wrap costs nothing extra.
The ring must hold more than the window. The consumer does not run the instant a hop completes. A higher-priority task or a long interrupt may delay it. Say the consumer is late by L samples. By the time it reads, L newer samples have arrived. The ring must still contain the whole window plus those L samples, so the rule is N ≥ W + L.
With W = 480 and a ring of 1,024, the largest safe lateness is 1,024 − 480 = 544 samples, or 34 ms at 16 kHz. With a ring of 512 the margin is 32 samples, or 2 ms. A single flash write or a long interrupt can cost more than 2 ms. That is why a ring sized “just enough” works on the bench and fails in the field. Try the three sizes.
The circle is the ring at the moment the consumer finally reads. The newest samples are at the top and age runs counter-clockwise. Yellow is what arrived while the consumer was late. Warm is the 480-sample window it wants. Red is window data that was already overwritten.
Exact arithmetic at 16,000 samples a second with a 480-sample window and 16-bit samples: samples lost = max(0, lateness in samples + 480 − ring size). The slots of the ring are drawn as arcs; the scale is samples, not milliseconds.
The rule has a second use. When the red arc appears, a sample count tells you how many samples of the window are garbage. The code below finds that out before it uses the data, and counts the failure.
c#define RING_N 1024u /* power of two */ static int16_t ring[RING_N]; static volatile uint32_t head; /* samples ever written; only the producer writes it */ static uint32_t overruns; void ring_put_block(const int16_t *src, uint32_t n) { uint32_t h = head; for (uint32_t i = 0; i < n; i++) ring[(h + i) & (RING_N - 1u)] = src[i]; head = h + n; /* publish only after the data is stored */ } /* copy the n newest samples that ended `late` samples ago; -1 if any were overwritten */ int ring_window(int16_t *dst, uint32_t n, uint32_t late) { uint32_t end = head - late, start = end - n; if (late + n > RING_N) { overruns++; return -1; } /* already gone */ for (uint32_t i = 0; i < n; i++) dst[i] = ring[(start + i) & (RING_N - 1u)]; if (head - start > RING_N) { overruns++; return -1; } /* the producer lapped us during the copy */ return 0; }
Notice the second check. The producer keeps running while the consumer copies. If it laps the start of the window mid-copy, the first samples in dst are already stale. The test after the loop catches that case. Both failures raise the same counter, and the counter belongs in your telemetry. A silent overwrite is the worst kind of bug: the model still returns a number, and the number is wrong.
delay_ms before each read. Raise the delay until overruns first becomes non-zero. It should match (N − 480) / 16 ms, which is 34 ms for N = 1,024. The measurement confirms the sizing rule on your own chip.Chapter 3
Choose how long each look is and how often you look, and count what each choice costs in frames, pitch detail and blind spots
Imagine reading a very long scroll through a cardboard slot. You see a short stretch at a time. You slide the card along, read the next stretch, and slide again. The slot is the window: the run of samples the pipeline looks at in one go. The distance you slide each time is the hop. Each look produces one frame, the short list of numbers that stands for that stretch.
Two numbers define the plan. The window length W says how much signal one frame sees. The hop H says how often a new frame appears. For micro_speech, W is 30 ms and H is 20 ms. At 16,000 samples a second that is a window of 480 samples and a hop of 320. Consecutive windows share 160 samples, and a new frame comes out 50 times a second.
How many frames does a stretch of L samples give? The first window fills when W samples have arrived. After that each hop of H samples adds one more window. So the count is the number of whole hops that fit after the first window, plus the first one.
frames = floor( (L − W) / H ) + 1
Check it against the real example. One second is L = 16,000 samples. Then (16,000 − 480) / 320 = 48.5, which rounds down to 48, and adding 1 gives 49 frames. That is exactly the 49 in the micro_speech settings. The UCI HAR dataset, a standard set of phone-sensor recordings, uses the same idea for motion. Its readings come at 50 Hz, and each window is 2.56 s long with 50% overlap. That is 128 readings per window and a hop of 64 readings, or 1.28 s.
Suppose the windows do not overlap, so H equals W. A short event, such as the start of a word, can land on the border of two windows. Each window then sees half of it, and neither sees it clearly. Overlap fixes that. With H smaller than W, every moment sits inside several windows, and at least one of them has it near its middle.
Overlap costs compute. The work per second is one frame's work times 1 / H. Halve the hop and you double the work. The overlap is 1 − H/W: 33% for 30 ms and 20 ms, and 50% for the HAR settings. The extra frames also add data to the model’s input, so a model trained at one hop does not accept another.
If H is larger than W, the windows have gaps. The samples in the gaps are in no window at all. The firmware is then blind for the fraction 1 − W/H of the time, and a short event can slip through whole. This is a bug you can create by choosing a hop to save energy. The device below marks gaps in red.
The window length decides two things you cannot have together. A long window sees many cycles of a wave, so it can tell two close pitches apart. A short window sees an event sharply in time, so it can place a click or a step. The transform of Chapter 4 sorts a window into slots of pitch called bins. The pitch detail of a window with N points is the bin width, the gap between two slots: fs / N. For the 512-point transform at 16 kHz that is 31.25 Hz. A window of 2.56 s has a bin of 1 / 2.56 s = 0.39 Hz, fine enough to see a walking rhythm, while a 30 ms window cannot see below about 33 Hz.
So a speech frame is short, because phonemes change in tens of milliseconds. A step counter is long, because steps repeat in about a second. Choose W from the thing you want to see, then H from the delay you can allow. Test an event against your choice below.
The blue band is a short event, such as the start of a word. Each bar is one window of audio. Bold green bars hold the whole event. Red marks on the axis are samples that no window ever sees.
Exact counts at 16,000 samples a second. Frames = floor((L − W) / H) + 1 for L = 16,000. A window holds the event if it starts at or before the event start and ends at or after the event end. The event begins at 400 ms. Bin width is 16,000 divided by the next power of two at or above the window size.
At 30 ms and 20 ms the device shows 49 frames. Raise the event length to 100 ms and no 30 ms window holds it whole, because the window is shorter than the event. The firmware never sees the event in one frame. The model must then learn it from several consecutive frames, which is exactly why the model reads a stack of frames and not one.
The symptom is a model that works in Python and never fires on the chip, or fires on everything. The cause is often a frame count that is off by one, or a hop that differs by a few samples, or a start-up period where the stack is still half empty. The measurement is simple: print the frame count for exactly 16,000 samples fed from a file, and print the first frame’s time. The fix is to keep W, H, the feature count and the frame count in one header that both the firmware and the training script generate from, and to refuse to run the model until the stack holds a full 49 frames.
c/* features_config.h: generate the Python twin from this file, never retype the numbers */ #define FS_HZ 16000 #define WIN_SAMPLES 480 /* 30 ms */ #define HOP_SAMPLES 320 /* 20 ms */ #define N_MEL 40 #define N_FRAMES 49 /* one second of context */ #define FRAMES_IN(L) (((L) - WIN_SAMPLES) / HOP_SAMPLES + 1) /* FRAMES_IN(16000) == 49 */ static int8_t frames[N_FRAMES][N_MEL]; /* a ring of frames: 49 x 40 = 1,960 bytes */ static uint32_t n_frames; /* frames ever pushed */ void push_frame(const int8_t f[N_MEL]) { memcpy(frames[n_frames % N_FRAMES], f, N_MEL); n_frames++; } bool model_ready(void) { return n_frames >= N_FRAMES; } /* no inference on a half-empty stack */
n_frames at the end. It must read 49. Then toggle a pin each time a frame is pushed, and check on a logic analyzer that the period is 20.00 ms. A period of 20.00 ms with a count of 48 means your first window starts late.Chapter 4
See why a hard cut smears one pure tone across the whole spectrum, and fix it with a smooth taper that costs one multiply per sample
Record a clean 1,000 Hz whistle and cut out 512 samples of it with scissors. Whether the cut is clean depends on luck. If the piece holds a whole number of cycles, its two ends meet smoothly. If it holds, say, 32.5 cycles, one end is at the top of a wave and the other is at the bottom. There is a sharp jump where the ends would join.
That jump matters because of how the next stage works. The FFT (fast Fourier transform) turns a block of samples into a list of how much of each pitch it contains. It quietly assumes the block repeats forever, end to end. A jump at the join is a sudden edge, and a sudden edge contains every pitch at once. So a pure tone appears to contain a little of everything. This smearing is called spectral leakage.
If both ends of the block are zero, the join has no jump at all. So before the FFT we multiply the block by a window function, or taper: a curve that is zero at the two ends and rises smoothly to 1 in the middle. The common choice is the Hann window. For sample number n in a block of N samples:
You then multiply sample by sample: tapered[n] = x[n] * w[n]. The table w is the same every time, so you compute it once and store it. That is N multiplies per frame, a few thousand cycles, small beside the FFT.
Nothing is free. The taper throws away the samples near the edges, because they are multiplied by almost 0. Information there is lost from this frame. It also makes a tone look a little wider: the peak in the spectrum spreads over about 4 bins instead of 2. In exchange the far-away leakage drops by tens of decibels. For a speech or motion feature, a clean floor is worth a slightly wide peak.
This ties back to Chapter 3. The edge samples are down-weighted in this frame, but they sit near the middle of the next one if the windows overlap. Overlap gives every sample a turn at full weight. A Hann window with 50% overlap sums to exactly 1 everywhere, so no part of the signal is favoured. At micro_speech’s 33% overlap the sum is not exactly flat, which is fine for features and would not be fine for rebuilding audio.
The decibel (dB) scale below compares sizes that differ a lot. Every 20 dB is a factor of 10 in amplitude. A peak at 0 dB and a floor at −60 dB means the floor is a thousand times smaller. Move the tone off the bin centre and compare the two windows.
Top: the 512-sample piece of a tone. Bottom: its spectrum in decibels. Slide the tone between two bins and watch the rectangular spectrum smear. Then choose Hann.
Computed live: a 512-point FFT of a tone sampled at 16,000 per second, block length 512, bin width 31.25 Hz. The Hann taper is w[n] = 0.5 − 0.5 cos(2πn/N). Levels are in dB relative to each spectrum’s own peak. Floating-point numbers; a fixed-point chip adds its own rounding floor (Chapter 7).
At offset 0.00 the tone fits exactly 32 cycles, and even the rectangular window looks clean. At offset 0.50 the rectangular spectrum has a floor near −25 dB ten bins from the peak, loud enough to hide a quiet second sound. The Hann spectrum drops to about −67 dB in the same place. The tone is the same. Only the cut changed.
On a Cortex-M the taper is one call. The CMSIS-DSP library has arm_mult_q15, which multiplies two arrays of Q15 numbers element by element with saturating arithmetic. Q15 is a fixed-point format where a 16-bit integer stands for a value between −1 and just under 1. The fixed-point DSP lesson builds the format from scratch.
c#include "arm_math.h" static q15_t hann[WIN_SAMPLES]; /* 480 x 2 B = 960 bytes, built once */ void hann_init(void) { for (int n = 0; n < WIN_SAMPLES; n++) hann[n] = (q15_t)(32767.0f * (0.5f - 0.5f * cosf(2.0f * (float)PI * n / WIN_SAMPLES))); } /* per frame: src holds 480 raw samples, dst gets the tapered copy */ arm_mult_q15(src, hann, dst, WIN_SAMPLES); /* 480 saturating Q15 multiplies */
Keep dst separate from src. The ring holds the raw samples, and the next window overlaps this one, so you must not write the taper back into the ring. This is also why the wrap in Chapter 2 costs nothing: the multiply already reads each sample once and writes it somewhere else.
The symptom is a model that scores lower on the device than in your notebook, with no crash. The cause is a different window. The training script might use a symmetric Hann, with N − 1 in the divisor, while the firmware uses the periodic form with N. The two differ in the last few digits, and a quantised model can notice. The measurement is to run the same 480 samples through both and compare the tapered arrays. The fix is to generate the table once, in Python, and paste it into a C array, so both sides share the very same numbers.
Chapter 5
Turn one tapered window of sound into a short list of band energies, and see the picture of sound that the model actually reads
Listen to someone say “yes” and then “no”. The raw wave looks like a nervous scribble in both cases. What differs is where the energy sits. The “ee” in “yes” puts energy high up, and the “o” in “no” puts it low. A model learns far faster from where the energy sits than from the scribble. So each window is turned into a short list of energies, one per band of pitch. That list is the feature frame.
The recipe has four steps, and each one has a shape. The window gives 480 numbers. The FFT turns them into 257 numbers. The filterbank squeezes those into 40 numbers. A log makes the 40 numbers easy for a network to use. Here is each step and why it is there.
Chapter 4 tapered the window. Now pad the 480 samples with zeros up to 512, because the FFT wants a power of two. The CMSIS-DSP real FFT, arm_rfft_fast_f32, supports lengths 32, 64, 128 and so on up to 4,096. A real FFT of N points gives N/2 + 1 complex values, here 257: one for each bin, a slot for one pitch, 31.25 Hz apart. Each value is a pair, a real part and an imaginary part, and together they describe a wave’s strength and timing.
The model does not care about timing inside the window. It cares about strength. The strength squared is the power: real2 + imaginary2. CMSIS-DSP has arm_cmplx_mag_squared_f32 for it. One quirk saves memory: the library packs the real FFT output into N floats by storing the Nyquist value, which is real, in the slot of the first value’s imaginary part. Your code must unpack the first two floats by hand.
257 bins are too many and too evenly spaced. Human hearing tells low pitches apart finely and high pitches coarsely. Between 100 Hz and 200 Hz you hear a big step. Between 5,100 Hz and 5,200 Hz you hear almost none. The mel scale bends the pitch axis to match. A common formula is m = 2595 × log10(1 + f / 700). At 1,000 Hz it gives about 1,000 mel by design, and at 4,000 Hz about 2,146 mel.
A mel filterbank places 40 overlapping triangles evenly along the mel axis. Each triangle is a list of weights over the bins it covers. Its output is the weighted sum of the power in those bins. Low triangles are narrow and cover few bins. High triangles are wide and cover many. The result: 257 power values become 40 band energies, with fine detail where the ear has it.
Loud and quiet sounds differ by factors of thousands. A network handles numbers of similar size much better. Taking the log squeezes the range, much as the decibel scale did in Chapter 4. Add a tiny constant first, since the log of zero has no value. Finally the value is scaled to one byte with the model’s own scale and zero point, two numbers stored in the model that map real values onto the 8-bit range. The TensorFlow Lite Micro frontend also applies noise reduction and a per-channel gain step called PCAN before the log, and ships its exact settings in the example’s audio_preprocessor.py.
Stack the frames side by side with time running to the right and band running upwards. You get a picture of sound over time, called a spectrogram. The model for micro_speech reads exactly such a picture, 49 columns by 40 rows. The device below builds one from a made-up second of sound: a low hum, a rising whistle, then a two-tone note. All of it is computed live in your browser, with the same steps as above.
The picture is one second of a made-up sound: a hum, a rising whistle, then a two-tone note. Bright means more energy. Change the window, the hop and the bands, and turn the taper off to see the smear.
The sound is synthetic and the filterbank is ours: triangles spaced evenly in mel from 100 Hz to 7,600 Hz, with the formula above. micro_speech’s own band edges, noise reduction and PCAN are not reproduced. The 30 ms window, 20 ms hop and 40 bands are its settings. Cost uses the model of Chapter 7 at 12 cycles per butterfly (illustrative).
At the defaults the picture is 49 columns by 40 rows, and the whole thing is 1,960 numbers. Drop the bands to 8 and the picture goes blocky: fewer numbers, but the two tones in the last part merge. Drop the taper and horizontal smears appear around every bright line. Raise the hop to 40 ms and the picture shows 25 columns, so each moment is seen once instead of twice.
cstatic arm_rfft_fast_instance_f32 rfft; /* arm_rfft_fast_init_f32(&rfft, 512) once at boot */ static float x[512], X[512], pw[257]; /* 2 KB + 2 KB + 1 KB of RAM */ void make_frame(const int16_t *raw, int8_t out[N_MEL]) { /* raw: 480 samples from the ring */ for (int i = 0; i < 480; i++) x[i] = raw[i] * hann_f[i] * (1.0f / 32768.0f); /* taper, scale to [-1, 1) */ for (int i = 480; i < 512; i++) x[i] = 0.0f; /* pad to a power of two */ arm_rfft_fast_f32(&rfft, x, X, 0); /* check the signature in your CMSIS-DSP version */ pw[0] = X[0] * X[0]; pw[256] = X[1] * X[1]; /* DC and Nyquist are packed in X[0], X[1] */ arm_cmplx_mag_squared_f32(&X[2], &pw[1], 255); /* bins 1..255: re^2 + im^2 */ for (int m = 0; m < N_MEL; m++) { /* 40 sparse triangles, weights from Python */ float a = 0.0f; for (int k = mel_lo[m]; k <= mel_hi[m]; k++) a += pw[k] * mel_w[m][k - mel_lo[m]]; int q = (int)lroundf(logf(a + 1e-6f) / in_scale) + in_zero; /* the model's own scale and zero point */ out[m] = (int8_t)(q < -128 ? -128 : q > 127 ? 127 : q); } }
The symptom looks like bad luck: accuracy 95% in the notebook, 70% on the chip. The cause is almost always a feature mismatch. The Python frontend and the C frontend differ in the taper, the mel edges, the log base, the noise step or the rounding. The measurement is to run the same WAV through both and compare the 49 × 40 arrays band by band. Plot the largest absolute difference. A good port is within one or two quantisation steps. The fix is to export the taper table, the mel weights and the scale and zero point from Python into a C header, and to add that comparison as a test that runs in your build.
make_frame and print all 49 frames over the serial port. Run the same clip through the Python frontend and diff the arrays. The largest difference per band tells you which step does not match.Chapter 6
Strip out gravity, measure how hard and how fast the wearer moves, and keep the features the same however the device is worn
A band on your wrist reports acceleration on three axes, 50 times a second. You sit, then walk, then run. The device should say which. The obvious plan is to feed the model the raw x, y and z numbers. The plan fails for a plain reason: gravity.
An accelerometer cannot tell gravity from motion. At rest it reads 1 g, the pull of Earth, pointing down. Which of the three axes carries that 1 g depends on how the band sits on the wrist. Tilt the band and the readings move from one axis to another, although nothing about the wearer changed. A model trained on one wrist angle then misreads every other.
Gravity changes slowly. Motion changes fast. So a low-pass filter (a filter that lets slow changes through and blocks fast ones) isolates gravity, and subtracting it leaves the motion. The UCI HAR dataset did exactly this: it used a Butterworth low-pass filter to separate body acceleration from gravity, with a 0.3 Hz cutoff for the gravity part.
The cheapest filter for a chip is one line per axis. Keep a running estimate g. For every new reading x, nudge g towards x by a small fraction a: g = g + a × (x − g). This is a one-pole filter. A cutoff of 0.3 Hz at 50 samples a second gives a = 1 − e−2π×0.3/50 = 1 − e−0.0377 = 0.037. That is one multiply and two adds per axis per sample. It is a cruder shape than a Butterworth, so say so, and match it in training.
A second way to get orientation out is the length of the acceleration vector, |a| = √(x2 + y2 + z2). Rotating the band changes x, y and z but not their combined length. At rest |a| is 1 g whatever the tilt. Motion makes |a| wobble around 1 g. The wobble is what we measure.
A window of 128 readings (2.56 s at 50 Hz, the HAR choice) is still too big to feed a small model raw. A handful of features says most of what matters:
Work one by hand on eight readings of |a| in g: 1.0, 1.2, 0.9, 1.1, 1.0, 1.2, 0.9, 1.1. The sum is 8.4, so the mean is 1.05. The gaps from the mean are −0.05, 0.15, −0.15, 0.05, repeated. Squared they are 0.0025, 0.0225, 0.0225, 0.0025, again repeated, and they add up to 0.1. Divide by 8 for the variance, 0.0125. The standard deviation is the square root, 0.112 g. A still wrist gives a standard deviation near zero, so 0.112 g is clearly motion.
The dominant frequency uses the same steps as the audio frame. Taper the 128 readings, take a 128-point real FFT, and find the strongest bin. The bin width is 50 / 128 = 0.39 Hz. A rhythm of 1.9 Hz lands in bin 5, at 1.95 Hz. Try it on four made-up activities.
Three coloured traces are the x, y and z readings. The warm band is the 2.56 s window. Choose an activity, then tilt the band. Watch which numbers move when only the tilt changes.
Toy signals, not recordings: still adds 0.01 g of noise; walking is a 1.9 Hz sway of 0.3 g, running a 2.8 Hz sway of 0.9 g, shaking a 5.5 Hz sway of 0.6 g, along the body’s vertical axis, which tilts with the wrist. The sample rate (50 Hz) and the window (128 readings) are the UCI HAR settings. Cost uses the Chapter 7 model.
Set the activity to walking and drag the tilt from 0 to 90 degrees. The raw mean of z falls from about 1.0 g to about 0 g, though the wearer still walks at the same pace. The standard deviation of |a| and the dominant rhythm stay put. The first number would confuse a model. The other two would not.
With a 50% overlap the windows share half their readings, and you can avoid re-reading all 128 on every hop. Keep a ring of |a| values and two running sums, one of the values and one of their squares. When a new value arrives, add it and subtract the one that leaves. The standard deviation then takes a few operations at any hop.
c#define WIN 128 #define LSB_G (1.0f / 16384.0f) /* 16-bit, +-2 g: 4 g over 65,536 steps */ static float mag[WIN], s1, s2; /* ring of |a|, running sum, running sum of squares */ static uint32_t n; void on_sample(const int16_t a[3]) { float x = a[0] * LSB_G, y = a[1] * LSB_G, z = a[2] * LSB_G, m; arm_sqrt_f32(x * x + y * y + z * z, &m); /* |a| in g: the same at any tilt */ float old = mag[n % WIN]; mag[n % WIN] = m; n++; s1 += m - old; s2 += m * m - old * old; /* slide both sums by one reading */ } float window_std(void) { float mean = s1 / WIN; return sqrtf(fmaxf(0.0f, s2 / WIN - mean * mean)); /* guard: rounding can make it slightly negative */ }
Two bugs hide in this code. In floating point, adding and subtracting forever lets rounding error pile up, so after hours the sums are slightly wrong. The cure is to recompute both sums from the ring every few hundred hops. In fixed point the squares are worse. A 16-bit reading can be as large as 32,768, and its square is 230. Adding 128 of them needs up to 237, which does not fit in 32 bits. The symptom is a standard deviation that jumps to nonsense in a hard shake. The measurement is to feed a full-scale square wave and watch the sum. The fix is a 64-bit accumulator, or a right shift before squaring, chosen on purpose.
window_std() with the board flat on a table, then tilted 45 and 90 degrees. The value should hold near 0.00x g at every tilt. Then tap the table and see it rise. If the number depends on the tilt, a raw axis has leaked into a feature.Chapter 7
Add up the cycles for one frame, compare them with the cycles the chip has per hop, and learn to measure the real number
You have picked a window and a hop. A friend asks, “Will the chip keep up?” You cannot answer by feel. A chip does not feel fast or slow. It does a fixed number of tiny steps each second, and your code needs a fixed number of steps for each hop. Keeping up means the second number is smaller than the first.
The tiny step is a clock cycle. At 64 MHz the CPU has 64 million cycles each second, and each cycle lasts 15.6 ns. A hop of 20 ms therefore gives the chip 64,000,000 × 0.020 = 1,280,000 cycles to finish everything: the frame, the model, and any other job on the chip. This is the cycle budget of one hop.
Count by stage, using the shapes from Chapter 5. Every number here is an estimate for planning. Chapter 7 ends by showing how to replace each with a measurement.
The sum is 2,880 + 12,288 + 2,056 + 1,600 = 18,824 cycles, or 0.29 ms at 64 MHz. The FFT is 65% of it. Divide by the 320 new samples per hop and you get about 59 cycles per input sample. The chip has 4,000 cycles per sample available at 64 MHz and 16 kHz, so the frame uses 1.5% of them.
The model is a different story. A small keyword network can need hundreds of thousands of cycles. If it needs 500,000 cycles, then one hop costs 18,824 + 500,000 = 518,824 cycles. That is 40.5% of the budget. The frontend is cheap. The network is the cost. Both numbers matter, and only measurement gives the real ones.
The cheapest way to be wrong is to forget what happens when the budget runs out. If the work for one hop takes longer than the hop, the next hop starts before the last one ends. Work piles up, the ring (Chapter 2) overruns, and Chapter 8 shows the result. So set a safety limit, such as no more than 60% busy on average, so jitter from other work has room.
The long outline is the cycles the chip has in one hop. The yellow bar is what one hop needs: the frame, then the model. The lower bar zooms into the frame alone. Change the clock, the hop and the costs.
The cycle counts are planning estimates from operation counts, not measurements: 6 cycles per sample, the chosen cycles per butterfly, 8 cycles per bin in the filterbank and 40 cycles per log. The window is 30 ms (480 samples, a 512-point FFT). A real Cortex-M4F will differ with flash wait states, cache and library version. Measure with the cycle counter shown below.
Lower the clock to 16 MHz with the defaults. One hop now has 320,000 cycles and needs 518,824, so the chip is over budget at 162% and cannot keep up. The device says the slowest clock that fits is about 26 MHz. Then double the cost per butterfly to 24. The frame grows by 12,288 cycles, but the total barely moves, because the model dominates. Spend your effort where the cycles are.
The nRF52840 and many STM32 parts have a Cortex-M4F core, whose FPU (floating-point unit) does single-precision maths in hardware. On those, a float FFT is fast and easy. Smaller cores such as the Cortex-M0+ have no FPU, so float maths runs as software and takes many times longer. There you use fixed-point formats such as Q15 (the fixed-point DSP lesson), which also halve the memory: 2 bytes per value, not 4. Fixed point trades range for speed, and Chapter 6 showed how a sum can overflow. Pick the format from the chip.
Arm Cortex-M3, M4 and M7 cores have a cycle counter in the Data Watchpoint and Trace unit (DWT). It is a 32-bit register that adds 1 on every clock. Switch it on once, read it before and after a function, and subtract. The CMSIS core header for the Cortex-M4 puts the DWT at 0xE0001000, with the cycle counter CYCCNT at offset 0x004 and an enable bit CYCCNTENA at bit 0 of the control register. The trace enable bit TRCENA is bit 24 of the debug register DEMCR at 0xE000EDFC. The Cortex-M0+ header has no DWT, so there you use a hardware timer instead. Some Cortex-M7 parts also lock the DWT until you write a key to its lock register, so check your reference manual.
c/* Cortex-M3/M4/M7: values from CMSIS core_cm4.h (DWT_BASE 0xE0001000, DEMCR at 0xE000EDFC) */ #define DEMCR (*(volatile uint32_t *)0xE000EDFCu) #define DWT_CTRL (*(volatile uint32_t *)0xE0001000u) #define DWT_CYCCNT (*(volatile uint32_t *)0xE0001004u) static inline void cyc_init(void) { DEMCR |= (1u << 24); /* TRCENA: power up the DWT */ DWT_CYCCNT = 0; DWT_CTRL |= 1u; /* CYCCNTENA: start counting */ } uint32_t t0 = DWT_CYCCNT; make_frame(raw, out); uint32_t frame_cycles = DWT_CYCCNT - t0; /* unsigned subtraction survives a counter wrap */
Measure the worst case, not one lucky call. Run the frame a few thousand times on real audio and keep the maximum. Flash wait states, cache misses and interrupts that land in the middle all push the worst case above the average, and the deadline is set by the worst case.
make_frame with the counter above and print the largest value over 5,000 frames. Compare it with the 18,824 estimate. Then divide the measurement by 512 to get cycles per bin and update the planning figure in your own budget. The 12 cycles per butterfly is a guess until you do.Chapter 8
Share one core between the sample handler, the feature code, the model and the radio, and keep the ring from being lapped
So far each stage had the chip to itself. A real device never works that way. The same core must also run the Bluetooth stack, blink a light, and answer a button. Four jobs now want the CPU, and they do not agree on what is urgent. Who runs when is a question about deadlines: the time by which a job must finish, or something breaks.
Look at what breaks. If the sample handler runs late, the DMA buffer is overwritten and samples are lost for good. If the feature code runs late, the ring (Chapter 2) can be lapped. If the model runs late, one decision is late or skipped, and the next one still comes. The three jobs have different costs of being late, and the schedule should follow that order.
A priority is a ranking. When two jobs are ready, the higher one runs, and it may preempt (interrupt) a lower one that is running. The lower one resumes when the higher one finishes. Here is a sensible ranking for the earbud:
The model runs last because its lateness is the cheapest. A late decision hurts a little. A lost sample hurts for ever. The feature task sits above the model for a second reason: it is short, so putting it first costs the model almost nothing, and it keeps the ring from being lapped.
It is tempting to compute the FFT inside the DMA callback, since the data just arrived. Do not. An interrupt handler blocks everything of lower or equal priority until it returns. A 0.29 ms handler would delay the radio, other sensors and the next DMA event by up to 0.29 ms every time. The rule: an interrupt does the least it can, usually a flag or a queue push, and a task does the rest. This split is the top half and bottom half pattern. The RTOS lessons, such as the embedded RTOS lesson, show the tools: semaphores, queues and task priorities.
A first test uses utilization: for each job, its work time divided by its period, summed. Our four jobs give 0.05/8 + 2/30 + 0.29/20 + 8/20 = 0.0063 + 0.0667 + 0.0145 + 0.4 = 0.487. The classic Liu and Layland result says that if the job with the shortest period always ranks highest (rate-monotonic order), n jobs always meet their deadlines when utilization stays below n(21/n − 1). For four jobs that bound is 0.757. Our ranking is not quite that order: the radio, with a 30 ms period, outranks the two 20 ms jobs. So treat 0.487 against 0.757 as a rough sanity check, not a proof. It says there is a lot of room. The response-time check below is the one that guards the ring.
Utilization is the average view. The ring cares about the worst moment, the response time of the feature task: the time from its release until it finishes, including interruptions. At worst the radio event (2 ms) and a sample handler (0.05 ms) sit in front of it, so it finishes within about 2 + 0.05 + 0.29 = 2.34 ms. That is 37 samples at 16 kHz, far less than the 544 samples of margin in a 1,024-sample ring. The pipeline is safe. Try changing the numbers.
Each row is one job, in priority order from the top. A coloured block means that job has the CPU. A red tick is a model result that arrived after the next hop began. Lengthen the model or the radio event until something breaks, then change the policy.
A simulation, not a trace. Fixed priorities, preemption, a 20 ms hop, a sample handler of 0.05 ms every 8 ms, a radio event every 30 ms, and a feature task of 0.29 ms (Chapter 7). The model and radio times are illustrative. A real RTOS adds context-switch time of its own, which you can measure with a pin toggle.
At the defaults the model’s worst response is about 8 ms, under the 20 ms hop, and all eight decisions arrive on time. Push the model to 25 ms. Utilization passes 1, and in Queue mode each decision arrives later than the one before: by the end of the chart the last result is 71 ms after its frame. In Skip mode the delay stays bounded at about 27 ms, because no decision waits behind another. Four of the eight decisions are dropped, and the counter shows it. Skipping is almost always right for a stream, since a decision about sound from a second ago is worth little. Now return the model to 8 ms and stretch the radio event to 12 ms: three results miss their hop, because the radio outranks the model.
The symptom is a keyword that works for the first few seconds and then reacts later and later. The measurement is a timestamp on each decision against the time of the audio it describes: plot the difference. A flat line is healthy. A line that climbs means a queue grows somewhere. The fix is a bounded queue with a drop policy, a counter for every drop, and the rule from Chapter 3: always push the cheap feature frame, and skip only the expensive model call.
c/* FreeRTOS-style sketch: the callback only signals; the feature task does the work */ static SemaphoreHandle_t hop_ready; /* binary semaphore, one give per hop */ static volatile uint32_t model_skipped, model_done; void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *h) { BaseType_t woken = pdFALSE; xSemaphoreGiveFromISR(hop_ready, &woken); /* tiny: no maths in the interrupt */ portYIELD_FROM_ISR(woken); } void feature_task(void *arg) { /* priority above the model task */ for (;;) { xSemaphoreTake(hop_ready, portMAX_DELAY); ring_window(win, WIN_SAMPLES, 0); make_frame(win, frame); push_frame(frame); if (model_ready() && uxSemaphoreGetCount(model_go) == 0) xSemaphoreGive(model_go); /* model idle: run */ else model_skipped++; /* model still busy: drop this decision, keep the frame */ } }
Chapter 9
Turn cycles into microamps, find where the battery goes, and cut the cost by running the expensive part only when it matters
A battery holds charge, counted in milliamp-hours (mAh). A device that draws 1 mA for an hour uses 1 mAh. Take a small 100 mAh cell, an illustrative size. At a steady 1 mA it lasts 100 hours, just over four days. At 0.1 mA it lasts 1,000 hours, almost six weeks. The whole game is the average current: the total charge used, divided by the time.
A chip does not draw one current. It draws a big current while it works and a tiny one while it sleeps. The nRF52840 product specification gives both numbers. Running CoreMark from flash at 64 MHz, the CPU draws 52 µA for each MHz, which is 52 × 64 = 3,328 µA, or 3.33 mA. In System ON idle, waking on its real-time counter, with no RAM kept, it draws 1.5 µA. That is a ratio of more than 2,000 to 1. So the average depends almost entirely on what share of the time the CPU is awake.
Iavg = duty × Iactive + (1 − duty) × Isleep
The duty cycle is the share of time spent awake. We already know it: it is the busy figure from Chapter 7. With the earbud numbers, the frame takes 0.29 ms and the model 8 ms, in a 20 ms hop. Duty is 8.29 / 20 = 41.5%. The average is 0.415 × 3,328 + 0.585 × 1.5 = about 1,380 µA. On the 100 mAh cell that is 72 hours, three days. The sleep term is a rounding error. Everything comes from the busy time.
The datasheet quotes current per megahertz. Turn that around: 52 µA per MHz means 52 µA × 1 s per million cycles, or 52 picocoulombs of charge per cycle. A cycle costs the same charge at 16 MHz or at 64 MHz. A 18,824-cycle frame costs 18,824 × 52 pC = 0.98 µC however fast the clock runs. Fifty frames a second cost 49 µA. The 500,000-cycle model, 50 times a second, costs 1.3 mA. The frontend is cheap, and the network eats the battery. (The per-MHz figure leaves out static current, so on a real chip finishing fast and sleeping is a little better than this model says.)
That moves the question from “how fast is my clock?” to “how many cycles do I spend per decision, and how many decisions do I make?” You have three levers. Spend fewer cycles per decision: a smaller FFT, fixed point, a smaller network. Make fewer decisions: a longer hop, at the price of delay. Or run the expensive stage only when needed.
Most of the time an earbud hears nothing worth a decision. Silence, traffic, the soft hum of a room. A gate is a tiny test that decides whether the heavy pipeline should run at all. The cheapest gate for audio is the energy of the window: the sum of squares of the 480 samples, which costs about the same as the taper (2,880 cycles), well below the FFT. If the energy is below a threshold, skip the FFT, the filterbank and the network, and go back to sleep. This is how an always-on sensor stays on for months: a small stage watches, and a big stage sleeps until it is woken.
The gate has a cost of its own, and it makes mistakes. Open too often and it saves nothing. Open too rarely and it misses the quiet word. The saving depends on how often something is really there. If sound that needs analysis is present 10% of the time and the gate is perfect, the heavy stages run on 10% of the hops and the average current falls by about 90%. The profile and the plot below put numbers on it.
Top: a model of what a current probe would show over 100 ms. Tall bars are the CPU awake. Bottom: average current against the worst-case delay for every hop, with the gate off (yellow) and on (green). The shaded zone is inside your delay budget.
A model. CPU at 52 µA per MHz and 64 MHz, sleep at 1.5 µA with no RAM kept (nRF52840 product specification; a real pipeline keeps its ring in RAM and runs a microphone, so expect more). Work per hop: frame 0.29 ms plus an illustrative 8 ms model; the gate costs 2,880 cycles (0.045 ms) and is assumed perfect. The 100 mAh cell and the share of time with sound are illustrative. Microphone and radio current are not counted.
At a 20 ms hop with the gate off, the device shows about 1.38 mA and three days. Switch the gate on with sound present 10% of the time: the average falls to roughly 147 µA, and the same cell lasts about 28 days. The hop is the other knob. Lengthen it to 40 ms, still inside an 80 ms budget? The delay is 15 + 40 + 8.3 = 63 ms, so yes, and the gate-off average halves to about 690 µA. Lengthen it to 60 ms and the delay of 83 ms breaks the budget. The best choice is the longest hop that still fits.
The symptom is a device that lasts 3 days when the calculation says 30. The measurement is a current trace from a power profiler, such as Nordic’s Power Profiler Kit II, or a bench supply with a current meter. Look at the baseline between bursts, not at the bursts. If it sits at hundreds of microamps and not at a few, something is still on: a peripheral clock, a microphone, a UART logger, a debug probe, an LED. The fix is to stop each in turn until the baseline drops, then check the bursts.
The idea of an always-on guard for motion appears again in the sensor hub lesson, and the audio version, a wake word on a small chip, is the topic of the always-on listening lesson.
Chapter 10
Keep the numbers, the checklist and the core code, then follow the links onward
A model on a small chip never reads the sensor. It reads what your pipeline makes. The pipeline keeps a ring of recent samples, cuts windows out of it every hop, tapers each window, turns it into a few features, and hands a fixed block to the model on time. Four limits shape every choice: the ring must outlast the lateness, the work must fit in the cycles of a hop, the delay must fit the product, and the average current must fit the battery. Each chapter measured one of them.
| Item | Value | Where it comes from |
|---|---|---|
| micro_speech frontend | 16 kHz, 30 ms window (480 samples), 20 ms stride (320), 40 features, 49 frames, 1,960 inputs, 4 labels | TensorFlow Lite Micro, micro_model_settings.h |
| UCI HAR windows | 50 Hz, 2.56 s windows, 128 readings, 50% overlap, 0.3 Hz low-pass for gravity | UCI dataset page |
| Frames from L samples | floor((L − W) / H) + 1; 16,000 samples at 480 and 320 gives 49 | Derived, Chapter 3 |
| FFT bin width | fs / N: 31.25 Hz for a 512-point FFT at 16 kHz | Derived, Chapter 3 |
| Real FFT in CMSIS-DSP | arm_rfft_fast_f32: lengths 32 to 4,096; N/2 + 1 complex bins packed into N floats | CMSIS-DSP documentation |
| Power and taper calls | arm_cmplx_mag_squared_f32; arm_mult_q15 (saturating) | CMSIS-DSP documentation |
| nRF52840 CPU | Cortex-M4F at 64 MHz, 52 µA per MHz from flash, so 3.33 mA | Nordic product specification |
| nRF52840 sleep | 1.5 µA System ON idle (RTC wake, no RAM kept); 0.4 µA System OFF | Nordic product specification |
| Charge per cycle | 52 pC (52 µA per MHz); 18,824 cycles cost 0.98 µC | Derived, Chapter 9 |
| Cycle counter | DWT at 0xE0001000, CYCCNT +0x004, DEMCR 0xE000EDFC bit 24, CYCCNTENA bit 0 | CMSIS core_cm4.h |
| Ring rule | N ≥ W + L, power of two so index = counter & (N − 1) | Derived, Chapter 2 |
| Rate-monotonic bound | n(21/n − 1): 1.0, 0.828, 0.780, 0.757 for n = 1 to 4; ln 2 = 0.693 as n grows | Liu and Layland |
| Planning model | 6 cycles per sample, 12 per butterfly, 8 per bin, 40 per log, 8 ms model: illustrative, measure yours | This lesson |
c/* the whole pipeline, as one hop of work (Chapters 1 to 8) */ void hop_task(void) { /* runs once per hop, above the model task in priority */ static int16_t win[WIN_SAMPLES]; static int8_t frame[N_MEL]; if (ring_window(win, WIN_SAMPLES, 0) < 0) { overruns++; return; } /* Ch 2: lapped, so drop and count */ arm_mult_q15(win, hann, win_t, WIN_SAMPLES); /* Ch 4: taper (separate output buffer) */ make_frame(win_t, frame); /* Ch 5: FFT, power, mel, log, int8 */ push_frame(frame); /* Ch 3: ring of 49 frames */ if (!model_ready()) return; /* Ch 3: wait for a full stack */ if (gate_open(win)) /* Ch 9: cheap energy test */ signal_model_task_or_skip(); /* Ch 8: never queue unboundedly */ }
This lesson is the bridge between the sensor lessons and the model lessons of the Edge ML track. Behind it: IMU FIFO and timestamps, fixed-point DSP and rings, queues and drops (a later lesson in the real-time track). Ahead: wake words on a small chip, the always-on sensor hub and orientation filters on an MCU. The model side lives in running a network on a Cortex-M, int8 in firmware, accelerators on MCUs and profile and ship, with quantization and TinyEngine from the TinyML series.
For the signal theory behind the frames, see audio representations, the short-time Fourier transform and cepstrum and MFCC. For the system around the pipeline, see the embedded systems intro, RTOS, real-time systems and robot real-time performance. Microphone arrays and echo cancellation sit in front of the pipeline in beamforming and echo cancellation. Estimation on motion data continues in the Kalman filter.
What we did not verify, and say so: micro_speech’s exact band edges, noise-reduction settings and FFT size (we infer 512 from the next power of two above 480); every cycle count outside the DWT register facts is a planning model; and the mel formula is the common one, not a claim about any one library.
Now press Teach and explain the pipeline out loud, from memory: why the ring needs headroom, how the frame count follows from the window and hop, why the taper exists, what the 40 numbers are, how many cycles a hop costs, and what the gate saves. Then go back to the pipeline builder and find the cheapest setting that still meets a 60 ms delay.