Skip to content

Instantly share code, notes, and snippets.

@abachman
Created November 7, 2018 02:08
Show Gist options
  • Save abachman/25b4e4b25c6d66396ab8f97a58a93a7a to your computer and use it in GitHub Desktop.
Save abachman/25b4e4b25c6d66396ab8f97a58a93a7a to your computer and use it in GitHub Desktop.
CircuitPython Trellis M4 Keyboard Demo
# CircuitPython + Trellis M4 Keyboard emulator. Fits in your pocket!
# using https://www.adafruit.com/product/4020
#
# Should work on any PC
import time
import board
import digitalio
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode
# CircuitPython demo - Keypad
from digitalio import DigitalInOut
import board
import adafruit_matrixkeypad
# lights
cols = []
for x in range(8):
cols.append(DigitalInOut(getattr(board, "COL{}".format(x))))
rows = []
for y in range(4):
rows.append(DigitalInOut(getattr(board, "ROW{}".format(y))))
key_names = []
for y in range(8):
row = []
for x in range(4):
coord = (x, y)
row.append(coord)
key_names.append(row)
keypad = adafruit_matrixkeypad.Matrix_Keypad(cols, rows, key_names)
key_names = {
(0, 0): 'a',
(0, 1): 'b',
(0, 2): 'c',
(0, 3): 'd',
(0, 4): 'e',
(0, 5): 'f',
(0, 6): 'g',
(0, 7): 'h',
(1, 0): 'i',
(1, 1): 'j',
(1, 2): 'k',
(1, 3): 'l',
(1, 4): 'm',
(1, 5): 'n',
(1, 6): 'o',
(1, 7): 'p',
(2, 0): 'q',
(2, 1): 'r',
(2, 2): 's',
(2, 3): 't',
(2, 4): 'u',
(2, 5): 'v',
(2, 6): 'w',
(2, 7): 'x',
(3, 0): 'y',
(3, 1): 'z',
(3, 2): '.',
(3, 3): '!',
(3, 4): '?',
(3, 5): ' ',
(3, 6): ' ',
(3, 7): Keycode.BACKSPACE,
}
import neopixel
pixels = neopixel.NeoPixel(board.NEOPIXEL, 32, brightness=0.3, auto_write=False)
pixels.fill(0)
pixels.show()
# The keyboard object!
time.sleep(1) # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard()
keyboard_layout = KeyboardLayoutUS(keyboard) # We're in the US :)
pressed = {}
while True:
keys = keypad.pressed_keys
if keys:
print("Pressed: ", keys)
for k in keys:
is_pressed = pressed.get(k, False)
if not is_pressed:
key = key_names.get(k, None)
if isinstance(key, str): # If it's a string...
keyboard_layout.write(key) # ...Print the string
else: # If it's not a string...
keyboard.press(key) # "Press"...
keyboard.release_all() # ..."Release"!
pixels[k[0] * 8 + k[1]] = (0, 0, 100)
pressed[k] = True
# unpress keys that aren't currently being held
for k, value in pressed.items():
print("was pressed: ", k)
if k in keys:
print(" ", k, " is pressed")
else:
print(" k ", k, " was released")
pixels[k[0] * 8 + k[1]] = (0, 0, 0)
pressed[k] = False
else:
for k, value in pressed.items():
pixels[k[0] * 8 + k[1]] = (0, 0, 0)
pressed[k] = False
pixels.show()
time.sleep(0.01)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment