半实时读取/写入 Python 中的串行数据(<0.1 秒延迟)



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

您要查找的术语是波特率。115200波特表示串口每秒传输115200比特(即读比特)。这是一个相当常见的波特率,所以应该不是一个问题,只要你的USB UART可以跟上。我有一个超级老的FTDI USB UART,在19200以上是不可靠的,但这是唯一一个给我带来悲伤的。不良电缆的症状是损坏,在您的回复和传输中丢失字符。

我不认为你可以使用打印或raw_input串行处理。如果你可以,我不认为有任何理由,因为这不是他们设计的目的。您需要使用的是pyserial模块:https://github.com/pyserial/pyserial

我有这个项目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

最新更新