import network
import time
import dht
import machine
from umqtt.simple import MQTTClient
ssid = "Wokwi-GUEST"
password = ""
def connect_to_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
if not wlan.active():
wlan.active(True)
if not wlan.isconnected():
print(f"Try connect to SSID : {ssid}")
wlan.connect(ssid, password)
while not wlan.isconnected():
print('.', end=" ")
time.sleep_ms(500)
return wlan
# Broker details
mqtt_broker = "4e93d9457b5d4cab8d4432171f2f0c55.s1.eu.hivemq.cloud"
mqtt_port = 8883 # Secure port for TLS/SSL
mqtt_username = "Seifounest"
mqtt_password = "Donia*+1995"
topic_temperature = "IoT/seif/temperature"
topic_humidity = "IoT/seif/humidity"
# Connect to MQTT Broker
def connect_mqtt():
ssl_params = {"server_hostname": mqtt_broker}
client = MQTTClient(
"ESP32_" + str(time.time()),
mqtt_broker,
port=mqtt_port,
user=mqtt_username,
password=mqtt_password,
ssl=True,
ssl_params=ssl_params,
)
client.connect()
return client
if __name__ == "__main__":
# Initialize DHT22 sensor
dht_sensor = dht.DHT22(machine.Pin(15))
my_wlan = connect_to_wifi(ssid, password)
client = connect_mqtt()
print("Connected to MQTT")
while True:
try:
dht_sensor.measure() # Correct method name
temp = dht_sensor.temperature()
humidity = dht_sensor.humidity()
print(f"Temperature: {temp}°C, Humidity: {humidity}%")
client.publish(topic_temperature, str(temp))
client.publish(topic_humidity, str(humidity))
except Exception as e:
print("Error reading sensor:", e)
time.sleep(5) # Wait 5 seconds before the next reading