class VOL(KeyObject): try: consumer_control = ConsumerControl(usb_hid.devices) except OSError: consumer_control = None def __init__(self, code): self.code = code def press(self, kbd, t): if not self.consumer_control: self.consumer_control = ConsumerControl(usb_hid.devices) self.consumer_control.send(self.code) self.last_exec = t self.repeated = False def release(self, kbd, time): pass def tick(self, kbd, time): threshold = 0.1 if self.repeated else 0.5 if time - self.last_exec > threshold: self.consumer_control.send(self.code) self.repeated = True self.last_exec = time
def __init__(self,display): self._display=display #read json button defs f=open("/buttons.json") # load buttons pages self.buttonPages=json.load(f) f.close() for buttonPage in self.buttonPages["buttons"]: print("Button Page : %s"%(buttonPage["name"])) parseButtons(buttonPage) self.currButtonPageIndex=0 #setup keyboard device self.keyboard=Keyboard(usb_hid.devices) self.cc=ConsumerControl(usb_hid.devices) #init button ui self.ui=ButtonPageUI() #init list ui self.uilist=ButtonListUI(self.buttonPages["buttons"]) self.listVisible=False #Initialize first button page self.LoadButtonPage(0) self._display.show(self.ui.group)
def setup_hid_devices(self): self.kbd = [ Keyboard(usb_hid.devices), Keyboard(usb_hid.devices), Keyboard(usb_hid.devices), Keyboard(usb_hid.devices), Keyboard(usb_hid.devices), Keyboard(usb_hid.devices) ] self.cc = ConsumerControl(usb_hid.devices)
class ButtonModel: def __init__(self): #read json button defs f = open("/buttons.json") # load buttons pages self.buttonPages = json.load(f) f.close() for buttonPage in self.buttonPages["buttons"]: print("Button Page : %s" % (buttonPage["name"])) parseButtons(buttonPage) self.LoadButtonPage(0) self.currButtonPageIndex = 0 #setup keyboard device self.keyboard = Keyboard(usb_hid.devices) self.cc = ConsumerControl(usb_hid.devices) # Loads the button page specified by the index def LoadButtonPage(self, newButtonPageIndex): self.currButtonDef = self.buttonPages["buttons"][newButtonPageIndex] #print("Changeing BGImg To " + buttonDef['img'] ) #imgbg=Image.open(buttonDef['img']) print("Loaded Button Page - %s" % (self.currButtonDef["name"])) #Flip the button page index def FlipButtonPage(self, changeIndex): self.currButtonPageIndex += changeIndex if self.currButtonPageIndex < 0: self.currButtonPageIndex = len(self.buttonPages['buttons']) - 1 elif self.currButtonPageIndex >= len(self.buttonPages['buttons']): self.currButtonPageIndex = 0 self.LoadButtonPage(self.currButtonPageIndex) # Button presed on current page def ButtonPressed(self, keyIndex): button = self.currButtonDef.get(keyIndex, None) if button != None and button['keycodes'] != None: print(keyIndex + "pressed") if (button["isCC"]) == False: self.keyboard.send(*button['keycodes']) time.sleep(150 / 1000) else: self.cc.send(button["keycodes"][0]) #Current Page Dictionary @property def CurrentButtons(self): return self.currButtonDef
def __init__(self, filename="shortcuts.txt"): self.display = LCD(I2CPCF8574Interface(0x27)) self.display.clear() self.keyboard = Keyboard() self.mouse = Mouse() self.consumer_control = ConsumerControl() self.display.print( "Ready! Choose a\nshortcut and press\nthe do-it switch.") self.switch_ins = tuple( digitalio.DigitalInOut(pin) for pin in SWITCH_PINS) for switch_in in self.switch_ins: switch_in.switch_to_input(pull=digitalio.Pull.UP) try: # Shortcuts is a dict mapping a switch number to a list of Shortcuts. self.shortcuts = Shortcut.read_shortcuts(filename) except BadShortcut as ex: self.fatal_error(*ex.args) if not self.shortcuts: self.fatal_error("No shortcuts defined!") self.current_switch = None # Keep track of the current shortcut for each switch. Start at the zero-th ones. # Skip any switches with no shortcuts. self.current_shortcut_index = {} for switch in self.shortcuts: self.current_shortcut_index[switch] = 0
def __init__(self): #read json button defs f = open("/buttons.json") # load buttons pages self.buttonPages = json.load(f) f.close() for buttonPage in self.buttonPages["buttons"]: print("Button Page : %s" % (buttonPage["name"])) parseButtons(buttonPage) self.LoadButtonPage(0) self.currButtonPageIndex = 0 #setup keyboard device self.keyboard = Keyboard(usb_hid.devices) self.cc = ConsumerControl(usb_hid.devices)
import board from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode from digitalio import DigitalInOut, Direction, Pull import time import adafruit_dotstar as dotstar from encoder import Encoder dot = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.1) dot[0] = (30, 0, 255) kbd = Keyboard() cc = ConsumerControl() prevTime = time.monotonic() def shortDelay(delayTime=0.1): global prevTime now = time.monotonic() diff = now - prevTime prevTime = now if diff < delayTime: return True return False # Encoder callbacks
import time import board import digitalio import adafruit_matrixkeypad import usb_hid from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode time.sleep(1) # Sleep for a bit to avoid a race condition on some systems control_key = Keycode.SHIFT cc = ConsumerControl(usb_hid.devices) # Uncomment the following code for 6 Key (V2.5) # cols = [digitalio.DigitalInOut(x) for x in (board.D11, board.D12, board.D13)] # rows = [digitalio.DigitalInOut(x) for x in (board.D9, board.D10)] # keys = ( # (0,1,2), # (3,4,5), # ) # Uncomment the following code for 9 Key (V2.6) # cols = [digitalio.DigitalInOut(x) for x in (board.D11, board.D12, board.D13)] # rows = [digitalio.DigitalInOut(x) for x in (board.D7, board.D9, board.D10)] # keys = ( # (6,7,8), # (3,4,5), # (0,1,2), # )
"""programme 6-8-2 : Commande de volume""" # importation des modules natifs utiles from time import * from board import * from digitalio import * from rotaryio import * # importation de modules supplémentaires import usb_hid from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode # Instanciation de la commande multimédia volume = ConsumerControl(usb_hid.devices) # Instanciation de l'encodeur en quadrature encodeur = IncrementalEncoder(D10, D9) derniere_position = encodeur.position # --------------------------------------- # ------- BOUCLE PRINCIPALE ----------- # --------------------------------------- while True: # Récupération de la position de l'encodeur position_actuelle = encodeur.position # Contrôle si la position a changé depuis la dernière itération changement_position = position_actuelle - derniere_position # S'il y a eu une augmentation de x incréments if changement_position > 0: # On envoie la commande d'augmentation du volume x fois for x in range(changement_position):
def __init__(self, keyboard, keyboardLayout, setKeyColour): self.setKeyColour = setKeyColour self.keyboard = keyboard self.keyboardLayout = keyboardLayout self.cc = ConsumerControl(usb_hid.devices)
elif (rising_edge == B_POSITION) and (falling_edge == A_POSITION): encoder_counter += 1 encoder_direction = 1 print("%d inc" % encoder_counter) else: # (shrug) something didn't work out, oh well! encoder_direction = 0 # reset our edge tracking rising_edge = falling_edge = UNKNOWN_POSITION rotary_prev_state = rotary_curr_state # Check if rotary encoder went up if encoder_direction == 1: ConsumerControl().send( ConsumerControlCode.VOLUME_DECREMENT) #Turn Down Volume # kbd.press(Keycode.LEFT_ARROW) # kbd.release_all() # Check if rotary encoder went down if encoder_direction == -1: ConsumerControl().send( ConsumerControlCode.VOLUME_INCREMENT) #Turn Up Volume # kbd.press(Keycode.RIGHT_ARROW) # kbd.release_all() # Button was 'just pressed' if (not button.value) and last_button: print("Button pressed!") kbd.press(Keycode.SPACE) #Keycode for spacebar kbd.release_all() ring[dot_location] = PRESSED_DOT_COLOR # show it was pressed on ring timestamp = time.monotonic() # something happened!
from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode # Set up Keybow i2c = board.I2C() keybow = Keybow2040(i2c) keys = keybow.keys # Set up the keyboard and layout keyboard = Keyboard(usb_hid.devices) layout = KeyboardLayoutUS(keyboard) # Set up consumer control (used to send media key presses) consumer_control = ConsumerControl(usb_hid.devices) # Our layers. The key of item in the layer dictionary is the key number on # Keybow to map to, and the value is the key press to send. # Note that key 0 is reserved as the modifier # purple - numeric keypad layer_1 = {4: Keycode.ZERO, 5: Keycode.ONE, 6: Keycode.FOUR, 7: Keycode.SEVEN, 8: Keycode.DELETE, 9: Keycode.TWO, 10: Keycode.FIVE, 11: Keycode.EIGHT,
import time import board import digitalio import adafruit_matrixkeypad import usb_hid import adafruit_dotstar from adafruit_hid.keyboard import Keyboard from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode time.sleep(1) control_key = Keycode.SHIFT cc = ConsumerControl(usb_hid.devices) kbd = Keyboard(usb_hid.devices) dot = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.5) time.sleep(1) # Uncomment the following code for 6 Key (V2.5) # cols = [digitalio.DigitalInOut(x) for x in (board.D11, board.D12, board.D13)] # rows = [digitalio.DigitalInOut(x) for x in (board.D9, board.D10)] # keys = ( # (0,1,2), # (3,4,5), # )
COOLDOWN_TIME = 0.25 LAST_PRESS_TIME = -1 current_layer = 0 # use built in display (PyPortal, PyGamer, PyBadge, CLUE, etc.) # see guide for up external displays (TFT / OLED breakouts, RGB matrices, etc.) # https://learn.adafruit.com/circuitpython-display-support-using-displayio/display-and-display-bus display = board.DISPLAY # Make the display context main_group = displayio.Group(max_size=10) display.show(main_group) kbd = Keyboard(usb_hid.devices) cc = ConsumerControl(usb_hid.devices) ts = adafruit_touchscreen.Touchscreen( board.TOUCH_XL, board.TOUCH_XR, board.TOUCH_YD, board.TOUCH_YU, calibration=((5200, 59000), (5800, 57000)), size=(display.width, display.height), ) layout = GridLayout( x=0, y=20, width=300, height=210,
class M2PicoMacro: sysKeyActions={ 'key1':'showlist', #shows the list page 'key2':'flipback', #Cycle to previous page 'key3':'showlist', 'key4':'flip' #Cycle to next page } listKeyActions={ 'key1':'up', 'key2':'down', 'key3':'select', 'key4':'select' } # ui = ButtonPageUI object def __init__(self,display): self._display=display #read json button defs f=open("/buttons.json") # load buttons pages self.buttonPages=json.load(f) f.close() for buttonPage in self.buttonPages["buttons"]: print("Button Page : %s"%(buttonPage["name"])) parseButtons(buttonPage) self.currButtonPageIndex=0 #setup keyboard device self.keyboard=Keyboard(usb_hid.devices) self.cc=ConsumerControl(usb_hid.devices) #init button ui self.ui=ButtonPageUI() #init list ui self.uilist=ButtonListUI(self.buttonPages["buttons"]) self.listVisible=False #Initialize first button page self.LoadButtonPage(0) self._display.show(self.ui.group) # Loads the button page specified by the index def LoadButtonPage(self,newButtonPageIndex): self.currButtonDef=self.buttonPages["buttons"][newButtonPageIndex] self.ui.LoadButtonPage(self.CurrentButtons) #print("Loaded Button Page - %s"%(self.currButtonDef["name"])) #Flip the button page index def FlipButtonPage(self,changeIndex,changePage=True): self.currButtonPageIndex+=changeIndex if self.currButtonPageIndex < 0: self.currButtonPageIndex=len(self.buttonPages['buttons'])-1 elif self.currButtonPageIndex>=len(self.buttonPages['buttons']): self.currButtonPageIndex=0 if changePage==True: self.LoadButtonPage(self.currButtonPageIndex) #Button pressed down def ButtonDown(self,keyIndex): self.ui.SetButtonState(keyIndex,True) pass #Button released def ButtonUp(self,keyIndex): self.ui.SetButtonState(keyIndex,False) pass # Button presed on current page def ButtonPressed(self,keyIndex): if self.listVisible==True: self.ListButtonPressed(keyIndex) else: button = self.currButtonDef.get(keyIndex,None) if button != None and button['keycodes'] != None: print(keyIndex + "pressed") if(button["isCC"])==False: self.keyboard.send(*button['keycodes']) time.sleep(150/1000) else: self.cc.send(button["keycodes"][0]) # Button pressed in list mode def ListButtonPressed(self,keyIndex): listAction=self.listKeyActions[keyIndex] self._display.auto_refresh=False if listAction=='up': self.FlipButtonPage(-1,False) self.uilist.setActiveItem(self.currButtonPageIndex) elif listAction=='down': self.FlipButtonPage(1,False) self.uilist.setActiveItem(self.currButtonPageIndex) elif listAction=="select": self.LoadButtonPage(self.currButtonPageIndex) self._display.show(self.ui.group) self.listVisible=False self._display.auto_refresh=True time.sleep(50/1000) #Long press of a button def ButtonLongPressed(self,keyIndex): sysaction=self.sysKeyActions[keyIndex] print("Sys Key action :" + sysaction) self._display.auto_refresh=False if sysaction=='flip': self.FlipButtonPage(1) elif sysaction=='flipback': self.FlipButtonPage(-1) elif sysaction=="showlist": #show page list self.uilist.setActiveItem(self.currButtonPageIndex) self._display.show(self.uilist.group) self.listVisible=True self._display.auto_refresh=True time.sleep(150/1000) #Current Page Dictionary @property def CurrentButtons(self): return self.currButtonDef
from digitalio import * from board import * from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode # Encoder button is a digital input with pullup on D2 button = DigitalInOut(D0) button.direction = Direction.INPUT button.pull = Pull.UP last_button = button.value cc = ConsumerControl() while True: # Button was 'just pressed' if (not button.value) and last_button: print("Button pressed!") cc.send(ConsumerControlCode.VOLUME_INCREMENT) elif button.value and (not last_button): print("Button Released!") last_button = button.value
STAY_EVEN_CHANGE_THRESHOLD = 60 # if encoder value increases at least this much # then brightness goes up INCREASE_CHANGE_THRESHOLD = 95 # timestamp of last time an action occurred LAST_ACTION_TIME = 0 # encoder value variable CUR_VALUE = 0 # pause state PAUSED = False cc = ConsumerControl(usb_hid.devices) encoder = rotaryio.IncrementalEncoder(board.ROTA, board.ROTB) switch = digitalio.DigitalInOut(board.SWITCH) switch.switch_to_input(pull=digitalio.Pull.DOWN) switch_state = None # previous encoder position variable last_position = encoder.position # previous switch variable prev_switch_value = False while True: now = time.monotonic()
def press(self, kbd, t): if not self.consumer_control: self.consumer_control = ConsumerControl(usb_hid.devices) self.consumer_control.send(self.code) self.last_exec = t self.repeated = False
from adafruit_hid.consumer_control import ConsumerControl from adafruit_displayio_layout.widgets.icon_widget import IconWidget from adafruit_featherwing import tft_featherwing_35 # seems to help the touchscreen not get stuck with chip not found time.sleep(3) # display and touchscreen initialization displayio.release_displays() tft_featherwing = tft_featherwing_35.TFTFeatherWing35() display = tft_featherwing.display touchscreen = tft_featherwing.touchscreen # HID setup kbd = Keyboard(usb_hid.devices) cc = ConsumerControl(usb_hid.devices) kbd_layout = KeyboardLayoutUS(kbd) # variables to envorce timout between icon presses COOLDOWN_TIME = 0.5 LAST_PRESS_TIME = -1 # 'mock' icon indexes for the layer buttons # used for debouncing PREV_LAYER_INDEX = -1 NEXT_LAYER_INDEX = -2 HOME_LAYER_INDEX = -3 # start on first layer current_layer = 0
import rotaryio import board import digitalio import usb_hid from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode # Update to match GP where "SW" from encoder is connected button = digitalio.DigitalInOut(board.GP6) button.direction = digitalio.Direction.INPUT button.pull = digitalio.Pull.UP # Update to match GP where "DT" is fisrt and "CLK" is second encoder = rotaryio.IncrementalEncoder(board.GP0, board.GP1) cc = ConsumerControl(usb_hid.devices) button_state = None last_position = encoder.position while True: current_position = encoder.position position_change = current_position - last_position if position_change > 0: for _ in range(position_change): cc.send(ConsumerControlCode.VOLUME_INCREMENT) print(current_position) elif position_change < 0: for _ in range(-position_change): cc.send(ConsumerControlCode.VOLUME_DECREMENT) print(current_position)
import usb_hid from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode # The button pins we'll use, each will have an internal pullup buttonpins = [board.A1, board.A2, board.A3] # The keycode sent for each button, will be paired with a control key buttonkeys = [ ConsumerControlCode.PLAY_PAUSE, # Center Foot Pad ConsumerControlCode.VOLUME_DECREMENT, #Left Foot Pad ConsumerControlCode.VOLUME_INCREMENT, # Right Foot Pad ] # the keyboard object! cc = ConsumerControl(usb_hid.devices) # our array of button objects buttons = [] # make all pin objects, make them inputs w/pullups for pin in buttonpins: button = digitalio.DigitalInOut(pin) button.direction = digitalio.Direction.INPUT button.pull = digitalio.Pull.UP buttons.append(button) print("Waiting for button presses") while True: # check each button for button in buttons:
from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode import adafruit_dotstar as dotstar dots = dotstar.DotStar(board.SCK, board.MOSI, 12, brightness=0.4) RED = 0xFF0000 AMBER = 0xAA9900 BLUE = 0x0066FF MAGENTA = 0xFF00FF PURPLE = 0x3B0F85 BLACK = 0x000000 kbd = Keyboard(usb_hid.devices) cc = ConsumerControl(usb_hid.devices) orientation = 1 # 0 = portrait/vertical, 1 = landscape/horizontal if orientation == 0: key_dots = [0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11] # 0 #4 #8 # 1 #5 #9 # 2 #6 #10 # 3 #7 #11 if orientation == 1: key_dots = [3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8] # 3 #2 #1 #0 # 7 #6 #5 #4 # 11 #10 #9 #8
consumer_control.send(ConsumerControlCode.VOLUME_INCREMENT) current_volume += 2 print(pot_val) elif current_volume > position: while current_volume > position: # Lower volume. print("Volume Down!") consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT) current_volume -= 2 print(pot_val) return last_position, current_volume # initialize hid device as consumer control consumer_control = ConsumerControl(usb_hid.devices) # initialize potentiometer (pot) wiper connected to GP26_A0 potentiometer = AnalogIn(board.GP26) # intialize the read time last_read = time.monotonic() # decrease volume all the way down # this allows the volume to be set by the current value of the pot for i in range(32): consumer_control.send(ConsumerControlCode.VOLUME_DECREMENT) # initalize volume and last position current_volume = 0
import time import usb_hid from digitalio import DigitalInOut, Direction, Pull import board from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode btn = DigitalInOut(board.GP28) btn.direction = Direction.INPUT btn.pull = Pull.DOWN kbd = Keyboard(usb_hid.devices) ctl = ConsumerControl(usb_hid.devices) prev = False while True: if prev == False and btn.value == True: time.sleep(0.02) if btn.value == True: print("pressed") # 我的截圖軟體設定快捷鍵是 CTRL+SHIFT+A kbd.send(Keycode.PRINT_SCREEN) ctl.send(ConsumerControlCode.VOLUME_INCREMENT) prev = btn.value
from adafruit_hid.consumer_control_code import ConsumerControlCode import adafruit_ble from adafruit_ble.advertising.standard import ProvideServicesAdvertisement from adafruit_ble.services.standard.hid import HIDService from adafruit_ble.services.standard.device_info import DeviceInfoService ble = adafruit_ble.BLERadio() ble.name = "Bluefruit-Volume-Control" # Using default HID Descriptor. hid = HIDService() device_info = DeviceInfoService(software_revision=adafruit_ble.__version__, manufacturer="Adafruit Industries") advertisement = ProvideServicesAdvertisement(hid) cc = ConsumerControl(hid.devices) FILL_COLOR = (0, 32, 32) UNMUTED_COLOR = (0, 128, 128) MUTED_COLOR = (128, 0, 0) DISCONNECTED_COLOR = (40, 40, 0) # NeoPixel LED ring # Ring code will auto-adjust if not 16 so change to any value! ring = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.05, auto_write = False) ring.fill(DISCONNECTED_COLOR) ring.show() dot_location = 0 # what dot is currently lit # CPB button for Play/Pause button_A = digitalio.DigitalInOut(board.BUTTON_A)
advertisement.appearance = 961 scan_response = Advertisement() ble = adafruit_ble.BLERadio() ble.name = "Zwiftendo" # Teardown any other BLE connections if ble.connected: for c in ble.connections: c.disconnect() # Start advertising on BLE print("Advertising...") ble.start_advertising(advertisement, scan_response) # Setup bluetooth HID resources consumer_control = ConsumerControl(hid.devices) k = Keyboard(hid.devices) kl = KeyboardLayoutUS(k) def make_pin_reader(pin): """ Creates a pin reader to feed to Debouncer """ ss.pin_mode(pin, ss.INPUT_PULLUP) return lambda: ss.digital_read(pin) def get_bat_percent(pin): # percentage relative to 4.2V max return (((pin.value * 3.3) / 65536 * 2) / 4.2) * 100
# 16 position neopixel ring ring = neopixel.NeoPixel(board.MISO, 16, brightness=0.2, auto_write=False) # 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) cc = ConsumerControl(usb_hid.devices) print("hello from qtpy-knob!") # standard colorwheel def colorwheel(pos): if pos < 0 or pos > 255: (r, g, b) = (0, 0, 0) elif pos < 85: (r, g, b) = (int(pos * 3), int(255 - pos * 3), 0) elif pos < 170: pos -= 85 (r, g, b) = (int(255 - pos * 3), 0, int(pos * 3)) else: pos -= 170
# Time to take fading out all of the keys. FADE_TIME = 1 # Once asleep, how much time to wait between "snores" which fade up and down one button. SNORE_PAUSE = 0.5 # Time in seconds to take fading up the snoring LED. SNORE_UP = 2 # Time in seconds to take fading down the snoring LED. SNORE_DOWN = 1 TOTAL_SNORE = SNORE_PAUSE + SNORE_UP + SNORE_DOWN kbd = Keyboard() cc = ConsumerControl() trellis = adafruit_trellism4.TrellisM4Express(rotation=ROTATION) for button in keymap: trellis.pixels[button] = keymap[button][0] current_press = set() last_press = time.monotonic() snore_count = -1 while True: pressed = set(trellis.pressed_keys) now = time.monotonic() sleep_time = now - last_press sleeping = sleep_time > TIMEOUT for down in pressed - current_press: if down in keymap and not sleeping:
# Encoder button is a digital input with pullup on D9 button = DigitalInOut(board.D9) button.direction = Direction.INPUT button.pull = Pull.UP # Rotary encoder inputs with pullup on D10 & D11 rot_a = DigitalInOut(board.D10) rot_a.direction = Direction.INPUT rot_a.pull = Pull.UP rot_b = DigitalInOut(board.D11) rot_b.direction = Direction.INPUT rot_b.pull = Pull.UP # Used to do HID output, see below kbd = Keyboard(usb_hid.devices) consumer_control = ConsumerControl(usb_hid.devices) # time keeper, so we know when to turn off the LED timestamp = time.monotonic() ######################### MAIN LOOP ############################## # the counter counts up and down, it can roll over! 16-bit value encoder_counter = 0 # direction tells you the last tick which way it went encoder_direction = 0 # constants to help us track what edge is what A_POSITION = 0 B_POSITION = 1 UNKNOWN_POSITION = -1 # initial state so we know if something went wrong
from adafruit_hid.consumer_control import ConsumerControl from adafruit_hid.consumer_control_code import ConsumerControlCode from adafruit_hid.keycode import Keycode import usb_hid cc = ConsumerControl(usb_hid.devices) def volume_up(steps=1): for i in range(0, steps): cc.send(ConsumerControlCode.VOLUME_INCREMENT) return def volume_down(steps=1): for i in range(0, steps): cc.send(ConsumerControlCode.VOLUME_DECREMENT) return def next_track(): cc.send(ConsumerControlCode.SCAN_NEXT_TRACK) return def prev_track(): cc.send(ConsumerControlCode.SCAN_PREVIOUS_TRACK) return def play_pause():