code.py
 1  # SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """CircuitPython Essentials HID Keyboard example"""
 6  import time
 7  
 8  import board
 9  import digitalio
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  
15  # A simple neat keyboard demo in CircuitPython
16  
17  # The pins we'll use, each will have an internal pullup
18  keypress_pins = [board.A1, board.A2]
19  # Our array of key objects
20  key_pin_array = []
21  # The Keycode sent for each button, will be paired with a control key
22  keys_pressed = [Keycode.A, "Hello World!\n"]
23  control_key = Keycode.SHIFT
24  
25  # The keyboard object!
26  time.sleep(1)  # Sleep for a bit to avoid a race condition on some systems
27  keyboard = Keyboard(usb_hid.devices)
28  keyboard_layout = KeyboardLayoutUS(keyboard)  # We're in the US :)
29  
30  # Make all pin objects inputs with pullups
31  for pin in keypress_pins:
32      key_pin = digitalio.DigitalInOut(pin)
33      key_pin.direction = digitalio.Direction.INPUT
34      key_pin.pull = digitalio.Pull.UP
35      key_pin_array.append(key_pin)
36  
37  # For most CircuitPython boards:
38  led = digitalio.DigitalInOut(board.LED)
39  # For QT Py M0:
40  # led = digitalio.DigitalInOut(board.SCK)
41  led.direction = digitalio.Direction.OUTPUT
42  
43  print("Waiting for key pin...")
44  
45  while True:
46      # Check each pin
47      for key_pin in key_pin_array:
48          if not key_pin.value:  # Is it grounded?
49              i = key_pin_array.index(key_pin)
50              print("Pin #%d is grounded." % i)
51  
52              # Turn on the red LED
53              led.value = True
54  
55              while not key_pin.value:
56                  pass  # Wait for it to be ungrounded!
57              # "Type" the Keycode or string
58              key = keys_pressed[i]  # Get the corresponding Keycode or string
59              if isinstance(key, str):  # If it's a string...
60                  keyboard_layout.write(key)  # ...Print the string
61              else:  # If it's not a string...
62                  keyboard.press(control_key, key)  # "Press"...
63                  keyboard.release_all()  # ..."Release"!
64  
65              # Turn off the red LED
66              led.value = False
67  
68      time.sleep(0.01)