API

CH340 / serial mouse API

Python helper for relative mouse move and clicks for our RP2350/RP2040 CH340 firmware.

Overview

Communicate with our RP2350/RP2040 CH340 firmware. Supports CP210x and other similar USB-serial modules.

Install

  1. Download ch340.py and example.py
  2. pip install -r requirements.txt (or: pip install pyserial)
  3. Flash / power your RP+CH340 and confirm Windows shows a COM port in Device Manager

Quick start

Pass a COM port, or leave it blank to auto-detect.

quickstart.pypython
from ch340 import ch340

dev = ch340('COM3')  # leave blank for auto

if not dev.open():
    raise SystemExit("Failed to open device")

dev.move(50, -20)
dev.click(ch340.BTN_L)
dev.close()

Methods

MethodReturnsDescription
ch340(port=None)ch340Create a client. Port can be in the format of "COM3", "3", or None for auto-detect.
findPort()str | NoneStatic. Scans serial ports for CH340 / CH341 / CP210 adapters.
open()boolOpen the serial port at 921600 baud. Returns False on failure.
close()boolClose the serial connection.
isConnected()boolTrue when the serial port is open.
move(x, y)NoneRelative mouse move.
setButtons(mask)NoneSet the held button mask (bitfield). Use RELEASE (0x00) to release.
click(mask, down_ms=30)NonePress buttons for down_ms milliseconds, then release.

Button constants

Pass these masks to click() and setButtons().

buttons.pypython
ch340.RELEASE  # 0x00 — release all
ch340.BTN_L     # 0x01 — left
ch340.BTN_R     # 0x02 — right
ch340.BTN_M     # 0x04 — middle
ch340.BTN_X1    # 0x08 — side / back
ch340.BTN_X2    # 0x10 — side / forward

# Hold left, then release
dev.setButtons(ch340.BTN_L)
dev.setButtons(ch340.RELEASE)

Full example

example.pypython
from ch340 import ch340

dev = ch340('COM3') # leave blank for auto

if not dev.open():
    raise SystemExit("Failed to open device")

print(f'CH340 connected on port: {dev.port}')


# Relative mouse movement (x, y)
dev.move(50, -20)

# Button press
dev.click(ch340.BTN_L)              # left click for 30 ms (default)
dev.click(ch340.BTN_R, down_ms=50)  # right click for 50ms

# Hold a button down until you tell it to release
dev.setButtons(ch340.BTN_L) # hold left click
# do something
dev.setButtons(ch340.RELEASE) # release all


dev.close()