import machine
import dht
import time
from machine import Pin
DHT_PIN = 18
class DHT22App:
def __init__(self):
self.dht_sensor = dht.DHT22(Pin(DHT_PIN))
self.temperature = None
self.humidity = None
def read_sensor_data(self):
try:
while True:
# Read data from the DHT22 sensor
self.dht_sensor.measure()
self.temperature = self.dht_sensor.temperature()
self.humidity = self.dht_sensor.humidity()
if self.temperature is not None and self.humidity is not None:
print(f'Temperature: {self.temperature:.2f}°C, Humidity: {self.humidity:.2f}%')
else:
print('Failed to get reading. Try again!')
time.sleep(2)
except KeyboardInterrupt:
print('Measurement stopped by the user.')
except Exception as e:
print(f'Error: {e}')
if __name__ == "__main__":
app = DHT22App()
app.read_sensor_data()