code.py
1 # SPDX-FileCopyrightText: 2018 Limor Fried for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 from digitalio import DigitalInOut, Direction, Pull 7 from adafruit_seesaw.seesaw import Seesaw 8 from adafruit_seesaw.analoginput import AnalogInput 9 from adafruit_seesaw.pwmout import PWMOut 10 from adafruit_motor import motor 11 from busio import I2C 12 import neopixel 13 import audioio 14 import audiocore 15 import board 16 17 # Create seesaw object 18 i2c = I2C(board.SCL, board.SDA) 19 seesaw = Seesaw(i2c) 20 21 # built in CPX button A 22 button = DigitalInOut(board.BUTTON_A) 23 button.direction = Direction.INPUT 24 button.pull = Pull.DOWN 25 26 # NeoPixels 27 pixels = neopixel.NeoPixel(board.A1, 10, brightness=0) 28 pixels.fill((0,0,250)) 29 30 # Analog reading from Signal #1 (ss. #2) 31 foot_pedal = AnalogInput(seesaw, 2) 32 33 # Create one motor on seesaw PWM pins 22 & 23 34 motor_a = motor.DCMotor(PWMOut(seesaw, 22), PWMOut(seesaw, 23)) 35 motor_a.throttle = 0 36 37 def map_range(x, in_min, in_max, out_min, out_max): 38 # Maps a number from one range to another. 39 mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min 40 if out_min <= out_max: 41 return max(min(mapped, out_max), out_min) 42 return min(max(mapped, out_max), out_min) 43 44 # Get the audio file ready 45 wavfile = "unchained.wav" 46 f = open(wavfile, "rb") 47 wav = audiocore.WaveFile(f) 48 a = audioio.AudioOut(board.A0) 49 50 time_to_play = 0 # when to start playing 51 played = False # have we played audio already? only play once! 52 while True: 53 # Foot pedal ranges from about 700 (unpressed) to 50 (pressed) 54 # make that change the speed of the motor from 0 (stopped) to 0.5 (half) 55 press = foot_pedal.value 56 speed = map_range(press, 700, 50, 0, 0.5) 57 print("%d -> %0.3f" % (press, speed)) 58 motor_a.throttle = speed 59 60 if not time_to_play and speed > 0.1: 61 print("Start audio in 3 seconds") 62 time_to_play = time.monotonic() + 3 63 elif time_to_play and time.monotonic() > time_to_play and not played: 64 print("Playing audio") 65 a.play(wav) 66 played = True 67 68 # turn on/off blue LEDs 69 if button.value: 70 if pixels.brightness < 0.1: 71 pixels.brightness = 1 72 else: 73 pixels.brightness = 0 74 time.sleep(0.5) 75 76 # loop delay 77 time.sleep(0.1)