"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
import ujson
from umqtt.simple import MQTTClient
import dht
from machine import Pin
# MQTT Configuration
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "mqtt-dashboard.com" # Try a different broker if needed
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
MQTT_KEEPALIVE = 60 # Keep the connection alive
# GPIO Configuration
sensor = dht.DHT22(Pin(15)) # DHT22 on GPIO 15
led = Pin(10, Pin.OUT) # LED on GPIO 2 (built-in LED for ESP32)
# Connect to WiFi
def connect_wifi():
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '') # Change to your WiFi SSID and password
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.5)
print(" Connected!")
# Connect to MQTT Broker
def connect_mqtt():
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD, keepalive=MQTT_KEEPALIVE)
try:
client.connect()
print("Connected to MQTT!")
return client
except OSError as e:
print("MQTT connection failed:", e)
return None
# Start WiFi & MQTT Connection
connect_wifi()
client = connect_mqtt()
prev_weather = ""
while True:
try:
# Ensure WiFi is still connected
if not network.WLAN(network.STA_IF).isconnected():
print("WiFi disconnected! Reconnecting...")
connect_wifi()
client = connect_mqtt()
print("Measuring weather conditions... ", end="")
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Filter out invalid temperature readings
if temperature < -50 or temperature > 100:
print("Invalid temperature reading, skipping...")
time.sleep(5)
continue
# LED logic: Turn on if temp > 40°C
if temperature > 40:
led.value(1) # Turn ON LED
else:
led.value(0) # Turn OFF LED
# Prepare MQTT message
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
# Publish only if there's a change
if message != prev_weather and client:
print(f"Reporting to MQTT topic {MQTT_TOPIC}: {message}")
try:
client.publish(MQTT_TOPIC, message)
prev_weather = message
except OSError as e:
print("Publish failed:", e)
client = connect_mqtt() # Reconnect MQTT if needed
else:
print("No change in weather data.")
time.sleep(5) # Prevent spamming the broker
except Exception as e:
print("Error:", e)
time.sleep(5) # Prevent crash loop