from machine import Pin, I2C, ADC
import network
import time
import dht
import ujson
from umqtt.simple import MQTTClient
from DFRobot_RGBLCD1602 import DFRobot_RGBLCD1602 # Import the library
# I2C Setup for LCD1602
i2c = I2C(scl=Pin(4), sda=Pin(2), freq=100000)
lcd = DFRobot_RGBLCD1602(i2c) # Initialize the LCD
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
sensor = dht.DHT22(Pin(15))
ldr = ADC(Pin(36)) # Initialize the LDR sensor on pin A0 (GPIO 36 for ESP32)
print("Connecting to WiFi", end="")
lcd.printStr("Connecting to WiFi")
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!")
lcd.clear()
lcd.printStr("Connected to WiFi!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
prev_weather = ""
prev_ldr_value = -1 # To store the previous LDR value
while True:
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
ldr_value = ldr.read()
# Display on LCD
lcd.clear()
lcd.printStr("Temp: {}C\nHumidity: {}%".format(temperature, humidity))
time.sleep(2)
lcd.clear()
lcd.printStr("Light Intensity:\n{}".format(ldr_value))
time.sleep(2)
message = ujson.dumps({
"temp": temperature,
"humidity": humidity,
})
if message != prev_weather:
print("Weather Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
try:
client.publish(MQTT_TOPIC, message)
except OSError as e:
print("MQTT Publish Error:", e)
prev_weather = message
if ldr_value != prev_ldr_value:
print("LDR value updated!")
ldr_message = ujson.dumps({
"ldr": ldr_value
})
print("Reporting LDR value to MQTT topic {}: {}".format(MQTT_TOPIC, ldr_message))
try:
client.publish(MQTT_TOPIC, ldr_message)
except OSError as e:
print("MQTT Publish Error:", e)
prev_ldr_value = ldr_value
time.sleep(1)