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