Skip to main content

Microphone (mic)

mic is the built-in microphone capture module of the Firefly T1 firmware. It drives the on-board SPM1423 digital microphone over I2S PDM and turns sound into 16-bit PCM data. You can either pull the raw samples and run your own audio analysis, or just call calculate_stats() to get the max, min, and average of one frame — the official "Soundlight" (sound-reactive LED) app in the firmware is built on it, and the examples in this page follow that same algorithm.

Pins are fixed in the module

CLK=GPIO40, DIN=GPIO41. They cannot be changed through the init arguments.

Two functions are enough

Use calculate_stats() for volume, read_data() for raw PCM.

Reads block

A call returns only after a full frame is collected, up to 1 second. Keep it out of button callbacks.

Hardware and Pins​

ItemValue
MicrophoneSPM1423 (PDM digital microphone)
Clock pinGPIO40 (fixed, not configurable)
Data pinGPIO41 (fixed, not configurable)
DriverI2S PDM; the hardware samples continuously at sample_rate
Data format16-bit signed PCM (int16), range -32768 to 32767, silence centered at 0
Module namemic

Once initialization succeeds the microphone samples continuously, with the hardware feeding a DMA buffer, so you only take the buffer when you need it.

Quick Start​

import mic

mic.init(16000, 16, 1, 1024) # sample rate, bit width, channels, buffer size in bytes

for _ in range(5): # grab 5 frames
stats = mic.calculate_stats()
if stats is None:
print("no data in this frame")
else:
print("max={} min={} avg={}".format(stats['max'], stats['min'], stats['avg']))

mic.release() # always release when done

What you will see: in a quiet room max stays within a few hundred and avg hovers around 0. Talk into the microphone or clap once and max jumps to several thousand or more (full scale is 32767), with a matching negative min.

How to Fill In the Init Arguments​

The four arguments of mic.init() have no defaults and must all be provided.

ArgumentMeaningUnitRecommendedNotes
sample_rateSample rateHz16000Plenty for voice detection; 8000 saves resources, 44100 is more detailed
bit_widthBits per samplebits16Pass 16; the module parses the data as 16-bit signed
slot_modeChannel mode—11 = mono, 2 = stereo
buff_sizeBuffer size for one readbytes1024The bytearray you pass later must be at least this long

The buffer size decides both latency and memory, because one read collects the whole buffer before returning:

buff_sizeMemoryApproximate time for one read at 16 kHz / 16-bit mono
10241 KBabout 32 ms
20482 KBabout 64 ms
40964 KBabout 128 ms

For real-time reactions such as sound-reactive LEDs, 1024 is the sweet spot; use 4096 when you want to record a longer clip. The estimate is: time ≈ buff_size ÷ (sample rate × 2).

API Reference​

Initialization mic.init()​

mic.init(sample_rate, bit_width, slot_mode, buff_size)
ArgumentTypeValue
sample_rateintSample rate in Hz, commonly 16000
bit_widthintBit width, pass 16
slot_modeint1 = mono, 2 = stereo
buff_sizeintBuffer size in bytes

No return value. Three things you must know:

  • The pins are fixed: CLK=GPIO40, DIN=GPIO41. They are not configurable and you do not pass them.
  • All four arguments are mandatory; omit one and you get TypeError: Expected 4 arguments: sample_rate, bit_width, slot_mode, buff_size.
  • You must call mic.release() before reconfiguring: the low-level init uses ESP_ERROR_CHECK, so an occupied channel or pin reboots the device instead of raising a Python exception. This is the easiest trap to hit and the hardest to diagnose.

After a successful init the module remembers buff_size, and both read_data() and calculate_stats() read according to it.

Reading raw data mic.read_data()​

bytes_read = mic.read_data(buffer)
ArgumentTypeRequirement
bufferbytearrayLength must be >= the buff_size used at init

Returns an int: the number of bytes actually read.

  • It blocks until the buffer is full (the low-level timeout is 1 second), so this is not an "immediately return the current volume" API.
  • Too small a buffer raises ValueError: Buffer too small for read; calling without init raises RuntimeError: mic not initialized.
  • The data is 16-bit signed PCM; parsing it with a memoryview cast to 'h' is the simplest approach:
