/ Labo_Piano_Light_FX / code.py
code.py
1 # SPDX-FileCopyrightText: 2018 Collin Cunningham for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import board 6 from rainbowio import colorwheel 7 import neopixel 8 from analogio import AnalogIn 9 10 n_pixels = 10 # Number of pixels you are using 11 dc_offset = 0 # DC offset in mic signal - if unusure, leave 0 12 noise = 100 # Noise/hum/interference in mic signal 13 lvl = 10 # Current "dampened" audio level 14 maxbrt = 127 # Maximum brightness of the neopixels (0-255) 15 wheelStart = 0 # Start of the RGB spectrum we'll use 16 wheelEnd = 255 # End of the RGB spectrum we'll use 17 18 mic_pin = AnalogIn(board.A7) 19 20 # Set up NeoPixels and turn them all off. 21 strip = neopixel.NeoPixel(board.NEOPIXEL, n_pixels, 22 brightness=0.1, auto_write=False) 23 strip.fill(0) 24 strip.show() 25 26 27 def remapRangeSafe(value, leftMin, leftMax, rightMin, rightMax): 28 # this remaps a value from original (left) range to new (right) range 29 30 # Force the input value to within left min & max 31 if value < leftMin: 32 value = leftMin 33 if value > leftMax: 34 value = leftMax 35 36 # Figure out how 'wide' each range is 37 leftSpan = leftMax - leftMin 38 rightSpan = rightMax - rightMin 39 40 # Convert the left range into a 0-1 range (int) 41 valueScaled = int(value - leftMin) / int(leftSpan) 42 43 # Convert the 0-1 range into a value in the right range. 44 return int(rightMin + (valueScaled * rightSpan)) 45 46 47 while True: 48 n = int((mic_pin.value / 65536) * 1000) # 10-bit ADC format 49 n = abs(n - 512 - dc_offset) # Center on zero 50 51 if n >= noise: # Remove noise/hum 52 n = n - noise 53 54 # "Dampened" reading (else looks twitchy) - divide by 8 (2^3) 55 lvl = int(((lvl * 7) + n) / 8) 56 57 # Color pixels based on rainbow gradient 58 vlvl = remapRangeSafe(lvl, 0, 255, wheelStart, wheelEnd) 59 for i in range(0, len(strip)): 60 strip[i] = colorwheel(vlvl) 61 # Set strip brightness based oncode audio level 62 brightness = remapRangeSafe(lvl, 50, 255, 0, maxbrt) 63 strip.brightness = float(brightness) / 255.0 64 strip.show()