#!/usr/bin/env python3 import evdev from evdev import InputDevice, categorize, ecodes import glob import serial import time # Controller #device_candidates = glob.glob('/dev/input/by-id/usb-8BitDo*-event*') device_candidates = glob.glob('/dev/input/by-id/usb-8Bit*') if not device_candidates: print("Error: No matching 8BitDo input device found.") sys.exit(1) device_path = device_candidates[0] #device_path = '/dev/input/by-id/usb-8BitDo_8BitDo_Ultimate_Controller_6fdf5bd817e4-event-joystick' #or just put it in # UART serial_port = '/dev/ttyUSB0' baudrate = 115200 device = InputDevice(device_path) print(f"Listening on {device.name} ({device_path})") ser = serial.Serial(serial_port, baudrate, timeout=1) print(f"UART opened on {serial_port} at {baudrate} bps") # diganostic time stamps def timestamp_ms(): return int(time.time() * 1000) import select button_map = { 'BTN_SOUTH': 'B', 'BTN_EAST': 'A', 'BTN_NORTH': 'Y', 'BTN_WEST': 'X', } try: while True: r, w, x = select.select([device.fd], [], [], 0.005) # timeout = 10ms if device.fd in r: for event in device.read(): ts = timestamp_ms() if event.type == ecodes.EV_KEY: key_event = categorize(event) k = key_event.keycode if isinstance(k, tuple): name = next((button_map[x] for x in k if x in button_map), str(k)) else: name = button_map.get(k, k) msg = f"KEY:{name}:{key_event.keystate}\n" ser.write(msg.encode('utf-8')) print(f"[{ts}] Sent: {msg.strip()}") elif event.type == ecodes.EV_ABS: axis = ecodes.ABS.get(event.code, f"ABS_{event.code}") val = event.value if axis == 'ABS_HAT0Y' or axis == 'ABS_HAT0X': if axis == 'ABS_HAT0Y': if val == -1: ser.write(b"KEY:U:1\r\n") print(f"[{ts}] Sent: KEY:U:1:") elif val == 1: ser.write(b"KEY:D:1\r\n") print(f"[{ts}] Sent: KEY:D:1:") elif val == 0: #ser.write(b"KEY:U:0\r\nKEY:D:0\r\n") print(f"[{ts}] Sent: KEY:U:0\n[{ts}] Sent: KEY:D:0") elif axis == 'ABS_HAT0X': if val == -1: ser.write(b"KEY:L:1\r\n") print(f"[{ts}] Sent: KEY:L:1:") elif val == 1: ser.write(b"KEY:R:1\r\n") print(f"[{ts}] Sent: KEY:R:1:") elif val == 0: #ser.write(b"KEY:L:0\r\nKEY:R:0\r\n") print(f"[{ts}] Sent: KEY:L:0\n[{ts}] Sent: KEY:R:0") else: msg = f"ABS:{axis}:{event.value}:\r\n" ser.write(msg.encode('utf-8')) print(f"[{ts}] Sent: {msg.strip()}") except KeyboardInterrupt: print("\nExiting...") finally: ser.close() print("UART closed.")