from machine import I2C, Pin
from pico_i2c_lcd import I2cLcd
import time
import dht
from umqtt.simple import MQTTClient
import ujson
import network
tm = 0
sensor = dht.DHT22(Pin(22))
hapin = Pin(15, Pin.OUT)
tapin = Pin(17, Pin.OUT)
dht_interval = 500
hum = 40
temp = 40
i2c_bus = I2C(0, sda=Pin(12), scl=Pin(13), freq=400000)
i2c_address = i2c_bus.scan()[0]
lcd = I2cLcd(i2c_bus, i2c_address, 2, 16)
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
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:
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)
while True:
if time.ticks_ms() - tm >= dht_interval:
sensor.measure()
hum = sensor.humidity()
temp = sensor.temperature()
lcd.putstr("hum=" + str(hum) + " ")
lcd.move_to(0, 1)
lcd.putstr("temp=" + str(temp) + " ")
lcd.move_to(0, 0)
tm = time.ticks_ms()
if hum < 20 or hum > 60:
hapin.value(1)
else:
hapin.value(0)
if temp > 45 or temp < 18:
tapin.value(1)
else:
tapin.value(0)