Skip to content

Instantly share code, notes, and snippets.

@cuu
Created May 14, 2026 08:31
Show Gist options
  • Select an option

  • Save cuu/1d477608042dc50ab6e5204a9fa98199 to your computer and use it in GitHub Desktop.

Select an option

Save cuu/1d477608042dc50ab6e5204a9fa98199 to your computer and use it in GitHub Desktop.
mouse_driver.py
import serial
from pynput.mouse import Controller
import time
# 配置串口
SERIAL_PORT = '/dev/ttyUSB0'
mouse = Controller()
remX = 0.0
remY = 0.0
try:
ser = serial.Serial(SERIAL_PORT, 115200, timeout=0.01)
print(f"Connected to {SERIAL_PORT}. Controlling mouse...")
while True:
line = ser.readline().decode('utf-8').strip()
if line:
try:
# 读取 Arduino 发出的位移分量
parts = line.split(',')
if len(parts) == 2:
dx = float(parts[0]) + remX
dy = float(parts[1]) + remY
# 拆分整数位移和剩余小数
stepX = int(dx)
stepY = int(dy)
remX = dx - stepX
remY = dy - stepY
if stepX != 0 or stepY != 0:
mouse.move(stepX, stepY)
except Exception as e:
continue
time.sleep(0.001)
except KeyboardInterrupt:
print("\nStopped.")
finally:
if 'ser' in locals():
ser.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment