Skip to content

Instantly share code, notes, and snippets.

@jshiell
Last active January 8, 2020 19:10
Show Gist options
  • Save jshiell/416050eafe6429e0d93607e74d36b118 to your computer and use it in GitHub Desktop.
Save jshiell/416050eafe6429e0d93607e74d36b118 to your computer and use it in GitHub Desktop.
USB keypress code for AdaFruit Trinket M0 with CircuitPython 4
import digitalio
from board import *
import time
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
import adafruit_dotstar
# The keycode sent for each button, optionally can be paired with a modifier key
# https://circuitpython.readthedocs.io/projects/hid/en/latest/api.html#adafruit-hid-keycode-keycode
button_keycode = 83
modifier_keycode = None # e.g. Keycode.RIGHT_ALT
led = adafruit_dotstar.DotStar(APA102_SCK, APA102_MOSI, 1)
led[0] = (0, 255, 0)
led.brightness = 0.0
kbd = Keyboard(usb_hid.devices)
button = digitalio.DigitalInOut(D0)
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
print("Waiting for button press: keycode %s with modifiers %s" % (button_keycode, modifier_keycode))
while True:
if (not button.value): # pressed?
print("Button pressed")
if modifier_keycode is not None:
kbd.press(button_keycode, modifier_keycode)
else:
kbd.press(button_keycode)
led.brightness = 1.0
while (not button.value):
pass
print("Button released")
kbd.release_all()
led.brightness = 0.0
time.sleep(0.01)
@jshiell
Copy link
Author

jshiell commented Jan 8, 2020

Simplified code for USB footpedal or similar. Also ensures LED is only active when pressed.

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