PySerial 最小示例:将串口接收的数据复制到 stdout

此示例不向串口发送数据,只将从串口接收的数据复制到 stdout。从串口接收的换行符被保留。

pyserial_copy_serial_to_stdout.py
#!/usr/bin/env python3
import serial
ser = serial.Serial("/dev/ttyUSB0", baudrate=115200)

try:
    while True:
        response = ser.read()
        if response:
            print(response.decode("iso-8859-1"), end="")
finally:
    ser.close()

通过使用 iso-8859-1 解码,我们确保即使二进制字节也以某种方式解码,不会导致异常。


Check out similar posts by category: 3D Printing, Embedded, Python