Skip to content

Instantly share code, notes, and snippets.

@sampoder
Created November 23, 2020 01:51
Show Gist options
  • Save sampoder/374fc57a01a08514f3946c02c1cec5fc to your computer and use it in GitHub Desktop.
Save sampoder/374fc57a01a08514f3946c02c1cec5fc to your computer and use it in GitHub Desktop.
import array
import math
import time
import audiobusio
import board
import time
import neopixel
from adafruit_circuitplayground import cp
pixels = cp.pixels
def genRainbowColourValue(pos):
if pos < 0 or pos > 255:
return (0, 0, 0)
if pos < 85:
return (255 - pos * 3, pos * 3, 0)
if pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3)
pos -= 170
return (pos * 3, 0, 255 - pos * 3)
def color_wipe(color, wait, amount):
if amount > 10:
amount = 10
for i in range(amount):
pixels[i] = color
time.sleep(wait)
pixels.show()
def rainbow_cycle(wait, amount):
if amount > 10:
amount = 10
for j in range(42):
for i in range(amount):
rc_index = (i * 256 // 10) + j*6 * 5
pixels[i] = genRainbowColourValue(rc_index & 255)
if cp.button_a:
break
pixels.show()
def color_wipe_backwards(color, wait, amount):
for i in range(10 - amount):
pixels[10-1-i] = color
time.sleep(0.01)
pixels.show()
OFF = (0, 0, 0)
colours = [(255, 0, 0), (255, 150, 0), (0, 255, 0), (0, 255, 255), (0, 0, 255), (180, 0, 255)]
current_colour = 0
rainbow = 0
def mean(values):
return sum(values) / len(values)
def normalized_rms(values):
minbuf = int(mean(values))
sum_of_audio_recording = sum(
float(sample - minbuf) * (sample - minbuf)
for sample in values
)
return math.sqrt(sum_of_audio_recording / len(values))
mic = audiobusio.PDMIn(
board.MICROPHONE_CLOCK,
board.MICROPHONE_DATA,
sample_rate=16000,
bit_depth=16
)
audio_recording = array.array('H', [0] * 160)
mic.record(audio_recording, len(audio_recording))
mic.record(audio_recording, len(audio_recording))
base_magnitude = normalized_rms(audio_recording)
peak_magnitude = 70 * 5
while True:
if cp.switch == True:
if cp.button_a:
rainbow = 0
if current_colour + 1 == len(colours):
current_colour = -1
current_colour+=1
if cp.button_b:
rainbow = 1
mic.record(audio_recording, len(audio_recording))
magnitude = normalized_rms(audio_recording)
print(((round((((magnitude)/peak_magnitude)*10))), 0))
color_wipe_backwards(OFF, 0.1, round((((magnitude)/peak_magnitude)*10)))
color_wipe(colours[current_colour], 0.001, round((((magnitude)/peak_magnitude)*10)))
if rainbow==1:
rainbow_cycle(0.01, round((((magnitude)/peak_magnitude)*10)))
if cp.switch == False:
color_wipe_backwards(OFF, 0.1, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment