from machine import Pin
import dht
import time
# Define the GPIO pin connected to the DHT22 data pin
DHT_PIN = 16 # Example: Change this to the actual pin you are using
# Initialize the DHT22 sensor
sensor = dht.DHT22(Pin(DHT_PIN))
def read_dht22():
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
return temperature, humidity
except OSError as e:
print("Error reading DHT22 sensor:", e)
return None, None
if __name__ == "__main__":
while True:
temperature, humidity = read_dht22()
if temperature is not None and humidity is not None:
print("Temperature: {:.2f} °C".format(temperature))
print("Humidity: {:.2f} %".format(humidity))
else:
print("Failed to read temperature and humidity.")
time.sleep(2) # Read sensor data every 2 seconds