import machine
import network
import time
from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from time import sleep
import dht
import ujson
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 = "mywheather"
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 = ""
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
LCD = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
DHT = dht.DHT22(Pin(4))
LEDT=Pin(32,Pin.OUT)
LEDH=Pin(33,Pin.OUT)
last_t=0
last_h=0
while True:
try:
sleep(2)
DHT.measure()
t = DHT.temperature()
h = DHT.humidity()
if t<18 or t>25:
LEDT.value(1)
else:
LEDT.value(0)
if h<20 or h>60:
LEDH.value(1)
else:
LEDH.value(0)
if t!=last_t or h!=last_h:
LCD.clear()
LCD.putstr("t: %3.1f C\n" %t)
LCD.putstr("h: %3.1f %%" %h)
last_t=t
last_h=h
print("Measuring weather conditions... ", end="")
message = ujson.dumps({
"temp": t,
"humidity": h,
})
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)
except OSError as e:
print('Failed to read sensor.')