Last active
August 8, 2023 14:17
-
-
Save suzumura-ss/5f7140d3767d999719e51f2adc90ac0a to your computer and use it in GitHub Desktop.
adafruit macropad HID Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://learn.adafruit.com/adafruit-macropad-rp2040/macropad-basics | |
# https://docs.circuitpython.org/projects/macropad/en/latest/index.html | |
# https://docs.circuitpython.org/projects/hid/en/latest/api.html | |
import time | |
import usb_hid | |
from adafruit_macropad import MacroPad | |
from adafruit_hid.consumer_control import ConsumerControl | |
from adafruit_hid.consumer_control_code import ConsumerControlCode | |
from adafruit_hid.keyboard import Keyboard | |
from adafruit_hid.keycode import Keycode | |
kbd = Keyboard(usb_hid.devices) | |
consumer_control = ConsumerControl(usb_hid.devices) | |
macropad = MacroPad() | |
class Encoder: | |
def __init__(self): | |
self.lastValue = None | |
self.lastSwitch = None | |
def processEncoder(self): | |
value = macropad.encoder | |
if self.lastValue == value: | |
return | |
print("Encoder: {}\n\n".format(value)) | |
if self.lastValue != None: | |
if self.lastValue < value: | |
consumer_control.send(ConsumerControlCode.VOLUME_INCREMENT) | |
else: | |
consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT) | |
self.lastValue = value | |
def processSwitch(self): | |
switch = macropad.encoder_switch | |
if self.lastSwitch == switch: | |
return | |
if switch: | |
consumer_control.send(ConsumerControlCode.MUTE) | |
self.lastSwitch = switch | |
keymap = { | |
0: [ Keycode.A, Keycode.B ], | |
1: [ Keycode.C, Keycode.D ], | |
2: [ Keycode.E, Keycode.F ], | |
3: [ Keycode.G, Keycode.H ], | |
4: [ Keycode.I, Keycode.J ], | |
5: [ Keycode.K, Keycode.L ], | |
6: [ Keycode.M, Keycode.N ], | |
7: [ Keycode.O, Keycode.P ], | |
8: [ Keycode.Q, Keycode.R ], | |
9: [ Keycode.S, Keycode.T ], | |
10: [ Keycode.U, Keycode.V ], | |
11: [ Keycode.W, Keycode.X ], | |
} | |
class Keypad: | |
def process(self): | |
key_event = macropad.keys.events.get() | |
if not key_event: | |
return | |
if not key_event.pressed: | |
return | |
if key_event.key_number in keymap: | |
for key in keymap[key_event.key_number]: | |
kbd.press(key) | |
time.sleep(0.01) | |
kbd.release(key) | |
time.sleep(0.01) | |
theEncoder = Encoder() | |
theKeypad = Keypad() | |
while True: | |
theEncoder.processEncoder() | |
theEncoder.processSwitch() | |
theKeypad.process() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment