Skip to content

Instantly share code, notes, and snippets.

@ladyada
Created April 12, 2022 01:54
Show Gist options
  • Save ladyada/f9f5ab3a4ee7a73337d251e267038de9 to your computer and use it in GitHub Desktop.
Save ladyada/f9f5ab3a4ee7a73337d251e267038de9 to your computer and use it in GitHub Desktop.
import serial
import io
import struct
from adafruit_debouncer import Debouncer
PORT = "COM7" # update me to match your setup!
BUTTON_0_MASK = 0b000000000010000
BUTTON_1_MASK = 0b000000100000000
BUTTON_2_MASK = 0b000001000000000
BUTTON_3_MASK = 0b000010000000000
BUTTON_4_MASK = 0b000100000000000
BUTTON_5_MASK = 0b000000000000001
BUTTON_6_MASK = 0b000000000000010
BUTTON_7_MASK = 0b000000000000100
BUTTON_8_MASK = 0b000000000001000
button_masks = [BUTTON_0_MASK,
BUTTON_1_MASK, BUTTON_2_MASK, BUTTON_3_MASK, BUTTON_4_MASK,
BUTTON_5_MASK, BUTTON_6_MASK, BUTTON_7_MASK, BUTTON_8_MASK]
curr_buttonstate = [False] * len(button_masks)
last_buttonstate = [False] * len(button_masks)
ser = serial.Serial(PORT, 9600, timeout=0.01)
print(ser.name)
def read_line(ser):
line = b''
while True:
x = ser.read()
if x == b'':
continue
#print(x, line)
if x == b'\r' or x == b'\n' :
break
if x != b'':
line = line + x
return line
def init(ser):
ser.write(b'CB\x01\r')
ser.write(b'MSS\r')
init(ser)
while True:
ser.write(b'd\r')
line = read_line(ser)
if not line:
continue
#print("READ:", line)
if line[0] == ord('K'): # button data
mask = struct.unpack('<H', line[1:])[0]
for buttonnum, bmask in enumerate(button_masks):
last_buttonstate[buttonnum] = curr_buttonstate[buttonnum]
if mask & bmask:
curr_buttonstate[buttonnum] = True
else:
curr_buttonstate[buttonnum] = False
if line[0] == ord('D'): # ball data
line = line.replace(b'^Q', b'\x11')
line = line.replace(b'^S', b'\x13')
line = line.replace(b'^M', b'\x0D')
line = line.replace(b'^^', b'^')
if len(line) != 15:
#print("Skip")
continue
period, xx, yy, zz, XX, YY, ZZ = struct.unpack('>Hhhhhhh', line[1:])
print("(%d, %d, %d) / (%d, %d, %d)" % (xx, yy, zz, XX, YY, ZZ))
for button in range(len(curr_buttonstate)):
if last_buttonstate[button] and not curr_buttonstate[button]:
print("Released", button)
last_buttonstate[button] = curr_buttonstate[button]
if not last_buttonstate[button] and curr_buttonstate[button]:
print("Pressed", button)
last_buttonstate[button] = curr_buttonstate[button]
ser.close() # close port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment