import machine
import array
import time
# Define the GPIO pins for I2S connection
sck_pin = machine.Pin(18) # Serial clock pin
ws_pin = machine.Pin(19) # Word select pin (also called L/R clock)
sd_pin = machine.Pin(20) # Serial data pin
# Setup I2S interface
i2s = machine.I2S(
0,
sck=sck_pin,
ws=ws_pin,
sd=sd_pin,
mode=machine.I2S.RX,
bits=16,
format=machine.I2S.MONO,
rate=16000, # Sample rate (can adjust based on your microphone)
ibuf=1024 # Buffer size
)
# Prepare a buffer to store sound data
buffer = array.array('h', [0] * 1024) # h means signed short
def record_sound(duration_ms):
"""Record sound for a given duration in milliseconds."""
start_time = time.ticks_ms()
sound_data = []
print("Recording...")
while time.ticks_diff(time.ticks_ms(), start_time) < duration_ms:
i2s.readinto(buffer) # Read I2S data into buffer
sound_data.extend(buffer) # Append buffer data to the list
print("Recording complete!")
return sound_data
# Record for 5 seconds
recorded_audio = record_sound(5000)
# Optional: Save recorded data to a file (for example, on Pico's filesystem)
with open('audio.raw', 'wb') as f:
f.write(bytearray(recorded_audio))
# Deinitialize I2S when done
i2s.deinit()
print("Sound data saved to audio.raw")