Skip to content

Instantly share code, notes, and snippets.

@elementc
Created May 16, 2021 22:22
Show Gist options
  • Save elementc/f15fb43fe0bc19d17f2cc9cc86320de1 to your computer and use it in GitHub Desktop.
Save elementc/f15fb43fe0bc19d17f2cc9cc86320de1 to your computer and use it in GitHub Desktop.
serial byte read on keybow2040
import math
import board
from keybow2040 import Keybow2040, number_to_xy, hsv_to_rgb
import usb_cdc
# Some constants
FULLBRIGHT = 1
MINBRIGHT = 0.05
# Set up Keybow
i2c = board.I2C()
keybow = Keybow2040(i2c)
keys = keybow.keys
console = usb_cdc.serials[0]
# Dicts to stow statuses.
is_pressed = {}
hues = {}
# Per-key init
for key in keys:
# init to not-pressed
is_pressed[key.number] = False
# A pressed handler
@keybow.on_press(key)
def press_handler(key):
# note current pressed status
is_pressed[key.number] = True
if key.number in hues:
hue = hues[key.number]
# Get brightened value.
r, g, b = hsv_to_rgb(hue, 1, FULLBRIGHT)
# Display it on the key!
key.set_led(r, g, b)
# A release handler
@keybow.on_release(key)
def release_handler(key):
is_pressed[key.number] = False
if key.number in hues:
hue = hues[key.number]
# Get darkened value.
r, g, b = hsv_to_rgb(hue, 1, MINBRIGHT)
# Display it on the key!
key.set_led(r, g, b)
# Increment step to shift animation across keys.
step = 0
while True:
# Always remember to call keybow.update() on every iteration of your loop!
keybow.update()
step += 1
# all keys dim, unless we got some serial bytes this cycle
value = MINBRIGHT
if console.in_waiting > 0:
value=FULLBRIGHT
# throw away as many bytes as we have in the buffer
console.read(console.in_waiting)
for key in keys:
# Convert the key number to an x/y coordinate to calculate the hue
# in a matrix style-y.
x, y = number_to_xy(key.number)
# Calculate the hue.
hue = (x + y + (step / 20)) / 8
hue = hue - int(hue)
hue = hue - math.floor(hue)
# Stow it for event handlers
hues[key.number] = hue
# Pick a value (brightness)
net_value = value
if is_pressed[key.number]:
net_value = FULLBRIGHT
# Convert the hue and value to RGB values.
r, g, b = hsv_to_rgb(hue, 1, net_value)
# Display it on the key!
key.set_led(r, g, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment