|
| 1 | +# SPDX-FileCopyrightText: 2017 Limor Fried for Adafruit Industries |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +# CircuitPlayground demo - Keyboard emu |
| 6 | + |
| 7 | +import time |
| 8 | + |
| 9 | +import board |
| 10 | +import usb_hid |
| 11 | +from adafruit_hid.keyboard import Keyboard |
| 12 | +from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS |
| 13 | +from adafruit_hid.keycode import Keycode |
| 14 | +from digitalio import DigitalInOut, Direction, Pull |
| 15 | + |
| 16 | +# A simple neat keyboard demo in circuitpython |
| 17 | + |
| 18 | +# The button pins we'll use, each will have an internal pullup |
| 19 | +buttonpins = [board.D2, board.D1, board.D0] |
| 20 | +# our array of button objects |
| 21 | +buttons = [] |
| 22 | +# The keycode sent for each button, will be paired with a control key |
| 23 | +buttonkeys = [Keycode.A, Keycode.B, "Hello World!\n"] |
| 24 | +controlkey = Keycode.SHIFT |
| 25 | + |
| 26 | +# the keyboard object! |
| 27 | +# sleep for a bit to avoid a race condition on some systems |
| 28 | +time.sleep(1) |
| 29 | +kbd = Keyboard(usb_hid.devices) |
| 30 | +# we're americans :) |
| 31 | +layout = KeyboardLayoutUS(kbd) |
| 32 | + |
| 33 | +# make all pin objects, make them inputs w/pullups |
| 34 | +for pin in buttonpins: |
| 35 | + button = DigitalInOut(pin) |
| 36 | + button.direction = Direction.INPUT |
| 37 | + button.pull = Pull.UP |
| 38 | + buttons.append(button) |
| 39 | + |
| 40 | +led = DigitalInOut(board.D13) |
| 41 | +led.direction = Direction.OUTPUT |
| 42 | + |
| 43 | +print("Waiting for button presses") |
| 44 | + |
| 45 | +while True: |
| 46 | + # check each button |
| 47 | + for button in buttons: |
| 48 | + if not button.value: # pressed? |
| 49 | + i = buttons.index(button) |
| 50 | + print("Button #%d Pressed" % i) |
| 51 | + |
| 52 | + # turn on the LED |
| 53 | + led.value = True |
| 54 | + |
| 55 | + while not button.value: |
| 56 | + pass # wait for it to be released! |
| 57 | + # type the keycode or string |
| 58 | + k = buttonkeys[i] # get the corresp. keycode/str |
| 59 | + if isinstance(k, str): |
| 60 | + layout.write(k) |
| 61 | + else: |
| 62 | + kbd.press(controlkey, k) # press... |
| 63 | + kbd.release_all() # release! |
| 64 | + |
| 65 | + # turn off the LED |
| 66 | + led.value = False |
| 67 | + |
| 68 | + time.sleep(0.01) |
0 commit comments