#!/usr/bin/env python3 """ 快速探测板子上的串口:逐个尝试 COM4/5/8/9,找哪个有数据、波特率对不对。 板子代码里 UART3 用 Timer3 波特率(9600),UART2 用 Timer2(9600)。 """ import serial import serial.tools.list_ports import time CH340_PORTS = ['COM4', 'COM5', 'COM8', 'COM9'] BAUDRATES = [9600, 115200] def probe_port(port_name, baudrate): """开一个口,等 2 秒看有没有数据进来""" try: s = serial.Serial(port_name, baudrate, timeout=0.1) except serial.SerialException as e: print(f" {port_name} @ {baudrate}: OPEN FAIL → {e}") return None buf = b'' start = time.time() while time.time() - start < 2.0: data = s.read(256) if data: buf += data # 收到一些数据后再等一会儿 time.sleep(0.1) s.close() if buf: # 判断看起来像不像板子的 JSON 输出 printable = sum(1 for b in buf[:200] if 32 <= b < 127 or b in (10, 13)) total = min(len(buf), 200) ratio = printable / max(total, 1) print(f" {port_name} @ {baudrate}: GOT {len(buf)} bytes, printable_ratio={ratio:.2f}") # 打印前 200 字节 snippet = buf[:200].replace(b'\r', b'\\r').replace(b'\n', b'\\n') print(f" → {snippet.decode('ascii', errors='replace')}") return buf else: print(f" {port_name} @ {baudrate}: NO DATA in 2s") return None print("=" * 60) print("PROBE: 逐个探测 CH340 串口的 9600 / 115200") print("=" * 60) results = {} for p in CH340_PORTS: for br in BAUDRATES: data = probe_port(p, br) if data: results[(p, br)] = data print("\n" + "=" * 60) print(f"探测完毕,有数据的端口: {list(results.keys())}") print("=" * 60)