Skip to content

Instantly share code, notes, and snippets.

@DiegoAscanio
Last active August 22, 2024 19:10
Show Gist options
  • Save DiegoAscanio/fae3fe59c9cb4b1e0941045d585b9285 to your computer and use it in GitHub Desktop.
Save DiegoAscanio/fae3fe59c9cb4b1e0941045d585b9285 to your computer and use it in GitHub Desktop.
serial-keypad
import serial
from evdev import UInput, ecodes as e
# create a dictionary of keycodes to map serial data
# to keycodes
keymap = {
'1': [e.KEY_1],
'2': [e.KEY_2],
'3': [e.KEY_3],
'4': [e.KEY_4],
'5': [e.KEY_5],
'6': [e.KEY_6],
'7': [e.KEY_7],
'8': [e.KEY_8],
'9': [e.KEY_9],
'0': [e.KEY_0],
'L': [e.KEY_LEFT],
'R': [e.KEY_RIGHT],
'D': [e.KEY_DOWN],
'U': [e.KEY_UP],
'E': [e.KEY_ENTER],
'.': [e.KEY_DOT]
}
# Open the serial port
ser = serial.Serial('/dev/ttyACM0', 9600)
# Create a virtual input device
ui = UInput()
try:
while True:
if ser.in_waiting:
data = ser.read().decode('utf-8')
if 'TECLA_' in data:
data = data.replace('TECLA_', '')
if data in keymap:
# press keys
for key in keymap[data]:
ui.write(e.EV_KEY, key, 1)
# release keys
for key in keymap[data][::-1]:
ui.write(e.EV_KEY, key, 0)
ui.syn()
if 'K_' in data:
data = data.replace('K_', '')
# realizar logica do K
if 'I_' in data:
data = data.replace('I_', '')
# realizar logica do I
if 'D_' in data:
data = data.replace('D_', '')
# realizar logica do D
except KeyboardInterrupt:
pass
finally:
ser.close()
ui.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment