Skip to content

Commit bd04d37

Browse files
authored
Add files via upload
1 parent 4b9da13 commit bd04d37

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# SPDX-FileCopyrightText: 2018 John Edgar Park for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import time
6+
import math
7+
import array
8+
import audiobusio
9+
import audioio
10+
import audiocore
11+
import board
12+
from adafruit_crickit import crickit
13+
14+
# Number of samples to read at once.
15+
NUM_SAMPLES = 160
16+
17+
# Remove DC bias before computing RMS.
18+
def normalized_rms(values):
19+
minbuf = int(mean(values))
20+
samples_sum = sum(
21+
float(sample - minbuf) * (sample - minbuf)
22+
for sample in values
23+
)
24+
25+
return math.sqrt(samples_sum / len(values))
26+
27+
def mean(values):
28+
return sum(values) / len(values)
29+
30+
mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA,
31+
sample_rate=16000, bit_depth=16)
32+
33+
# Record an initial sample to calibrate. Assume it's quiet when we start.
34+
samples = array.array('H', [0] * NUM_SAMPLES)
35+
mic.record(samples, len(samples))
36+
37+
head_servo = crickit.servo_1
38+
head_servo.set_pulse_width_range(min_pulse=500, max_pulse=2500)
39+
head_servo.angle = 90 # center the head.
40+
41+
# Set audio out on speaker.
42+
a = audioio.AudioOut(board.A0)
43+
44+
# Start playing the file (in the background).
45+
def play_file(wavfile):
46+
print("Playing scream!")
47+
with open(wavfile, "rb") as f:
48+
wav = audiocore.WaveFile(f)
49+
a.play(wav)
50+
while a.playing:
51+
head_servo.angle = 60
52+
time.sleep(.01)
53+
head_servo.angle = 120
54+
time.sleep(.01)
55+
56+
57+
while True:
58+
mic.record(samples, len(samples))
59+
magnitude = normalized_rms(samples)
60+
print(((magnitude),)) # formatting is for the Mu plotter.
61+
62+
if magnitude < 1000: # it's quiet, do nothing.
63+
pass
64+
else:
65+
print("LOUD")
66+
head_servo.angle = 60
67+
time.sleep(.05)
68+
head_servo.angle = 120
69+
time.sleep(.05)
70+
head_servo.angle = 90
71+
time.sleep(.02)
72+
play_file("scream_low.wav")
73+
head_servo.angle = 90
74+
time.sleep(2)

0 commit comments

Comments
 (0)