У меня есть манометр дифференциального давления, который я подключаю через USB на Raspberry 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@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
Извините за длинный пост, я ценю любой комментарий