import dht
import machine
import utime # Import utime module for timing
# Define the pin number to which the DHT sensor is connected
dht_pin = machine.Pin(10) # Change to the appropriate pin number
# Create a DHT object
dht_sensor = dht.DHT22(dht_pin)
while True:
try:
# Read temperature and humidity
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Check if the values are valid (not default)
if temperature != 0.0 and humidity != 0.0:
print("Temperature: {:.2f}°C".format(temperature))
print("Humidity: {:.2f}%".format(humidity))
# Categorize temperature range
if 20 <= temperature <= 40:
temp_category = "normal"
elif 40 < temperature <= 60:
temp_category = "high"
else:
temp_category = "extremely high"
# Categorize humidity range
if humidity <= 40:
humidity_category = "dry"
elif 40 < humidity <= 60:
humidity_category = "moderate"
else:
humidity_category = "humid"
# Print weather condition based on temperature and humidity
if temp_category == "normal" and humidity_category == "dry":
print("Mostly sunny and cool.")
elif temp_category == "high" and humidity_category == "humid":
print("Hot and humid.")
elif temp_category == "extremely high":
print("Extremely hot. Stay indoors.")
else:
print("Weather conditions not specified.")
else:
print("Invalid data. Retrying...")
# Delay for a specified time (e.g., 5 seconds)
utime.sleep(5) # Sleep for 5 seconds
except Exception as e:
print("Error:", e)