import machine
from machine import Pin, SoftI2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
import network
import ujson
import time
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "micropython-temphum"
MQTT_BROKER = "test.mosquitto.org"
MQTT_PORT = 1883
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "temp13378"
MQTT_TOPIC1 = "hum13378"
from machine import Pin
import dht
d = dht.DHT22(machine.Pin(15))
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
led1 = machine.Pin(14, machine.Pin.OUT)
led2 = machine.Pin(26, machine.Pin.OUT)
i2c = SoftI2C(scl=Pin(13), sda=Pin(12), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)
sensor = dht.DHT22(Pin(15))
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!")
while True:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print(temp)
print(hum)
except OSError as e:
print('Failed to read sensor.')
if 17<temp<25:
led1.off()
else:
led1.on()
if 20<hum<60:
led2.off()
else:
led2.on()
lcd.clear()
lcd.putstr(f'Temp: {temp}')
lcd.putstr(f' \nHumidity: {hum}')
prev_weathertemp = ""
prev_weatherhum = ""
messagetemp = str(d.temperature())
messagehum = str(d.humidity())
if (temp != prev_weathertemp) or (hum != prev_weatherhum):
print("Updated!")
print("Reporting to MQTT topic")
prev_weathertemp = temp
prev_weatherhum = hum
client.publish(MQTT_TOPIC, str(temp))
client.publish(MQTT_TOPIC1, str(hum))
else:
print("No change")
time.sleep(1)