Read/Write 半实时 Python 中的串行数据(<0.1 秒延迟)

Read/Write Serial data in Python in semi-realtime (<0.1 second delay)

我想在 /dev/ttyUSB0115200 的波特率读取和写入串行连接。 [它使用 PL2303 芯片组也可能是相关的] 有没有办法在 python 2.7 中通过 printraw_input 语句做到这一点?

您要查找的术语是波特率。 115200 波特表示串行端口每秒能够传输 115200 位(:读取 BITS)。这是一个相当常见的波特率,因此只要您的 USB UART 能够跟上,这应该不是问题。我有一个超旧的 FTDI USB UART,它在 19200 年以上都不可靠,但这是唯一让我感到悲伤的。电缆损坏的症状是在您的响应和传输中丢失字符。

我认为您不能使用 print 或 raw_input 进行串行处理。如果可以,我认为没有任何理由这样做,因为这不是它们的设计目的。你要用的是pyserial模块:https://github.com/pyserial/pyserial

我有一个在 Raspberry Pi 上运行的项目 https://github.com/PyramidTechnologies/Python-RS-232 很好。实施要点:

    ser = serial.Serial(
        port=portname,
        baudrate=115200,
        bytesize=serial.SEVENBITS,
        parity=serial.PARITY_EVEN,
        stopbits=serial.STOPBITS_ONE
    )

请务必设置为您的目标设备所说的任何内容

然后为了读写,像这样设置一些流量控制:

// msg could be a list of numbers. e.g. [4, 56, 34, 213]
ser.write(msg)

// Experiment with delay before reading if you are not getting
// a response right away.
time.sleep(0.1)

// Keep reading from port while there is data to read
out = ''
while ser.inWaiting() > 0:
    out += ser.read(1)
    if out == '':
        continue

// out is now the received bytes
// https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.read