main.py 778 B

123456789101112131415161718192021222324252627282930
  1. import serial
  2. import time
  3. try:
  4. # 配置串口参数 - 请根据实际设备修改端口号
  5. ser = serial.Serial(
  6. port='COM27', # 修改为实际的端口号
  7. baudrate=115200,
  8. parity=serial.PARITY_NONE,
  9. stopbits=serial.STOPBITS_ONE,
  10. bytesize=serial.EIGHTBITS,
  11. timeout=1 # 添加超时设置,避免程序卡死
  12. )
  13. if ser.is_open:
  14. print(f"成功打开串口: {ser.port}")
  15. # 发送数据
  16. data = "Hello, Serial!"
  17. ser.write(data.encode('utf-8'))
  18. print(f"发送数据: {data}")
  19. time.sleep(1)
  20. ser.close()
  21. print("串口已关闭")
  22. except serial.SerialException as e:
  23. print(f"串口错误: {e}")
  24. except Exception as e:
  25. print(f"发生错误: {e}")