import network
import time
from machine import Pin, SoftI2C
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.hivemq.com" # Use an alternative broker if needed
MQTT_USER = "Child"
MQTT_PASSWORD = "man"
MQTT_TOPIC = "wokwi-weather"
# DHT22 Sensor and LED Setup
sensor = dht.DHT22(Pin(15))
led = Pin(2, Pin.OUT)
# I2C LCD setup using SoftI2C (modify according to your I2C address)
I2C_ADDR = 0x27
I2C_SCL = 33
I2C_SDA = 32
i2c = SoftI2C(scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=400000)
# LCD Driver Implementation
class I2cLcd:
def __init__(self, i2c, address, rows, cols):
self.i2c = i2c
self.address = address
self.rows = rows
self.cols = cols
self.init_lcd()
def init_lcd(self):
self.write_cmd(0x33)
self.write_cmd(0x32)
self.write_cmd(0x28)
self.write_cmd(0x0C)
self.write_cmd(0x06)
self.write_cmd(0x01)
time.sleep_ms(5)
def write_cmd(self, cmd):
self.i2c.writeto(self.address, bytearray([0x80, cmd]))
def write_data(self, data):
self.i2c.writeto(self.address, bytearray([0x40, data]))
def clear(self):
self.write_cmd(0x01)
time.sleep_ms(5)
def putstr(self, string):
for char in string:
self.write_data(ord(char))
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# Connect to WiFi
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Function to connect to MQTT Broker
def connect_mqtt():
print("Connecting to MQTT server... ", end="")
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
return client
except Exception as e:
print(f"Failed to connect to MQTT broker: {e}")
return None
client = connect_mqtt()
prev_weather = ""
while True:
if client is None:
client = connect_mqtt()
time.sleep(10) # Wait before trying to reconnect
continue
try:
print("Measuring weather conditions... ", end="")
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
# Turn on LED
led.value(1)
# Display data on LCD
lcd.clear()
lcd.putstr("Temp: {:.1f} C".format(temperature))
lcd.putstr("\nHumidity: {:.1f}%".format(humidity))
# Keep the LED on for a short time to indicate data was sent
time.sleep(1)
led.value(0)
else:
print("No change")
time.sleep(10) # Wait 10 seconds before measuring again
except OSError as e:
print(f"Connection error: {e}")
client = None
time.sleep(10) # Wait before trying to reconnect