Skip to main content

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:

FeatureValue
SoCNordic nRF52833
CPU64 MHz Cortex-M4F
Flash512 kB
RAM128 kB
Microphoneintegrated analog MEMS (Knowles SPU0410LR5H-QB-7)
Speakerintegrated

Manufacturer specifications of the microphone used in the acquisition model:

ParameterValue
Nominal sensitivity−38 dBV/Pa
Sensitivity tolerance±3 dB
Typical SNR63 dB(A)
Acoustic overload point118 dB SPL
Output impedance≤ 400 Ω

The hardware change required two separate adaptations:

  1. replace the INMP441 acquisition model with a micro:bit V2 model;
  2. 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.

SplitSamplesInterpretersHumWhistle
Training71125521190
Validation144510638
Test209715356
Total1,06437780284

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:

ParameterValue
Sample rate16,000 Hz
Clip length2.0 s
Samples32,000
FFT size512
Hop length160
FFT interval10 ms
Mel bands64
Minimum frequency100 Hz
Maximum frequency8,000 Hz
Dynamic range80 dB
Output1 × 64 × 201

The steps:

  1. FFT: a 512-point real FFT gives 257 non-redundant frequency bins.
  2. Power: the power spectrum is |X[k]|².
  3. Mel: the filter bank reduces the 257 bins to 64 perceptually spaced bands.
  4. 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.
  5. Normalisation: values are mapped to [−1, +1] with normalized = dB / 40 + 1:
dBNormalised
−80 dB−1
−40 dB0
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:

MetricDifference
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.

ParameterNominal trainingStress test
Sensitivity±3 dB
Response jitter±1 dB
Relative SNR45–63 dB35–50 dB
Clipping probability5 %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:

MetricValueApprox.
Trainable parameters46,88246.9 k
MACs / inference2,331,0722.33 M
INT8 convolution weights45,216 B44.2 KiB
Estimated INT8 model blob55,224 B53.9 KiB
Peak INT8 tensor pair38,976 B38.1 KiB
Reserved scratch budget12,288 B12 KiB
Estimated working set (tensors + scratch)51,264 B50.1 KiB

The project enforces these design gates, and all current V4 checks pass:

GateLimitV4
INT8 model blob< 64 KiB53.9 KiB ✅
Peak tensor pair< 48 KiB38.1 KiB ✅
MACs< 3 million2.33 M ✅
Working set< 128 KiB50.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​

SettingValue
OptimizerAdamW
Batch size64
Maximum epochs30
Initial learning rate1e-3
Weight decay2e-4
Label smoothing0.02
Gradient clipping5.0
Dropout0.20
Random seed42
micro:bit augmentation80 % of training examples
Early stopping patience8 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:

MetricValue
Clean validation balanced accuracy0.9906
micro:bit validation balanced accuracy1.0000
Selection score0.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.

note

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:

  1. a conservative probability threshold;
  2. 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 parsingreal micro:bit microphone waveform
speaker-independent splitactual embedded signal scaling
audio loadingPython ↔ C++ frontend parity
resamplingINT8 model accuracy
active-window extractionCMSIS-NN inference latency
STFTreal RAM usage
Mel filter bankreal Flash usage
dB conversionfalse triggers / hour
normalisationspeaker feedback behaviour
micro:bit V2 channel approximationwooden-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​

PurposeFiles
Main V4 checkpointmodels/best_model_v4_microbit.pt
Reproducible splitdata/splits/train.csv, validation.csv, test.csv, split_summary.json
Training history and auditoutputs/logs/training_history.csv, outputs/logs/model_audit.json
Reference implementationsrc/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.


← KNIFE-019 · ↩️ Všetky KNIFE príspevky · KNIFE-021 →