I built an allsky camera with a temperature sensor and a heater. The heater is supposed to turn when the sensor (measure_temp()) return a temperature below 8, which is checked every 15 minutes. However, about every 4th measurement fails and so I included an error handler that returns 7, so that the heater turns on if the sensor returns an error, but it seems like a bad solution. Is there a better way to handle the error like run the function until no error occurs?
import RPi.GPIO as GPIO
import time
import datetime
import time
import board
import adafruit_dht
def measure_temp():
dhtDevice = adafruit_dht.DHT22(board.D18)
try:
temperature = dhtDevice.temperature
error_test = ""
except RuntimeError as error:
temperature = 7
except:
temperature = 7
return temperature
if __name__ == '__main__':
while True:
if measure_temp() < 8:
GPIO.setmode(GPIO.BCM)
RELAIS_1_GPIO = 17
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
GPIO.output(RELAIS_1_GPIO, GPIO.HIGH)
print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
print('Heating on')
print()
time.sleep(900)
GPIO.cleanup()
else:
GPIO.setmode(GPIO.BCM)
RELAIS_1_GPIO = 17
GPIO.setup(RELAIS_1_GPIO, GPIO.OUT)
GPIO.output(RELAIS_1_GPIO, GPIO.LOW)
print('{:%d.%m.%Y %H:%M:%S}'.format(datetime.datetime.now()))
print('Heating off')
time.sleep(900)
GPIO.cleanup()