Created
May 14, 2026 08:31
-
-
Save cuu/1d477608042dc50ab6e5204a9fa98199 to your computer and use it in GitHub Desktop.
mouse_driver.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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