Skip to main content
 首页 » 编程设计

python之如何在 python 中一致地从串行打印数据

2025年05月04日8think

我正在尝试打印来自 Arduino 的串行数据,但我无法这样做。我尝试的代码是这样的:

import serial 
import time 
s = serial.Serial('/dev/tty.usbmodemfd141',9600) 
 
while 1: 
   if s.inWaiting(): 
      val = s.readline(s.inWaiting()) 
      print val 

但是在大​​约 30 行左右被吐出后,我收到以下错误消息:

Traceback (most recent call last): 
  File "py_test.py", line 7, in <module> 
    val = s.readline(s.inWaiting()) 
  File "build/bdist.macosx-10.8-intel/egg/serial/serialposix.py", line 460, in read 
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?) 

我想我错误地使用了 inWaiting,但我不知道如何以任何其他方式使用它。

请您参考如下方法:

您是否尝试过将 readline 包装在 try/except SerialException block 中?然后您可以传递 SerialException。当接收缓冲区中没有任何数据时,串行驱动程序报告数据可能是一个问题,在这种情况下,您的代码将继续运行。不是一个很好的修复,但它可能会引导您找到正确的解决方案。

try: 
    s.read(s.inWaiting()) 
except serial.serialutil.SerialException: 
    pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is