无法从串口读取数据

Unable to read data from serial port

我尝试使用 pyserial 从 OSX 上的 USB 端口读取数据。当我尝试使用 CoolTerm 阅读它时,一切正常。这是配置:

然后我试着写了一个不连续输出数据的短脚本(它只输出一次数据,即使我重新启动脚本也没有输出):

import serial
import time

ser = serial.Serial("/dev/cu.SLAB_USBtoUART", 115200, timeout=5, bytesize=8, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE)


def getTFminiData():
    while True:
        # time.sleep(0.1)
        count = ser.in_waiting
        if count > 8:
            recv = ser.read(9)
            ser.reset_input_buffer()

            if recv[0] == 0x59 and recv[1] == 0x59:  # python3
                distance = recv[2] + recv[3] * 256
                strength = recv[4] + recv[5] * 256
                print('(', distance, ',', strength, ')')
                ser.reset_input_buffer()


if __name__ == '__main__':
    try:
        if ser.is_open == False:
            ser.open()
        getTFminiData()
    except KeyboardInterrupt:  # Ctrl+C
        if ser != None:
            ser.close()

有谁知道在这种情况下获取与 CoolTerm 相同的数据的正确方法是什么?

感谢Joe 的评论,我搞清楚了如何修改代码。工作示例如下:

import serial
import time

ser = serial.Serial("/dev/cu.SLAB_USBtoUART", 115200, bytesize=8, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE)


def getTFminiData():
    bytes_read = 0
    data = None
    while True:
        # time.sleep(0.1)
        count = max(1, ser.in_waiting)
        if count < 8:
            if data is None:
                data = ser.read(count)
            else:
                data.append(ser.read(count))
            bytes_read += count

        else:
            recv = ser.read(9 - bytes_read)
            bytes_read = 0
            recv = data + recv
            data = None
            ser.reset_input_buffer()

            if recv[0] == 0x59 and recv[1] == 0x59:  # python3
                distance = recv[2] + recv[3] * 256
                strength = recv[4] + recv[5] * 256
                print('(', distance, ',', strength, ')')
                ser.reset_input_buffer()


if __name__ == '__main__':
    try:
        if ser.is_open == False:
            ser.open()
        getTFminiData()
    except KeyboardInterrupt:  # Ctrl+C
        if ser != None:
            ser.close()