Skip to content

Instantly share code, notes, and snippets.

@benevpi
Created July 23, 2021 14:54
Show Gist options
  • Save benevpi/f5f83fffe0d1f3d6f956b5d303b70e9b to your computer and use it in GitHub Desktop.
Save benevpi/f5f83fffe0d1f3d6f956b5d303b70e9b to your computer and use it in GitHub Desktop.
modwheel.py
import time
import board
import busio
from simpleio import map_range
from analogio import AnalogIn
from digitalio import DigitalInOut, Direction
import usb_midi
import adafruit_midi # MIDI protocol encoder/decoder library
from adafruit_midi.control_change import ControlChange
from adafruit_midi.note_on import NoteOn
USB_MIDI_channel = 1
usb_midi = adafruit_midi.MIDI(
midi_out=usb_midi.ports[1], out_channel=USB_MIDI_channel - 1
)
knob = AnalogIn(board.A2)
cc_number = 1
cc_range = (0, 127)
cc_value = (0,0)
last_cc_value = (0,0)
def range_index(ctl, ctrl_max, old_idx, offset):
if (ctl + offset > 65535) or (ctl + offset < 0):
offset = 0
idx = int(map_range((ctl + offset) & 0xFF00, 1200, 65500, 0, ctrl_max))
if idx != old_idx: # if index changed, adjust hysteresis offset
# offset is 25% of the control slice (65536/ctrl_max)
offset = int(
0.25 * sign(idx - old_idx) * (65535 / ctrl_max)
) # edit 0.25 to adjust slices
return idx, offset
def sign(x): # determine the sign of x
if x >= 0:
return 1
else:
return -1
counter = 0
while True:
cc_value = range_index(
knob.value,
(cc_range[1] - cc_range[0] + 1),
cc_value[0],
cc_value[1],
)
if cc_value != last_cc_value: # only send if it changed
# Form a MIDI CC message and send it:
usb_midi.send(ControlChange(cc_number, cc_value[0] + cc_range[0]))
print("sending change")
print(cc_value)
print(last_cc_value)
print(knob.value)
last_cc_value = cc_value
time.sleep(0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment