from machine import Pin, SoftI2C
from machine_i2c_lcd import I2cLcd
from utime import sleep
import dht
import network
import ujson
from hd44780 import HD44780
from umqtt.simple import MQTTClient
sensor_pin = Pin(22)
sensor = dht.DHT22(sensor_pin)
lcd = HD44780(rs=Pin(12), enable=Pin(14), d4=Pin(15), d5=Pin(0), d6=Pin(4), d7=Pin(17))
led_temp_pin = Pin(2, Pin.OUT)
led_humidity_pin = Pin(21, Pin.OUT)
lcd.init()
lcd.clear()
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "test.e-ln.ru"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "qwertyjnhbjgvcgh"
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="")
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:
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
print('Temperature: %3.1f C' % temp)
print('Humidity: %3.1f %%' % hum)
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr('Temp: %3.1f C' % temp)
lcd.move_to(0, 1)
lcd.putstr('Hum: %3.1f %%' % hum)
if temp < 17 or temp > 25:
led_temp_pin.on()
else:
led_temp_pin.off()
if hum < 40 or hum > 60:
led_humidity_pin.on()
else:
led_humidity_pin.off()
except Exception as e:
print('Error reading from sensor:', e)
sleep(1)