简体   繁体   English

Python 3中的多行串行读取

[英]Multiline serial read in Python 3

I am playing around with bidirectional serial communication between my PC and a STM32 development board. 我正在PC和STM32开发板之间进行双向串行通信。 I am using Python 3.7 with PySerial 3.4 to open the serial port and receive/transceive messages from/to the dev board. 我正在将Python 3.7PySerial 3.4一起使用以打开串行端口并从开发板接收消息/从开发板接收消息。 Everything is working as expected except when I try to read and print multiline messages. 除了我尝试阅读和打印多行消息时,其他所有工作都按预期进行。 In this case I only get the first line of the message. 在这种情况下,我只会得到消息的第一行。

The program on the microcontroller is such, that I get a multiline help-message back, if I send 'H' via serial to the controller board. 如果我通过串行将“ H”发送到控制器板上,那么微控制器上的程序就可以返回多行帮助消息。 The multiline message the dev board is sending back looks like this: 开发板发回的多行消息如下所示:

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

So I am expecting to see the following printout: 因此,我希望看到以下打印输出:

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

But instead I only get: 但是相反,我只会得到:

HELP

If I connect to the port with PuTTY and send 'H' manually, I get the full message; 如果我使用PuTTY连接到端口并手动发送“ H”,则会收到完整的消息; so I know that it is not a problem of my microcontroller program. 所以我知道这不是我的微控制器程序的问题。

My python code looks like this: 我的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)

Any help would be much appreciated. 任何帮助将非常感激。

You need to wait for new data after each line. 您需要在每行之后等待新数据。 Based on that, your read method need to be modified as below: 基于此,您的read方法需要进行如下修改:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM