import network
from machine import Pin, SoftI2C
import dht
import ujson
import time
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
led = Pin(5, Pin.OUT)
led1 = Pin(12, Pin.OUT)
sensor = dht.DHT22(Pin(14))
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000) #initializing the I2C method for ESP32
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
lcd.putstr("Hello master")
h = -1
t = -1
# Connecting to wifi / mqtt server
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!")
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 = ""
while True:
sensor.measure() # read the parameters from the sensor
if h != sensor.humidity() or t != sensor.temperature():# if the humidity or temperature is changed the LCD will display the value
h = sensor.humidity()
t = sensor.temperature()
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr("Humidity: ")
lcd.putstr(str(h))
lcd.move_to(0, 1)
lcd.putstr("Temperature:")
lcd.putstr(str(t))
'''
if the degree over 40C -> The light turns on
if the degree below 40C -> The light turns off
'''
if t > 40 :
led.on()
if t < 40 :
led.off()
if h < 50:
led1.on()
if h > 50:
led1.off()
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print("No change")
time.sleep(1)