code.py
 1  # SPDX-FileCopyrightText: 2020 Liz Clark for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import time
 6  import board
 7  import digitalio
 8  import usb_midi
 9  import adafruit_midi
10  from adafruit_midi.note_on import NoteOn
11  
12  #  pins for the solenoid output signals
13  noid_pins = [board.D5, board.D6, board.D9, board.D10]
14  
15  #  array for the solenoids
16  noids = []
17  
18  #  setup for the solenoid pins to be outputs
19  for pin in noid_pins:
20      noid = digitalio.DigitalInOut(pin)
21      noid.direction = digitalio.Direction.OUTPUT
22      noids.append(noid)
23  
24  #  MIDI note array
25  notes = [60, 61, 62, 63]
26  
27  #  MIDI in setup
28  midi = adafruit_midi.MIDI(midi_in=usb_midi.ports[0], in_channel=0)
29  
30  #  delay for solenoids
31  speed = 0.03
32  retract = 0
33  
34  while True:
35  
36      #  msg holds MIDI messages
37      msg = midi.receive()
38  
39      for i in range(4):
40          #  states for solenoid on/off
41          noid_output = noids[i]
42  
43          #  states for MIDI note recieved
44          notes_played = notes[i]
45  
46          #  if NoteOn msg comes in and the MIDI note # matches with predefined notes:
47          if isinstance(msg, NoteOn) and msg.note is notes_played:
48              print(time.monotonic(), msg.note)
49  
50              #  solenoid is triggered
51              noid_output.value = True
52              #  quick delay
53              retract = time.monotonic()
54  
55          #  retracts solenoid using time.monotonic() to avoid delays between notes activating
56          if (retract + speed) < time.monotonic():
57              noid_output.value = False