我正在尝试使用覆盆子pi3中的python从血压监测器获取数据。我用谷歌搜索并找到一些使用python获取数据的例子。
我的代码:
#!/usr/bin/python
import serial
neo = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=0
)
print("connected to: " + neo.portstr)
#neo.open() #opens port
print "Is port open ? ",neo.isOpen() #returns true?
#ser.write("help\n");
while True:
dataline = neo.readline();
if dataline:
print(dataline), neo.close()
当我使用" sudo python pyusb.py "命令,它返回以下错误:
connected to: /dev/ttyUSB0
Is port open ? True
None
Traceback (most recent call last):
File "pyusb.py", line 18, in <module>
dataline = neo.readline();
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 443, in read
if not self._isOpen: raise portNotOpenError
ValueError: Attempting to use a port that is not open
如果未注释该行&#34; neo.open()&#34;它引发了另一个错误:
connected to: /dev/ttyUSB0
Traceback (most recent call last):
File "pyusb.py", line 13, in <module>
neo.open() #opens port
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 271, in open
raise SerialException("Port is already open.")
serial.serialutil.SerialException: Port is already open.
我看过类似的问题here。但是有一个问题是覆盖&#34; serial.Serial()&#34;方法。我无法确切地确定上面的代码有什么问题。谁能帮助我,我在那里做错了什么?
答案 0 :(得分:1)
如果你看一下pyserial的文档,http://pyserial.readthedocs.io/en/latest/shortintro.html#readline它说你必须在使用readline()
时指定超时。这是因为readline()
在每次传输结束时等待EOL字符。尝试使用以下内容将超时增加到1:
import serial
neo = serial.Serial(
port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
print("connected to: " + neo.portstr)
while True:
dataline = neo.readline();
print dataline