import serial import time try: # 配置串口参数 - 请根据实际设备修改端口号 ser = serial.Serial( port='COM27', # 修改为实际的端口号 baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 # 添加超时设置,避免程序卡死 ) if ser.is_open: print(f"成功打开串口: {ser.port}") # 发送数据 data = "Hello, Serial!" ser.write(data.encode('utf-8')) print(f"发送数据: {data}") time.sleep(1) ser.close() print("串口已关闭") except serial.SerialException as e: print(f"串口错误: {e}") except Exception as e: print(f"发生错误: {e}")