add exception handling to convert humidity

This commit is contained in:
Robert Borzutzki 2021-02-15 11:44:38 +00:00
parent 6d06b429d5
commit 66a25e7719

View File

@ -45,22 +45,29 @@ client.connect(mqtt_broker) # MQTT server address
client.loop_start() client.loop_start()
while True: while True:
# Get Temperature from DHT # Get Temperature from DHT
_, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) _, temperature = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
temperature = round(float(temperature), 2)
# Get Humidity from DHT # Get Humidity from DHT
humidity, _ = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) humidity, _ = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN)
humidity = round(float(humidity), 2)
# Publish our data
client.publish(temperature_topic, temperature)
client.publish(humidity_topic, humidity)
client.publish(time_topic, dt_string)
#Output data to screen #Output data to screen
print(dt_string) print(dt_string)
print(temperature) print(temperature)
print(humidity) print(humidity)
temperature = round(float(temperature), 2)
try:
humidity = round(float(humidity), 2)
break
except ValueError:
print("Not able to convert humidity to float: " + humidity)
# Publish our data
client.publish(temperature_topic, temperature)
client.publish(humidity_topic, humidity)
client.publish(time_topic, dt_string)
time.sleep(30) time.sleep(30)