Skip to content

PDMIn on RP2040 sample rate factor-of-two error? #9900

Open
@mediumcrab

Description

@mediumcrab

CircuitPython version

Adafruit CircuitPython 9.2.1 on 2024-11-20; Waveshare RP2040-Plus (16MB) with rp2040
Board ID:waveshare_rp2040_plus_16mb

Code/REPL

import array
import time
import audiobusio
import board
import math

# Constants
SAMPLE_RATE = 22050  # Sample rate in Hz
DURATION = 0.4      # Recording duration in seconds
BUFFER_SIZE = int(SAMPLE_RATE * DURATION)  

# Prepare a buffer to record into
buffer = array.array("H", [0] * BUFFER_SIZE)

with audiobusio.PDMIn(
    board.GP2, 
    board.GP3, 
    sample_rate=SAMPLE_RATE, 
    mono=True,
    oversample=64,
    bit_depth=16,
    startup_delay=0.2
) as mic:
    # discard short period of data
    dump_length = int(SAMPLE_RATE*0.01)
    tmp_buffer = array.array("H", [0] * dump_length)
    while(dump_length > 0):
        samples_read = mic.record(tmp_buffer, len(tmp_buffer))
        dump_length -= samples_read
    print("Recording...")
    offset = 0  
    while offset < len(buffer):
        chunk_size = min(512, len(buffer) - offset)  
        samples_used = mic.record(memoryview(buffer)[offset:offset+chunk_size], chunk_size)  
        offset += samples_used  
    print("Recording complete.")
    with open(f"/audio_data{mic.sample_rate}.bin", "wb") as file:
        file.write(buffer)
        file.flush()
    print("Data written to file")

Behavior

When using the above code, I find that the audio data is half the expected sample rate when I inspect the data. I.e. recording a 500Hz sine tone using this code, I would expect a 22050Hz sample rate, but on inspection I see a 11025Hz sample rate because the plotted waveform from my saved data has a 1kHz frequency.

Attaching a logic analyzer to the Clock and Data pins, I see that the clock frequency is measured at 705kHz. With the args passed to the ctor to the PDMIn object, I would expect 64*22050 = 1411200 i.e. 1.41120MHz clock frequency.. I think?

Happy to dive deeper and see if I can find out what is going on and submit a PR, but just want to know first if I've misunderstood how it is meant to work! Thanks!

Description

The hardware is a Waveshare Pico Plus board, and the PDM mic is the Adafruit PDM MEMS Microphone

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions