无法从串行端口读取数据

问题描述 投票:0回答:1

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

enter image description here

然后,我试图编写一个短脚本,该脚本不会连续输出数据(它只输出一次数据,即使重新启动脚本,也不会输出任何内容:]

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取得相同数据的正确方法是什么?

python pyserial
1个回答
0
投票

由于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()
© www.soinside.com 2019 - 2024. All rights reserved.