import time
import network
import dht
import machine
from umqtt.simple import MQTTClient
# Wi-Fi credentials
ssid = "Wokwi-GUEST"
password = ""
# MQTT broker details
mqtt_server = "test.mosquitto.org"
my_topic2 = "temperature"
my_topic3 = "Humidity"
# Initialize DHT22 sensor
sensor = dht.DHT22(machine.Pin(4)) # GPIO pin where the sensor is connected
# Connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
print('Connecting to network...')
time.sleep(1)
print('Network connected')
print('IP address:', wlan.ifconfig()[0])
# Connect to MQTT broker
def connect_mqtt():
client = MQTTClient("ESP32Client", mqtt_server)
try:
client.connect()
print("Connected to MQTT Broker")
except Exception as e:
print(f"Failed to connect to MQTT Broker: {e}")
time.sleep(5)
machine.reset()
return client
# Main function to publish sensor data
def publish_sensor_data(client):
while True:
try:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
print(f"Temp: {temperature:.1f} C Humidity: {humidity:.1f} %")
client.publish(my_topic2, str(temperature))
client.publish(my_topic3, str(humidity))
except Exception as e:
print(f"Failed to read from sensor or publish data: {e}")
client.disconnect()
client = connect_mqtt()
time.sleep(2) # Delay to avoid flooding the MQTT broker with messages
# Connect to Wi-Fi
connect_wifi()
# Connect to MQTT broker and start publishing sensor data
mqtt_client = connect_mqtt()
publish_sensor_data(mqtt_client)