import board import digitalio import time import usb_hid from adafruit_hid.keyboard import Keyboard from adafruit_hid.keycode import Keycode
# Pin definitions button_pin_w = digitalio.DigitalInOut(board.D5) # Key "w" assigned to pin D5 button_pin_w.direction = digitalio.Direction.INPUT # Pin set to "INPUT" meaning it will read the state of the buttons button_pin_w.pull = digitalio.Pull.UP # Pull-up resistor enabled, reads True when not pressed button_pin_s = digitalio.DigitalInOut(board.D9) # Repeat for each pin button_pin_s.direction = digitalio.Direction.INPUT button_pin_s.pull = digitalio.Pull.UP ...
# Create a Keyboard object kbd = Keyboard(usb_hid.devices)
# Function to send the key press def send_key(key): kbd.press(key) # Function to release the key def release_key(key): kbd.release(key)
# Main loop keys_pressed = set() # Track the currently pressed keys while True: # Check if the "W" button is pressed (the pin goes LOW when the button is pressed) if not button_pin_w.value: if Keycode.W not in keys_pressed: send_key(Keycode.W) keys_pressed.add(Keycode.W) else: if Keycode.W in keys_pressed: release_key(Keycode.W) keys_pressed.remove(Keycode.W) # Check if the "S" button is pressed (the pin goes LOW when the button is pressed) if not button_pin_s.value: if Keycode.S not in keys_pressed: send_key(Keycode.S) keys_pressed.add(Keycode.S) else: if Keycode.S in keys_pressed: release_key(Keycode.S) keys_pressed.remove(Keycode.S) # ... (similar code for other buttons)
# Add a small delay to avoid excessive key presses (adjust as needed) time.sleep(0.025)