code.py
1 # SPDX-FileCopyrightText: 2018 phillip torrone for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 import array 7 import math 8 from busio import I2C 9 from adafruit_seesaw.seesaw import Seesaw 10 from adafruit_seesaw.pwmout import PWMOut 11 from adafruit_motor import motor 12 import audiobusio 13 import board 14 15 print("Sound sensor motor!") 16 17 # Create seesaw object 18 i2c = I2C(board.SCL, board.SDA) 19 seesaw = Seesaw(i2c) 20 21 # Create one motor on seesaw PWM pins 22 & 23 22 motor_a = motor.DCMotor(PWMOut(seesaw, 22), PWMOut(seesaw, 23)) 23 motor_a.throttle = 0 # motor is stopped 24 25 26 ##################### helpers 27 28 # Maps a number from one range to another. 29 def map_range(x, in_min, in_max, out_min, out_max): 30 mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min 31 if out_min <= out_max: 32 return max(min(mapped, out_max), out_min) 33 return min(max(mapped, out_max), out_min) 34 35 # Returns the average 36 def mean(values): 37 return sum(values) / len(values) 38 39 # Audio root-mean-square 40 def normalized_rms(values): 41 minbuf = int(mean(values)) 42 return math.sqrt(sum(float(sample-minbuf)*(sample-minbuf) for sample in values) / len(values)) 43 44 45 # Our microphone 46 mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, 47 sample_rate=16000, bit_depth = 16) 48 samples = array.array('H', [0] * 200) 49 mic.record(samples, len(samples)) 50 51 while True: 52 mic.record(samples, len(samples)) 53 magnitude = normalized_rms(samples) 54 print(((magnitude),)) 55 motor_a.throttle = map_range(magnitude, 90, 200, 0, 1.0) 56 time.sleep(0.1)