|
| 1 | +# SPDX-FileCopyrightText: 2022 Liz Clark for Adafruit Industries |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +import time |
| 5 | +import array |
| 6 | +import math |
| 7 | +import board |
| 8 | +import audiobusio |
| 9 | +import simpleio |
| 10 | +import neopixel |
| 11 | + |
| 12 | +# neopixel setup |
| 13 | +pixel_pin = board.A0 |
| 14 | + |
| 15 | +pixel_num = 16 |
| 16 | + |
| 17 | +pixels = neopixel.NeoPixel(pixel_pin, pixel_num, brightness=0.1, auto_write=False) |
| 18 | + |
| 19 | +# function to average mic levels |
| 20 | +def mean(values): |
| 21 | + return sum(values) / len(values) |
| 22 | + |
| 23 | +# function to return mic level |
| 24 | +def normalized_rms(values): |
| 25 | + minbuf = int(mean(values)) |
| 26 | + samples_sum = sum( |
| 27 | + float(sample - minbuf) * (sample - minbuf) |
| 28 | + for sample in values |
| 29 | + ) |
| 30 | + |
| 31 | + return math.sqrt(samples_sum / len(values)) |
| 32 | + |
| 33 | +# mic setup |
| 34 | +mic = audiobusio.PDMIn(board.TX, |
| 35 | + board.A1, sample_rate=16000, bit_depth=16) |
| 36 | +samples = array.array('H', [0] * 160) |
| 37 | + |
| 38 | +# variable to hold previous mic level |
| 39 | +last_input = 0 |
| 40 | + |
| 41 | +# neopixel colors |
| 42 | +GREEN = (0, 127, 0) |
| 43 | +RED = (127, 0, 0) |
| 44 | +YELLOW = (127, 127, 0) |
| 45 | +OFF = (0, 0, 0) |
| 46 | + |
| 47 | +# array of colors for VU meter |
| 48 | +colors = [GREEN, GREEN, GREEN, GREEN, GREEN, GREEN, GREEN, GREEN, |
| 49 | + GREEN, YELLOW, YELLOW, YELLOW, YELLOW, YELLOW, RED, RED] |
| 50 | + |
| 51 | +# begin with pixels off |
| 52 | +pixels.fill(OFF) |
| 53 | +pixels.show() |
| 54 | + |
| 55 | +while True: |
| 56 | + # take in audio |
| 57 | + mic.record(samples, len(samples)) |
| 58 | + # magnitude holds the value of the mic level |
| 59 | + magnitude = normalized_rms(samples) |
| 60 | + # uncomment to see the levels in the REPL |
| 61 | + # print((magnitude,)) |
| 62 | + |
| 63 | + # mapping the volume range (125-500) to the 16 neopixels |
| 64 | + # volume range is optimized for music. you may want to adjust the range |
| 65 | + # based on the type of audio that you're trying to show |
| 66 | + mapped_value = simpleio.map_range(magnitude, 125, 500, 0, 16) |
| 67 | + # converting the mapped range to an integer |
| 68 | + input_val = int(mapped_value) |
| 69 | + |
| 70 | + # if the mic input has changed from the last input value... |
| 71 | + if last_input != input_val: |
| 72 | + for i in range(input_val): |
| 73 | + # if the level is lower... |
| 74 | + if last_input > input_val: |
| 75 | + for z in range(last_input): |
| 76 | + # turn those pixels off |
| 77 | + pixels[z] = (OFF) |
| 78 | + # turn on pixels using the colors array |
| 79 | + pixels[i] = (colors[i]) |
| 80 | + pixels.show() |
| 81 | + # update last_input |
| 82 | + last_input = input_val |
| 83 | + |
| 84 | + time.sleep(0.01) |
0 commit comments