Building a Real-Time Ultrasonic Bat Detector with Python

Building a Real-Time Ultrasonic Bat Detector with Python

Bats echolocate at frequencies between 20kHz and 120kHz — well above human hearing. To detect them, you need specialized hardware and software. Here's how I built a real-time bat detector.

Hardware Requirements

  • Ultrasonic microphone capable of 192kHz sampling
  • High-quality ADC with low noise floor
  • Raspberry Pi 4 or laptop for processing
  • The DSP Pipeline

    1. Audio Capture

    Using PyAudio to capture audio at 192kHz. This requires a microphone that can handle ultrasonic frequencies.

    
    import pyaudio
    import numpy as np
    
    RATE = 192000
    CHUNK = 4096
    
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paFloat32,
                    channels=1,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    

    2. Heterodyne Mixing

    Shift ultrasonic frequencies down to the audible range by mixing with a reference frequency.

    3. Spectral Analysis

    Use FFT to identify characteristic frequency patterns of different bat species.

    Species Identification

    Different bat species have distinct call patterns:

  • Pipistrelle: 45-50kHz, FM sweeps
  • Noctule: 20-25kHz, lower frequencies
  • Horseshoe bats: Constant frequency around 80kHz
  • Next Steps

    I'm building a neural network classifier using spectrograms to automate species ID. More on that in a future post.


    Read the full series: Why Bats? · The Bat Sonar Project · Field Recording in Vietnamese Caves