2

我正在尝试打印来自 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,但我不知道如何以任何其他方式使用它。

4

3 回答 3

1

您是否尝试将 readline 包装在 try/except SerialException 块中?然后,您可以只传递 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
于 2012-10-05T01:03:40.233 回答
0

我相信你想使用函数 read(),而不是 readline()。您正在检索缓冲区中的字符数,它们不一定以换行符结尾

你的循环变成:

while 1:
   if s.inWaiting():
      val = s.read(s.inWaiting())
      print val
于 2012-10-05T01:29:30.113 回答
0

如果您只想打印来自串行连接设备的数据。您只需使用readline()即可。首先使用open()打开端口,然后您需要使用readline()

注意:/dev/ttyUSB0 是 linux 的端口号,com0 是 windows

这是代码

import serial 

BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)

s.open()
print s

try:
    while True:
        line = s.readline()   //after this you can give the sleep time also as time.sleep(1) before that import time module.
        print line
finally:
    s.close()
于 2014-04-21T04:22:08.270 回答