Radar de Batman
Acoustic sonar in the style of The Dark Knight: Python and Raspberry Pi Pico
- Created
- Last substantial change
- Last touch
- Technology
- Python
What does an echo look like?
With an object ahead, a peak crosses the threshold: 16.9 dB at 0.47 m. The gray line shows the empty room.
How it was measured
Evidence
Video demo · View the publication ↗
How it was made
Proof of concept of an active sonar (in the style of the one in The Dark Knight, but honest about its limits): it emits a near-ultrasonic chirp through the speaker, records with the built-in microphone and measures distances to surfaces from the time of flight of the echo.
Safety. Near-ultrasound (18–22 kHz) at high volume bothers dogs and cats (they hear it perfectly) and can damage the tweeters of small speakers, which are not made for sustained energy in that band. The default digital amplitude is low (
0.1) and there is a hard cap (--max-amplitude,0.5by default) that the audio adapter checks before playing. Keep the operating system volume moderate too. If you have pets nearby, use short sessions or the audible band.
Evidence
- Sonar documentation and hardware of the 3D sonar, with materials and wiring.
- Code of the tests on the Raspberry Pi Pico:
pico/.
Measurements




Setup


How it works
- A train of N linear chirps is emitted (by default 18–22 kHz, 8 ms, Tukey window), one every 60 ms, preceded by 50 ms of silence.
sounddevice.playrecplays and records on the same clock, so the N pings are rigidly spaced in the recording.- Zero-phase band-pass filter → matched filter (cross-correlation with the emitted chirp) → Hilbert envelope. The 8 ms chirp (2.7 m long in air) is compressed to a peak of ~0.25 ms.
- t0 = direct path. The first strong arrival is the sound travelling straight from the speaker to the microphone. All distances are measured from that peak, so the unknown latency of the audio system (10–300 ms on Windows) cancels out completely.
- Each of the N pings is re-anchored to its own direct path and they are averaged coherently (noise drops by √N; 16 pings ≈ +12 dB), then aligned with sub-sample precision.
- Optionally, the background profile recorded with
calibrateis subtracted (coupling through the chassis, direct path, table…), with a least-squares gain that absorbs volume changes. - Detection: peaks above an OS-CFAR threshold (local median) and a global minimum SNR, discarding side lobes of stronger arrivals according to the chirp's real autocorrelation.
distance = c · (t_echo − t0) / 2, withc = 331.3·√(1 + T/273.15)(343.2 m/s at 20 °C).
Range resolution: c / (2·B) → 4.3 cm with 4 kHz of bandwidth; 2.1 cm with 8–16 kHz.
Accuracy (not resolution) is sub-centimetre on synthetic data thanks to the parabolic interpolation
of the peak.
Installation
Requires Python ≥ 3.11 and uv.
uv sync # creates .venv with dependencies + dev group (pytest, hypothesis)
uv run sonar --help
On Linux install PortAudio: sudo apt install libportaudio2.
Commands
Global options go before the command, e.g. sonar --band audible --pings 32 ping.
| Global option | Default | Description |
|---|---|---|
--band ultrasonic|audible |
ultrasonic | 18–22 kHz or 8–16 kHz preset |
--f-start/--f-end |
18000/22000 | Manual band (Hz) |
--fs |
48000 | Sample rate |
--chirp-ms, --window |
8, tukey | Chirp duration and window |
--pings |
16 | Averaged pings |
--amplitude, --max-amplitude |
0.1, 0.5 | Amplitude and safety cap |
--temperature, --sound-speed |
20 °C, — | Speed of sound |
--min-range, --max-range |
0.15, 5 m | Search window |
--min-snr |
12 dB | Minimum SNR of an echo |
--direct-path |
0 m | Speaker–microphone separation (corrects the bias) |
--input, --output |
OS default | Index or part of the device name |
sonar devices
Lists devices, host API, channels and supported sample rates. Marks the defaults.
sonar diagnose [--duration 2] [--min-snr 15] [--plot respuesta.png]
Measures ambient noise, plays a 1 kHz → 23 kHz sweep and computes the SNR per frequency. Shows a table per kHz, warns if your current band is outside the hardware's response and recommends, in order of preference: the band ≥ 17 kHz with the highest SNR (nearly inaudible), the one with the highest SNR within the audible fallback 8–16 kHz, or any usable band. Prints the exact command to use.
sonar calibrate [--out .sonar/background.npz]
Records the background profile. Do it at the measuring position, pointing at free space (without the
target in front): everything present when calibrating will be subtracted afterwards. The file stores a
fingerprint of the configuration; if you change band, fs, chirp or interval, ping will reject it and ask you to
recalibrate.
sonar ping [--background RUTA | --no-background] [--plot a.png] [--show] [--json]
One measurement. Prints the strongest echoes (distance, delay, SNR). Uses
.sonar/background.npz automatically if it exists.
sonar live [--history 120]
Real-time A-scan on top and waterfall below. Transient errors (low SNR, clipping) are
shown in the window without breaking the loop. Close the window or press Ctrl+C to exit.
Tip: sonar --pings 4 live refreshes faster.
sonar sweep [--out sweep.png] [--show]
Turn the device by hand; at each position type the angle and press Enter to measure. An empty Enter finishes and produces a radar-style polar plot (angle × distance, colour = SNR, red dot = strongest echo).
Recommended physical setup
- Quiet room, no fans or music. Air conditioning adds in-band noise.
- Device on a table, pointing at a flat, hard wall 0.5–2 m away, with free space between them. Soft surfaces (curtains, sofas) absorb and diffuse.
- To validate: measure the distance with a tape and compare it with
sonar ping; if there is a constant bias, it is the speaker–microphone separation: correct it with--direct-path <metres>. - Avoid surfaces closer than 15 cm (blind zone: the echo overlaps the direct path).
- Calibrate (
sonar calibrate) at the same position but pointing at free space, and do not move the device between calibration and measurement.
System configuration (important)
- Use the built-in microphone and speakers, not a headset (
--input/--output). - Turn off noise suppression, "audio enhancements", echo cancellation and AGC (on Windows: Device properties → Enhancements / Audio effects; apps like "AI Noise-cancelling"). These filters remove precisely the chirp and the echo.
- On Windows prefer the WASAPI device at 48 kHz: MME/DirectSound resample and can cut everything above ~20 kHz.
- Many laptop speakers drop sharply above 18 kHz: if
diagnoseconfirms it, use--band audible(you can hear it, but it works and has better resolution).
Windows: lessons from a real laptop (ASUS ROG/TUF)
- Use exclusive WASAPI (
--host-api WASAPI --exclusive). In shared mode Windows applies the microphone's voice processing (echo cancellation, noise gate, AGC): it erases the chirp after the first pings, adds jitter of tens of samples between pings and cuts above ~8 kHz. - Choose devices by name, not by index: indexes change when you connect or disconnect
a monitor or headphones. Example:
sonar --host-api WASAPI --exclusive --input "Varios micr" --output "Altavoces (Realtek" ping - With the lid closed the built-in microphone turns off.
- Armoury Crate → "Two-way AI noise cancellation" disables the physical microphone and
leaves only a virtual microphone, "AI Noise-cancelling Input". After turning it off you may have to
re-enable the microphone by hand (
mmsys.cpl→ Recording → show disabled devices → Enable) and unmute it. - The first pings come out different because the amplifier is waking from power saving; that is why
the
--warmuppings exist, which are emitted but not averaged. - If the room reverberates, space the pings further apart (
--interval-ms 150–250) so the tail of the previous ping does not add coherently to the next one.
Errors and how they are reported
Each error is shown with a message and a "Cómo resolverlo" (how to fix it) section (exit code 2):
| Situation | Detection |
|---|---|
| Device does not exist | query_devices fails → suggests sonar devices |
| Unsupported sample rate | PortAudio's check_*_settings |
| Microphone permission denied | The recording is exact digital silence (Windows/macOS give no error, they deliver zeros) or PortAudio returns a host error; instructions depend on the OS |
| Clipping | Samples ≥ 0.99 FS → lower amplitude/volume/gain |
| Low SNR | Direct-path SNR < 15 dB in a noisy environment |
| Band outside the response | Quiet environment but the chirp does not appear → suggests diagnose / --band audible |
| Unsafe amplitude | Configuration > cap or signal > cap at the adapter |
| Incompatible background profile | Different configuration fingerprint |
Tests
uv run pytest
They run without hardware: FakeAudioDevice feeds the real chain with a simulator
(sonar.simulation) that models random latency, direct path, reflectors with exact fractional
delays (FFT), the hardware's frequency response, noise and ADC clipping.
They cover: error < 2 cm in distance (including a property test with Hypothesis over distance,
gain, latency and seed), multiple echoes, echoes overlapping in time, echoes below the
resolution, no echoes (no false alarms), low SNR, coherent averaging gain, clipping,
blocked microphone, band outside the response, audible fallback, background subtraction, the full
CLI and the plots.
If pytest cannot write to its system temporary folder, use
uv run pytest --basetemp=.pytest_tmp.
Architecture
src/sonar/
config.py immutable SonarConfig + validation + derived quantities
signal.py chirp, ping train, sweep (pure functions)
audio.py AudioDevice port, sounddevice adapter, FakeAudioDevice
simulation.py synthetic acoustic scene (for the fake and the tests)
processing.py band-pass, matched filter, Hilbert, averaging, background, pipeline
detection.py OS-CFAR + side-lobe rejection → list of echoes
diagnostics.py frequency response and band recommendation
engine.py service: orchestrates device + domain (measure/calibrate/diagnose)
viz.py A-scan, live (A-scan + waterfall), response, polar radar
cli.py typer; thin layer, turns errors into actionable messages
The domain (signal, processing, detection, diagnostics) does no audio I/O; only
audio.SoundDeviceAudio touches sounddevice, and it is imported lazily.
Known limitations
- A single microphone gives no direction: only distance. The "radar" in
sweepdepends on you turning the device and on the (poor) directivity of the speaker. - Laptop speakers/microphones are not specified above 20 kHz; the response varies a lot
between models.
diagnoseexists for that reason. - Small or soft surfaces return weak echoes; walls and doors work better.
- Background subtraction assumes a static scene: moving the device or large temperature changes leave residue; recalibrate.
Life line
- Code1 change in the code: docs: link the README to its log entry, RZ-001View source ↗
- PublicationYouTube · Radar de BatmanView source ↗
- PublicationTikTok · Radar de BatmanView source ↗
- PublicationLinkedIn · Radar de BatmanView source ↗
- No released code versions.
- No corrections.
- No failed attempts recorded.
Where it lives
Comes from here
Found an error? Report it in the repository ↗
- Witness
- docs: link the README to its log entry, RZ-001
- Date
- 2026-11-06