import network
import time
from machine import Pin, I2C
import dht
import ujson
from umqtt.simple import MQTTClient
import ssd1306
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
# Initialize DHT22 sensor
sensor = dht.DHT22(Pin(15))
# Connect to Wi-Fi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
if not sta_if.isconnected():
print("WiFi disconnected, reconnecting...")
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Connect to MQTT server
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Initialize OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
# Get temperature and humidity
temperature = sensor.temperature()
humidity = sensor.humidity()
# Create JSON message for MQTT
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
# Publish data to MQTT
try:
client.publish(MQTT_TOPIC, message)
except OSError as e:
print("Failed to publish message, reconnecting...")
client.connect()
# Display temperature and humidity on OLED
oled.fill(0) # Clear the screen
oled.text("Temp: {:.1f} C".format(temperature), 0, 0)
oled.text("Humidity: {:.1f} %".format(humidity), 0, 16)
oled.show()
# Wait before next measurement
time.sleep(1)