import mic

mic.init(16000, 16, 1, 1024)
buf = bytearray(1024)
n = mic.read_data(buf) # blocks until 1024 bytes are collected

samples = memoryview(buf).cast('h', (n // 2,))
peak = max(abs(s) for s in samples)
print("read {} bytes, peak {}".format(n, peak))

mic.release()

Statistics mic.calculate_stats()​

stats = mic.calculate_stats() # returns a dict, or None

No arguments. It allocates a buffer, reads one frame, computes the statistics, and frees the buffer — nothing for you to manage.

KeyTypeMeaning
maxintLargest sample value in this frame
minintSmallest sample value in this frame
avgintAverage sample value in this frame
  • It blocks too (it returns only after a full frame), with the timing shown in the buffer table above.
  • When no data is available it returns None rather than raising, so check if stats is None.
  • Calling it without init raises RuntimeError: mic not initialized.
  • avg is a signed average that stays near 0 in silence; use max and -min to judge loudness.

Releasing resources mic.release()​

mic.release()

No arguments, no return value. It disables and deletes the I2S receive channel and clears the internally recorded buff_size to 0.

  • Afterwards read_data() / calculate_stats() raise RuntimeError: mic not initialized; you must call init() again.
  • Always call it before your app exits, otherwise the next init() will reboot the device because the channel was never released.

Timing and Blocking Behavior​

Your callActual behavior
mic.init(...)Returns immediately; the microphone then samples continuously into a DMA buffer
read_data() / calculate_stats()Blocks until a full frame is collected (≈ buff_size ÷ (sample rate × 2) s), up to 1 second
Quiet roommax within a few hundred, avg ≈ 0
Speech / clapmax jumps to several thousand or more (full scale 32767)
Called inside a button callbackThe whole system stalls for one frame's worth of time; buttons and LED effects become sluggish

Common Pitfalls​

  1. None of the four init() arguments can be omitted, or you get a TypeError.
  2. Call release() before calling init() again. The low-level code uses ESP_ERROR_CHECK, so a conflict reboots the device instead of raising an exception — it looks like "the program reboots as soon as it runs", which is very hard to trace.
  3. buff_size is a byte count, not a sample count. buff_size=1024 only holds 512 16-bit samples.
  4. The bytearray passed to read_data() must be at least buff_size long, or you get a ValueError.
  5. Reads block. They do not return "the volume right now"; they first collect a whole frame, and a larger buff_size means slower reactions.
  6. Judge loudness with max (and -min), not avg. Audio oscillates around 0, so the average barely moves.
  7. calculate_stats() can return None. That is not an exception; just check and retry.
  8. Do not call the microphone APIs from a button callback. Callbacks run in the scheduler context, and blocking for one frame slows the whole system down.

More Recipes​

Sound-reactive LED strip (the same algorithm as the official Soundlight app)​

Sensitivity 5, mute threshold 20, reference amplitude 1000 — these are exactly the values tuned in the official firmware.

import mic
import neopixel
from machine import Pin

NUM_PIXELS = 30
SENSITIVITY = 5 # 1 to 10, higher is more sensitive
MUTE_THRESHOLD = 20 # below this the level is treated as silence
MAX_AMPLITUDE = 1000 # reference amplitude, higher is less sensitive

np = neopixel.NeoPixel(Pin(13), NUM_PIXELS)
mic.init(16000, 16, 1, 1024)


def volume_level(max_value):
level = int((max_value / MAX_AMPLITUDE) * 100 * SENSITIVITY / 5)
if level < MUTE_THRESHOLD:
level = 0
return min(max(level, 0), 100) # 0 to 100


try:
while True:
stats = mic.calculate_stats()
if stats is None:
continue
lit = int(NUM_PIXELS * volume_level(stats['max']) / 100)
for i in range(NUM_PIXELS):
np[i] = (0, 80, 0) if i < lit else (0, 0, 0)
np.write()
finally:
np.fill((0, 0, 0))
np.write()
mic.release()

Detecting "is there any sound"​

import mic
import time

mic.init(16000, 16, 1, 1024)

NOISE_FLOOR = 800 # a peak above this counts as sound

while True:
stats = mic.calculate_stats()
if stats and max(stats['max'], -stats['min']) > NOISE_FLOOR:
print("sound detected")
time.sleep(0.05)

Saving raw PCM to a file​

import mic

mic.init(16000, 16, 1, 4096)
buf = bytearray(4096)

with open('/sd/rec.pcm', 'wb') as f:
for _ in range(25): # 4096 bytes ~ 128 ms/frame, about 3.2 s total
n = mic.read_data(buf)
f.write(memoryview(buf)[:n])

mic.release()

What you will see: rec.pcm appears in the SD card root, containing raw PCM. Open it in Audacity with "Import Raw Data → Signed 16-bit / Little-endian / Mono / 16000 Hz" to play it back.

Complete Example​

Firefly T1 apps live on the SD card under /sd/apps/<app folder>/, with boot.py as the entry point. Save the code below as /sd/apps/my-sound-app/boot.py: the main loop maps volume to LED strip length, a short press of the center key prints the statistics of the current frame, and a long press exits.

import mic
import neopixel
from machine import Pin
from button import Button

NUM_PIXELS = 30
MIN_LEVEL = 500 # peaks below this count as quiet
MAX_LEVEL = 8000 # peaks at this value fill the strip

np = neopixel.NeoPixel(Pin(13), NUM_PIXELS)
mic.init(16000, 16, 1, 1024)

buttons = Button()
running = True
dump_once = False # the callback only sets a flag; the main loop does the work


def on_center_short():
global dump_once
dump_once = True


def on_center_long():
global running
running = False


buttons.register_callback('center', 'short', on_center_short)
buttons.register_callback('center', 'long', on_center_long)

while running:
stats = mic.calculate_stats() # blocks about 32 ms, which is the frame duration
if stats is None:
continue

peak = max(stats['max'], -stats['min'])

if dump_once: # short press: print this frame's statistics
dump_once = False
print("peak {} max={} min={} avg={}".format(
peak, stats['max'], stats['min'], stats['avg']))

level = (peak - MIN_LEVEL) * NUM_PIXELS // (MAX_LEVEL - MIN_LEVEL)
level = min(max(level, 0), NUM_PIXELS)
for i in range(NUM_PIXELS):
np[i] = (0, 90, 0) if i < level else (0, 0, 0)
np.write()

np.fill((0, 0, 0))
np.write()
mic.release() # always release before exiting, or the next init() reboots
buttons.deinit()

Related modules: 5-Way Button (button), WS2812 LED Strip (ws2812), and Buzzer (beep).

Troubleshooting​

SymptomCause / Fix
TypeError: Expected 4 arguments...init() was given too few arguments → all four are required, there are no defaults
The device reboots as soon as init() is calledThe previous session never called release(), or init() was called twice, so the channel/pin conflict trips the assertion → release() first, then init()
RuntimeError: mic not initializedNever called init(), or already called release() → call init() again
ValueError: Buffer too small for readThe bytearray is smaller than buff_size → match its length to buff_size
calculate_stats() returns NoneNo data arrived for this frame → check for None and retry
LED effects respond sluggishly, low frame ratebuff_size too large, each frame takes too long → drop to 1024
avg barely changes even with soundavg is a signed average that cancels out → use max and -min
The strip flickers in a quiet roomGain too sensitive → raise MUTE_THRESHOLD / MAX_AMPLITUDE, or lower the sensitivity
Readings are always 0You did not re-init(), or I2S was initialized twice elsewhere → initialize exactly once, and re-init after release()

AI Usage (Coming Soon)​

Soon you will not have to tune sensitivity or work out the blocking time yourself: describe the audio behavior you want in plain language, and the Agent will follow the API in this document to generate a complete program that runs on the Firefly T1.

For example, just tell it:

Make the LED strip length follow the volume and turn fully off when it is quiet; a short press of the center key shows the current peak on screen, a long press exits.

It will combine mic, neopixel, and Button into a working program and place it in /sd/apps/ for you.

Agent entry (coming soon)

The entry link will go here. Once it is live, one click lets you start describing the app you want.