Skip to content

Instantly share code, notes, and snippets.

@dglaude
Created February 28, 2021 00:00
Show Gist options
  • Save dglaude/4c443bc324a972e8c88d673236e3197a to your computer and use it in GitHub Desktop.
Save dglaude/4c443bc324a972e8c88d673236e3197a to your computer and use it in GitHub Desktop.
Gt-Py Knob midi control
# qtpy-knob-midi.py -- Mount a rotary encoder directly to an Adafruit QT Py,
# use it for midi CC message
#
# 2020 @todbot / Tod Kurt
# 2021 @David.Glaude / David Glaude
import time
import board
from digitalio import DigitalInOut, Direction, Pull
import rotaryio
import usb_midi
import adafruit_midi
from adafruit_midi.control_change import ControlChange
midi = adafruit_midi.MIDI(midi_out=usb_midi.ports[1], out_channel=0)
# button of rotary encoder
button = DigitalInOut(board.MOSI)
button.pull = Pull.UP
# Use pin A2 as a fake ground for the rotary encoder
fakegnd = DigitalInOut(board.A2)
fakegnd.direction = Direction.OUTPUT
fakegnd.value = False
encoder = rotaryio.IncrementalEncoder(board.A3, board.A1)
last_encoder_val = encoder.position
oldval = 63
newval = oldval
oldbut = button.value
newbut = oldbut
while True:
diff = last_encoder_val - encoder.position # encoder clicks since last read
last_encoder_val = encoder.position
if diff != 0:
newval=oldval+diff
if newval > 127:
newval = 127
if newval < 0:
newval = 0
newbut = button.value
if oldbut != newbut: # button pressed
if newbut:
button_midi = ControlChange(2, 0)
else:
button_midi = ControlChange(2, 127)
midi.send(button_midi) # sending CC message
#### print("button:", newbut)
oldbut = newbut
else: # not pressed
if oldval != newval:
oldval = newval
modWheel = ControlChange(1, newval)
midi.send(modWheel) # sending CC message
#### print("new:", newval)
time.sleep(0.05)
@dglaude
Copy link
Author

dglaude commented Feb 28, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment