KNIFE-020 – micro:bit V2 whistle detection pipeline
📅 2026-11-17 · stav: rozpracované (PC pipeline overená, nasadenie na zariadenie čaká) · priorita: vysoká · ✍️ Aymeric
The question: the audio hardware moved from the ESP32-S3 + INMP441 to the BBC micro:bit V2 (KNIFE-019). Can the whistle detector be adapted to the new microphone and squeezed into 128 KiB of RAM without losing accuracy?
Short answer:
- Yes, on the PC so far. The model is trained, the audio frontend is validated, and the network was redesigned to fit the micro:bit resource budget.
- V4 DS-CNN: 46.9 k parameters, 2.33 M MACs, about 54 KiB as an INT8 model and about 38 KiB of peak activations. It reaches 0.99 clean / 1.00 simulated micro:bit balanced validation accuracy.
- Real-time detection works from a PC microphone at a threshold of 0.97.
- What remains is embedded deployment: INT8 quantization, CMSIS-DSP / CMSIS-NN and measurements on the real board. The model design itself is done.
Current pipeline:
microphone audio
→ 16 kHz mono signal
→ 2 s active window
→ STFT
→ 64-band log-Mel representation
→ compact DS-CNN
→ P(Whistle)
→ decision threshold
Remaining work:
PyTorch V4
→ INT8 quantization
→ CMSIS-DSP frontend
→ CMSIS-NN inference
→ micro:bit microphone acquisition
→ speaker response
→ on-device validation
Why V4 was necessary
The previous V3 classifier was developed for the ESP32-S3 + INMP441 architecture. It classified very well, but the hardware later changed to a BBC micro:bit V2 to reduce:
- component count;
- wiring;
- integration uncertainty;
- mechanical failure points;
- overall cost.
The micro:bit V2 provides:
| Feature | Value |
|---|---|
| SoC | Nordic nRF52833 |
| CPU | 64 MHz Cortex-M4F |
| Flash | 512 kB |
| RAM | 128 kB |
| Microphone | integrated analog MEMS (Knowles SPU0410LR5H-QB-7) |
| Speaker | integrated |
Manufacturer specifications of the microphone used in the acquisition model:
| Parameter | Value |
|---|---|
| Nominal sensitivity | −38 dBV/Pa |
| Sensitivity tolerance | ±3 dB |
| Typical SNR | 63 dB(A) |
| Acoustic overload point | 118 dB SPL |
| Output impedance | ≤ 400 Ω |
The hardware change required two separate adaptations:
- replace the INMP441 acquisition model with a micro:bit V2 model;
- redesign the DS-CNN so that its intermediate activations fit safely inside the micro:bit RAM budget.
Dataset
V4 keeps the same MLEnd Hums & Whistles subset as the previous experiments: 1,064 recordings from 37 interpreters, in two classes, Hum and Whistle.
The split is speaker-independent: each person belongs to only one of training, validation or test. This is essential. A random file split could put recordings of the same person in both training and test data and give an unrealistically optimistic estimate of generalisation.
| Split | Samples | Interpreters | Hum | Whistle |
|---|---|---|---|---|
| Training | 711 | 25 | 521 | 190 |
| Validation | 144 | 5 | 106 | 38 |
| Test | 209 | 7 | 153 | 56 |
| Total | 1,064 | 37 | 780 | 284 |
The split manifests are frozen as:
data/splits/train.csv
data/splits/validation.csv
data/splits/test.csv
data/splits/split_summary.json
Each split also gets a SHA-256 hash, so the exact partition can be reproduced later.
Audio preparation
Every recording is first converted to a deterministic input format:
audio file
→ mono
→ resample to 16 kHz
→ select 2 s active region
→ exactly 32,000 samples
- Short recordings are zero-padded at the end.
- Longer recordings: candidate 2 s windows are evaluated every 250 ms.
- In validation and testing, the highest-energy window is chosen deterministically.
- In training, one window is sampled from the five highest-energy candidates.
This gives some temporal variation in training while keeping evaluation reproducible.
Log-Mel frontend
The CNN does not process raw audio. Each 2 s waveform is turned into a time-frequency representation:
16 kHz mono audio
→ 32,000 samples
→ Hann window
→ STFT
→ power spectrum
→ 64 Mel filters
→ logarithmic dB scale
→ normalization
→ 1 × 64 × 201 tensor
The frozen configuration:
| Parameter | Value |
|---|---|
| Sample rate | 16,000 Hz |
| Clip length | 2.0 s |
| Samples | 32,000 |
| FFT size | 512 |
| Hop length | 160 |
| FFT interval | 10 ms |
| Mel bands | 64 |
| Minimum frequency | 100 Hz |
| Maximum frequency | 8,000 Hz |
| Dynamic range | 80 dB |
| Output | 1 × 64 × 201 |
The steps:
- FFT: a 512-point real FFT gives 257 non-redundant frequency bins.
- Power: the power spectrum is |X[k]|².
- Mel: the filter bank reduces the 257 bins to 64 perceptually spaced bands.
- dB: power is converted to dB relative to the strongest point of the spectrogram. The maximum energy becomes 0 dB, and the minimum retained value is −80 dB.
- Normalisation: values are mapped to [−1, +1] with
normalized = dB / 40 + 1:
| dB | Normalised |
|---|---|
| −80 dB | −1 |
| −40 dB | 0 |
| 0 dB | +1 |
The classifier input is therefore 1 × 64 × 201: 1 input channel, 64 Mel frequency bands and 201 time frames.
Frontend reproducibility
For V4, the frontend was rewritten explicitly instead of relying on a single high-level Librosa call. The implementation exposes each of these steps:
- the Hann window;
- the Mel filter bank;
- the STFT framing;
- the power calculation;
- the dB conversion;
- the normalisation.
This matters because these exact constants will later be exported to the micro:bit firmware.
The explicit implementation was compared numerically with the original Librosa reference:
| Metric | Difference |
|---|---|
| Maximum absolute error | ≈ 1.6 × 10⁻⁵ |
| Mean absolute error | ≈ 8.5 × 10⁻⁷ |
The two are numerically equivalent for this application. This also prepares the ground for golden-vector tests between Python and C/C++.
micro:bit V2 acquisition model
Training directly on clean MLEnd recordings would assume that the future microphone behaves exactly like the devices the dataset was recorded on. Instead, V4 adds a lightweight simulation of the micro:bit V2 acquisition chain in front of the Mel frontend.
The model deliberately keeps three kinds of parameters apart:
- manufacturer specifications;
- derived circuit parameters;
- training-only robustness augmentation.
Manufacturer-derived microphone response
The microphone is modelled with the approximate free-field response of the SPU0410LR5H-QB-7. It is almost flat through most of the useful whistle range:
- a small attenuation near 100 Hz;
- approximately flat around 1–3 kHz;
- a slight rise toward the upper frequencies.
These values approximate the manufacturer's curve. They are not calibration measurements of the actual NightJar enclosure.
Analog high-pass approximation
The micro:bit schematic uses 33 kΩ, 1 kΩ and a 1 µF coupling capacitor. The equivalent bias resistance:
Rbias = 33 kΩ || 1 kΩ ≈ 970.6 Ω
With the microphone output impedance between about 0 Ω and its specified maximum of 400 Ω, the first-order AC-coupling approximation fc = 1 / (2πRC) gives:
fc ≈ 116.12 – 163.98 Hz
This cutoff is derived from the circuit. It is not an arbitrary fixed value. A real-board measurement will still be needed after firmware integration.
Training-domain randomisation
During training, the simulated channel varies the microphone sensitivity, the frequency-response perturbation, relative noise, clipping, quantization and the analog high-pass cutoff.
| Parameter | Nominal training | Stress test |
|---|---|---|
| Sensitivity | ±3 dB | |
| Response jitter | ±1 dB | |
| Relative SNR | 45–63 dB | 35–50 dB |
| Clipping probability | 5 % | 15 % |
| Effective quantization | ~12 bit |
The SNR and clipping distributions are robustness augmentations, not manufacturer specifications. The dataset has no calibrated sound-pressure levels, so reading this as a physically exact self-noise simulation would be wrong.
Why the V3 DS-CNN could not simply be reused
The previous V3 architecture:
Input 1 × 64 × 201
→ Conv 1 → 32
→ DS 32 → 64
→ DS 64 → 128
→ DS 128 → 192
→ DS 192 → 256
→ DS 256 → 256
→ Global Average Pooling
→ Linear 256 → 2
It had 160,066 trainable parameters: about 625 KiB of FP32 weights, or 156 KiB in INT8.
The parameter count was not the main problem. The first activation, after the initial convolution, was about:
32 × 32 × 101 = 103,424 values ≈ 101 KiB in INT8
The micro:bit V2 has only 128 KiB of RAM in total. That would leave almost nothing for:
- the runtime;
- the stack;
- microphone buffers;
- FFT workspaces;
- Mel features;
- CMSIS-NN scratch memory.
The architecture therefore had to change before deployment.
V4 micro:bit-balanced DS-CNN
V4 keeps a substantial network while controlling the largest activation:
Input 1 × 64 × 201
→ 5 × 5 Conv 1 → 16 stride (2, 4)
→ DS block 16 → 32 stride (2, 2)
→ DS block 32 → 64 stride (2, 2)
→ DS block 64 → 96 stride (2, 2)
→ DS block 96 → 128
→ DS block 128 → 160
→ Global Average Pooling
→ Dropout 0.20
→ Linear 160 → 2
→ NotWhistle / Whistle
The larger temporal stride in the first layer is intentional. Instead of the old 32 × 32 × 101 activation, V4 produces:
16 × 32 × 51 = 26,112 values ≈ 25.5 KiB INT8
That leaves much more memory margin without making the classifier too small.
Embedded resource audit
The V4 project includes an automatic deployment audit. Measured architecture:
| Metric | Value | Approx. |
|---|---|---|
| Trainable parameters | 46,882 | 46.9 k |
| MACs / inference | 2,331,072 | 2.33 M |
| INT8 convolution weights | 45,216 B | 44.2 KiB |
| Estimated INT8 model blob | 55,224 B | 53.9 KiB |
| Peak INT8 tensor pair | 38,976 B | 38.1 KiB |
| Reserved scratch budget | 12,288 B | 12 KiB |
| Estimated working set (tensors + scratch) | 51,264 B | 50.1 KiB |
The project enforces these design gates, and all current V4 checks pass:
| Gate | Limit | V4 |
|---|---|---|
| INT8 model blob | < 64 KiB | 53.9 KiB ✅ |
| Peak tensor pair | < 48 KiB | 38.1 KiB ✅ |
| MACs | < 3 million | 2.33 M ✅ |
| Working set | < 128 KiB | 50.1 KiB ✅ |
These numbers are pre-deployment engineering estimates. Final memory acceptance still needs the compiled firmware's linker map and a runtime memory measurement on the micro:bit.
Training configuration
| Setting | Value |
|---|---|
| Optimizer | AdamW |
| Batch size | 64 |
| Maximum epochs | 30 |
| Initial learning rate | 1e-3 |
| Weight decay | 2e-4 |
| Label smoothing | 0.02 |
| Gradient clipping | 5.0 |
| Dropout | 0.20 |
| Random seed | 42 |
| micro:bit augmentation | 80 % of training examples |
| Early stopping patience | 8 epochs |
Mixed precision is enabled when CUDA is available. Class weights are computed automatically from the training manifest to compensate for the Hum / Whistle imbalance.
Model selection
Each epoch is evaluated in two domains:
Clean validation:
original validation waveform → log-Mel frontend → classifier
Nominal micro:bit validation:
original validation waveform → deterministic micro:bit acquisition model → log-Mel frontend → classifier
The checkpoint selection score:
selection score = 0.5 × clean balanced accuracy + 0.5 × micro:bit balanced accuracy
This keeps the model from being chosen only for its clean-data performance, or only for the simulated hardware domain.
Training result
Training stopped automatically after 8 epochs without validation improvement, at epoch 19. The best checkpoint reached:
| Metric | Value |
|---|---|
| Clean validation balanced accuracy | 0.9906 |
| micro:bit validation balanced accuracy | 1.0000 |
| Selection score | 0.995283 |
| Calibrated whistle threshold | ≈ 0.953 |
The checkpoint is stored as models/best_model_v4_microbit.pt.
This is encouraging: the reduced embedded architecture kept about the same validation performance as the much larger V3. It is not a strict V3-versus-V4 benchmark, though, because the train/validation/test partition changed slightly.
Held-out test evaluation
The V4 test set has 209 recordings (153 Hum, 56 Whistle) from 7 completely unseen interpreters.
Final V4 test metrics are intentionally not reported yet. They must be produced from the frozen checkpoint with python -m src.evaluate before this KNIFE is finalised.
The final table will include accuracy, balanced accuracy, macro-F1, false positives and false negatives, each on the clean test, the nominal micro:bit test and the stress micro:bit test. Keeping them separate avoids presenting validation results as test performance.
Real microphone test
The trained V4 model was also run in real time from a PC microphone:
PC microphone
→ native sample stream
→ resample to 16 kHz
→ rolling 2 s window
→ log-Mel frontend
→ V4 DS-CNN
→ P(Whistle)
The model runs repeatedly on the rolling window instead of waiting for a new independent 2 s recording each time.
The first live test showed that tonal computer noise could push whistle confidence above the automatically calibrated threshold. For the live PC experiment, the runtime threshold was raised to 0.97. With that threshold, real whistle detection worked correctly in the manual test.
0.97 is an empirical operating point for the PC microphone. It is not yet the final NightJar threshold, which must be calibrated with the actual micro:bit microphone and enclosure.
Important limitation: Hum is not every non-whistle sound
The source dataset contains only Hum and Whistle. Internally, V4 treats Hum as the negative class, NotWhistle, but the training set does not yet contain a representative sample of:
- speech;
- keyboard noise;
- fan noise;
- handling noise;
- room ambience;
- music;
- silence;
- NightJar speaker feedback.
The PC live test already shows why this matters: a tonal environmental noise can look more whistle-like than a Hum recording.
For deployment, there are two complementary protections:
- a conservative probability threshold;
- real environmental negative examples, added if field testing shows significant false triggers.
A temporal confirmation rule can also be added:
high P(Whistle) on multiple consecutive windows → confirmed whistle
This should be evaluated once the real micro:bit acquisition path works.
Software validation
Before training, the complete V4 Python pipeline passed:
- micro:bit channel determinism test;
- dataset round-trip test;
- frontend shape / equivalence test;
- model forward / audit test;
- training smoke test.
Result: 4 core tests passed.
The channel self-test produced:
input samples 32000
sample rate 16000 Hz
derived HP range 116.12 – 163.98 Hz
deterministic True
finite True
The complete frontend produced:
waveform (32000,)
simulated channel (32000,)
CNN tensor (1, 64, 201)
range [-1, 1]
finite True
This confirms that the PC reference implementation is internally consistent.
What is validated now
| ✅ Validated | ⏳ Still to validate on hardware |
|---|---|
| MLEnd dataset parsing | real micro:bit microphone waveform |
| speaker-independent split | actual embedded signal scaling |
| audio loading | Python ↔ C++ frontend parity |
| resampling | INT8 model accuracy |
| active-window extraction | CMSIS-NN inference latency |
| STFT | real RAM usage |
| Mel filter bank | real Flash usage |
| dB conversion | false triggers / hour |
| normalisation | speaker feedback behaviour |
| micro:bit V2 channel approximation | wooden-enclosure acoustic effects |
| DS-CNN architecture | |
| resource audit | |
| training | |
| checkpoint selection | |
| threshold calibration | |
| PC live inference |
Next deployment step
The machine-learning design is now stable enough to move to the embedded implementation:
best_model_v4_microbit.pt
→ fold BatchNorm
→ quantize network to INT8
→ compare FP32 and INT8 predictions
→ export: weights, biases, quantization scales,
Hann window, Mel filter coefficients, golden vectors
→ implement 16 kHz microphone acquisition on micro:bit
→ CMSIS-DSP: Hann, RFFT, power, Mel, log, normalization
→ CMSIS-NN: Conv, depthwise Conv, pointwise Conv, pooling, fully connected
→ whistle probability
→ decision logic
→ speaker response
→ cooldown
→ listen again
Golden-vector validation comes before relying on live acoustic tests:
same reference waveform
→ Python frontend
→ embedded frontend
→ compare intermediate values
This is essential: a correct CNN can still fail if the FFT scaling, the Mel filters or the normalisation differ between Python and the firmware.
Current project files
| Purpose | Files |
|---|---|
| Main V4 checkpoint | models/best_model_v4_microbit.pt |
| Reproducible split | data/splits/train.csv, validation.csv, test.csv, split_summary.json |
| Training history and audit | outputs/logs/training_history.csv, outputs/logs/model_audit.json |
| Reference implementation | src/audio.py, src/features.py, src/microbit_channel.py, src/dataset.py, src/model.py, src/model_audit.py, src/train.py, src/evaluate.py |
Current engineering conclusion
The project has moved from a proof-of-concept classifier to an architecture designed around the actual embedded target. The key result is not only the classification score. V4 achieves all of these at once:
- ≈ 99 % balanced validation performance;
- robustness to the nominal simulated micro:bit channel;
- 46.9 k trainable parameters;
- 2.33 M MACs per inference;
- ≈ 54 KiB estimated INT8 model blob;
- ≈ 38 KiB peak activation pair;
- successful real-microphone whistle detection.
The previous V3 network was statistically strong but did not fit the micro:bit memory budget. V4 keeps comparable classification capability while shrinking the model and activation footprint enough to make real Cortex-M4 deployment credible.
The remaining uncertainty is now where it should be:
- real hardware acquisition;
- INT8 numerical parity;
- runtime latency and memory;
- environmental false positives;
- final enclosure acoustics.
These will be measured directly on the micro:bit instead of guessed in software.