code.py
 1  # SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import array
 6  import math
 7  import board
 8  import audiobusio
 9  import neopixel
10  from rainbowio import colorwheel
11  
12  # Increase this number to use this example in louder environments. As you increase the number, it
13  # increases the level of sound needed to change the color of the LEDs. 5 is good for quiet up to
14  # workshop-level settings. If you plan to be in a louder setting, increase this number to maintain
15  # the same behavior as in a quieter setting.
16  magnitude_color_modifier = 5
17  
18  pixels = neopixel.NeoPixel(board.NEOPIXEL, 6, auto_write=False)
19  mic = audiobusio.PDMIn(
20      board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16
21  )
22  
23  
24  def normalized_rms(values):
25      """Normalized Root Mean Square. Removes DC bias before computing RMS."""
26      mean_values = int(sum(values) / len(values))
27      return math.sqrt(
28          sum(float(sample - mean_values) * (sample - mean_values) for sample in values)
29          / len(values)
30      )
31  
32  
33  audio_samples = []  # Create an empty list for sample values
34  while True:
35      sample_array = array.array("H", [0] * 32)
36      mic.record(sample_array, len(sample_array))
37      normalized_samples = normalized_rms(sample_array)  # Calculate normalized sample value
38      audio_samples.append(normalized_samples)  # Add normalized values to the audio samples list
39      audio_samples = audio_samples[-10:]  # Keep only the 10 most recent values in samples list
40      magnitude = sum(audio_samples) / len(audio_samples)  # The average of the last 10 audio samples
41      print(magnitude)
42      # Fill NeoPixels with color based on scaled magnitude
43      pixels.fill(colorwheel(min(255, (magnitude / magnitude_color_modifier))))
44      pixels.show()