We're going to use CircuitPython, Mu and the sound sensor built into the Circuit Playground Express to plot sound levels. We'll run this code on our Circuit Playground Express and use Mu to plot the sensor data that CircuitPython prints out.

Save the following as code.py on your Circuit Playground Express board, using the Mu editor:

# SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
#
# SPDX-License-Identifier: MIT

import array
import math
import time

import audiobusio
import board


def mean(values):
    return sum(values) / len(values)


def normalized_rms(values):
    minbuf = int(mean(values))
    sum_of_samples = sum(
        float(sample - minbuf) * (sample - minbuf)
        for sample in values
    )

    return math.sqrt(sum_of_samples / len(values))


mic = audiobusio.PDMIn(
    board.MICROPHONE_CLOCK,
    board.MICROPHONE_DATA,
    sample_rate=16000,
    bit_depth=16
)
samples = array.array('H', [0] * 160)
mic.record(samples, len(samples))

while True:
    mic.record(samples, len(samples))
    magnitude = normalized_rms(samples)
    print(((magnitude),))
    time.sleep(0.1)

Let's look at the code!

First we import audiobusio, time, board, array and math. Then we have two helper functions. The first one uses math to return a mean, or average. It is used in the second helper. The second one uses math to return a normalised rms average. We use these functions to take multiple sound samples really quickly and average them to get a more accurate reading.

Next we set up the microphone object and our samples variable. Then we initialise the mic object so it's ready when we are.

Then we use the mic object to start taking sound samples. We use our normalised rms to find the average of a given set of samples, and we call that the magnitude. Last, we print the magnitude to the serial console.

Note that the Mu plotter looks for tuple values to print. Tuples in Python come in parentheses () with comma separators. If you have two values, a tuple would look like (1.0, 3.14) Since we have only one value, we need to have it print out like (1.0,) note the parentheses around the number, and the comma after the number. Thus the extra parentheses and comma in print(((magnitude),)).

Once you have everything setup and running, try speaking towards the Circuit Playground Express, and watch the plotter immediately react! Move further away from the board to cause smaller changes in the plotter line. Move closer to the board to see bigger spikes!

It's a really easy way to test your microphone and see how it reads sound changes on the Circuit Playground Express!

This guide was first published on Apr 09, 2018. It was last updated on Mar 28, 2024.

This page (Sound) was last updated on Mar 28, 2024.

Text editor powered by tinymce.