我有一个差压压力计,可以通过USB连接到树莓派pi 3上,以成功完成数据记录。
我要完成的是,当我卸下USB时,代码将进入睡眠模式,直到重新连接。
对不起,如果我的代码有点幼稚,但是我是物理学家,并且我对优化代码等不了解很多。我在这里错过了很多吗?
import serial
import time
import os.path
while True:
if (os.path.exists('/dev/ttyUSB0') == True):
print ("USB connected")
time.sleep(1)
# setup
pceport = serial.Serial(port = '/dev/ttyUSB0',
baudrate = 9600,
parity = serial.PARITY_NONE,
bytesize = serial.EIGHTBITS,
writeTimeout = 0,
timeout = 1)
# command words
pceport.write([0x55, 0xaa, 0x01]) # connect to serial port to receive data
print ("Start reading...")
time.sleep(1)
# read from the serial port
while (pceport.isOpen() == True):
if (pceport.isOpen() == True):
pceport.read(5) # 2 ID bytes, Sign, Voltage and Unit skipped
else:
pceport.close()
if (pceport.isOpen() == True):
data = pceport.read(5) # Data bytes (5)
else:
pceport.close()
if (pceport.isOpen() == True):
pceport.read(1) # Checkcode byte skipped
else:
pceport.close()
print (data.decode('utf-8'), "mbar")
else:
print ("USB disconnected")
time.sleep(2)
print ("Trying to reconnect...")
time.sleep(8)
Pi的终端:
pi@raspberrypi:~ $ python3 pcetest.py
USB connected
Start reading...
0.182 mbar
0.139 mbar
0.185 mbar
0.245 mbar
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 490, in read
'device reports readiness to read but returned no data '
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pcetest.py", line 26, in <module>
pceport.read(5) # 2 ID bytes, Sign, Voltage and Unit skipped
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 497, in read
raise SerialException('read failed: {}'.format(e))
serial.serialutil.SerialException: read failed: device reports readiness to read but returned no data (device disconnected or multiple access on port?)
这是我拔下USB时的错误。我希望它退出阅读循环,回到顶部并进入USB断开连接循环,但事实并非如此。
在拔出插头并将其插入的情况下,它反之亦然。
pi@raspberrypi:~ $ python3 pcetest.py
USB disconnected
Trying to reconnect...
USB connected
Start reading...
0.260 mbar
0.228 mbar
0.242 mbar
0.230 mbar
很抱歉,很长的帖子,我感谢您的任何评论