【问题标题】:Multiline serial read in Python 3Python 3 中的多行串行读取
【发布时间】:2019-01-15 17:21:00
【问题描述】:

我正在玩我的 PC 和 STM32 开发板之间的双向串行通信。我正在使用 Python 3.7PySerial 3.4 来打开串行端口并从/向开发板接收/收发消息。一切都按预期工作,除非我尝试阅读和打印多行消息。在这种情况下,我只得到消息的第一行。

微控制器上的程序是这样的,如果我通过串行向控制器板发送“H”,我会收到一条多行帮助消息。 开发板发回的多行消息如下所示:

"HELP\r\nList of commands:\r\nH:  Display list of commands\r\nS:  Start the application"

所以我期待看到以下打印输出:

HELP
List of commands:
H:  Display list of commands
S:  Start the application

但我只得到:

HELP

如果我使用 PuTTY 连接到端口并手动发送“H”,我会收到完整的消息;所以我知道这不是我的微控制器程序的问题。

我的 python 代码如下所示:

import serial
import io

class mySerial:
    def __init__(self, port, baud_rate):
        self.serial = serial.Serial(port, baud_rate, timeout=1)
        self.serial_io_wrapped = io.TextIOWrapper(io.BufferedRWPair(self.serial, self.serial))

    # receive message via serial
    def read(self):
        read_out = None
        if self.serial.in_waiting > 0:
            read_out = self.serial_io_wrapped.readline()
        return read_out

    # send message via serial
    def write(self, message):
        self.serial.write(message)

    # flush the buffer
    def flush(self):
        self.serial.flush()


commandToSend = 'H'
ser = mySerial('COM9', 115200)

ser.flush()
ser.write(str(commandToSend).encode() + b"\n")

while True:
    incomingMessage = ser.read()
    if incomingMessage is not None:
        print(incomingMessage)

任何帮助将不胜感激。

【问题讨论】:

    标签: python multiline pyserial


    【解决方案1】:

    您需要在每行之后等待新数据。基于此,您的读取方法需要修改如下:

    def read(self):
        read_out = None
        timeout = time.time() + 0.1
        while ((self.serial.in_waiting > 0) and (timeout > time.time())):
            pass
        if self.serial.in_waiting > 0:
            read_out = self.serial_io_wrapped.readline()
        return read_out
    

    【讨论】:

    • 感谢您的建议。刚才有机会测试你的代码。不幸的是,它并没有解决我的问题。我仍然只得到第一行:(
    猜你喜欢
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多