我在编写用于读取树莓派上的一些温度传感器(DS18B20)的脚本时遇到了麻烦。我有一个工作脚本,但有时传感器会掉下来,然后脚本也会停止。我正在尝试通过集成 try-except 语句来制作更强大的版本。如果其中一个传感器没有反应,目标是继续到范围内的下一个传感器。如果我通过拔出其中一个传感器来模拟传感器故障,则脚本将停止对所有传感器进行测量(而不是对已拔出的传感器进行测量)。它不会给我一个错误。有任何想法吗?
这是带有 try 语句的脚本部分:
if time.time() <= timeout:
for index in range (numsensors):
try:
def read_temp_raw(): # gets the temps one by one
f = open(device_file[index], 'r')
lines = f.readlines()
f.close()
return lines
def read_temp(): # checks the received temperature for errors
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
# set proper decimal place for deg C
temp = float(temp_string) / 1000.0
# Round temp to x decimal points --> round(temp,x)
temp = round(temp, 2)
return temp
reading = (read_temp())
temp[index].append(reading)
print device[index],"=", temp[index]
continue
except IOError:
print "Error"