import dht
import machine
import time
import paho.mqtt.client as mqtt
# Initialize the DHT22 sensor on GPIO pin 13
dht_pin = machine.Pin(13)
sensor = dht.DHT22(dht_pin)
# MQTT setup
mqtt_broker = "broker.emqx.io"
mqtt_port = 1883
mqtt_topic = "sensor/temperature_humidity"
mqtt_client_id = "dht22_sensor_client"
# Create an MQTT client
mqtt_client = mqtt.Client(mqtt_client_id)
# Connect to the broker
mqtt_client.connect(mqtt_broker, mqtt_port)
# Variables to store last measured values
last_temp = None
last_hum = None
def read_sensor_data():
"""Read data from the DHT22 sensor and return temperature and humidity."""
try:
sensor.measure() # Take a measurement
temperature = sensor.temperature() # Get temperature in Celsius
humidity = sensor.humidity() # Get humidity in percentage
return temperature, humidity
except Exception as e:
print('Error occurred: ', e)
return None, None
def print_if_changed(current_value, last_value, label):
"""Print the value if it has changed from the last one."""
if current_value != last_value:
print(f'{label}: {current_value}')
return current_value
return last_value
def send_mqtt_message(temperature, humidity):
"""Send the temperature and humidity to the MQTT broker."""
message = f"Temperature: {temperature} °C, Humidity: {humidity} %"
mqtt_client.publish(mqtt_topic, message)
print(f"Sent to MQTT: {message}")
while True:
temperature, humidity = read_sensor_data()
if temperature is not None and humidity is not None:
# Print and send data if it has changed
last_temp = print_if_changed(temperature, last_temp, 'Temperature (°C)')
last_hum = print_if_changed(humidity, last_hum, 'Humidity (%)')
# Send the data to the MQTT broker
send_mqtt_message(temperature, humidity)
# Wait for a short period before taking another reading
time.sleep(2) # Adjusted sleep time for better performance