import Adafruit_DHT sensor = Adafruit_DHT.DHT11 pin = 4 humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: print('Temperature = {0:0.1f}*C Humidity = {1:0.1f}%'.format(temperature, humidity)) else: print('Failed to retrieve data from sensor')
import Adafruit_DHT sensor = Adafruit_DHT.DHT22 pin = 17 try: humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) print('Temperature = {0:0.1f}*C Humidity = {1:0.1f}%'.format(temperature, humidity)) except Adafruit_DHT.DHTError: print('Failed to retrieve data from sensor') except Exception as e: print(e)In this example, the DHT22 sensor is connected to pin 17 of the Raspberry Pi. The read_retry() function is called inside a try/except block to handle any errors that may occur during the reading process. If the function raises a DHTError exception, the message "Failed to retrieve data from sensor" is printed to the console. If any other exception occurs, the exception message is printed to the console.