import machine
from machine import Pin, SoftI2C
import dht
import network
import time
from time import sleep
import ujson
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "tah"
MQTT_TOPIC2 = "mess"
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
sensor = dht.DHT22(Pin(23))
led_red=Pin(32,Pin.OUT)
led_blue=Pin(33,Pin.OUT)
buzzer=Pin(26,Pin.OUT)
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!")
last_temp=0
last_hum=0
while True:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
if temp<18 or temp>25:
led_red.value(1)
else:
led_red.value(0)
if hum<20 or hum>60:
led_blue.value(1)
else:
led_blue.value(0)
if temp!=last_temp or hum!=last_hum:
lcd.clear()
lcd.putstr("Temp: %3.1f C\n" %temp)
lcd.putstr("Hum: %3.1f %%" %hum)
last_temp=temp
last_hum=hum
message = ujson.dumps({
"temp": temp,
"humidity": hum,
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)