pySerial有时在使用`readline()时以新行打印

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

[每隔一秒钟,Arduino打印(串行)'当前时间(以毫秒为单位)和Hello world'。在串行监视器上,输出看起来不错。

但是在pySerial中,有时在字符串的中间有换行符。

313113   Hel
lo world
314114   Hello world
315114   Hello world

我的python代码为:

import serial
import time
ser = serial.Serial(port='COM4',
                    baudrate=115200,
                    timeout=0)

while True:
   str = ser.readline()         # read complete line
   str = str.decode()           # decode byte str into Unicode
   str = str.rstrip()           

   if str != "":
      print(str)
   time.sleep(0.01)

我做错了什么?

python-3.x arduino pyserial
1个回答
0
投票

我仍然不明白它发生的原因。但是以下代码通过检查结束字是否到达来解决此问题。它有效,但不是根本问题的解决方案。

import serial
import time
ser = serial.Serial(port='COM4',
                    baudrate=115200,
                    timeout=0)

while True:
   str = ser.readline()         # read complete line
   str = str.decode()           # decode byte str into Unicode
   str = str.rstrip()        

    while not 'world'in string:   
    # checking to see if the 'world' word is present or not.
    # if not, rerun to read serial output.
        temp = ser.readline()
        temp = temp.decode()        
        temp = temp.rstrip()
        str +=temp   

   if str != "":
      print(str)
   time.sleep(0.01)
© www.soinside.com 2019 - 2024. All rights reserved.