import dht
from machine import Pin
import wifi
import time
from umqtt.simple import MQTTClient
# Initialize DHT sensor on pin 12
d = dht.DHT22(Pin(12, Pin.IN))
# Connect to Wi-Fi
wifi.connect_ap()
# Connect to MQTT Broker
# Use MD5 to encrypt the name of the topic to identify on MQTT
client_id = "650ea76379ff486f95098f7fb3e361f2.s2.eu.hivemq.cloud"
server = "broker.hivemq.com"
client = MQTTClient(client_id, server)
client.connect()
def loop():
while True:
# Measure temperature and humidity
d.measure()
temperature = d.temperature()
humidity = d.humidity()
print("Send data to broker")
# Publish temperature data to MQTT broker
client.publish("IoT_MQTT_TemperatureA", str(temperature))
# Uncomment the line below if you want to publish humidity data as well
# client.publish("IoT_MQTT_HumidityA", str(humidity))
# Send data every 5 seconds
time.sleep(2)
if __name__ == "__main__":
loop()