import time
from time import sleep
from machine import I2C, Pin, ADC
from i2c_lcd import I2cLcd
import dht
import math
from umqtt.simple import MQTTClient
import ujson
import network
# MQTT Server Parameters
MQTT_CLIENT_ID = "Wokwi-GUEST"
MQTT_BROKER = "broker.emqx.io"
MQTT_USER = "Wokwi-GUEST"
MQTT_PASSWORD = ""
MQTT_TOPIC = "exams/Asoukidis/temp/"
# WiFi connection
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!")
# MQTT server connection
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Settings of display
AddressOfLcd = 0x27
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
print("display is ready")
# Settings of sensor
sensor = dht.DHT22(Pin(2))
print("sensor is ready")
time.sleep(0.5)
print("PROGRAM START")
last_temp = ""
while True:
sensor.measure()
temp = sensor.temperature()
#hmd = sensor.humidity()
if temp != last_temp :
print("Temperature: {}°C".format(temp))
#print("Temperature: {}°C Humidity: {}%".format(temp,hmd))
lcd.move_to(0,0)
lcd.putstr("Temperature:")
lcd.move_to(7,1)
lcd.putstr(str(temp))
message = ujson.dumps({
"Asoukidis/temperature": temp,
})
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
last_temp = temp