import time
import dht
import network
from machine import Pin
from umqtt.simple import MQTTClient
sensor = dht.DHT22(Pin(20))
# Broker settings
MQTT_BROKER="labo.g2.org"
MQTT_PORT=1883
MQTT_TEMP_TOPIC="/indobot/temp"
MQTT_HUM_TOPIC="/indobot/hum"
def connect_to_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect("Wokwi-GUEST", "")
while not sta_if.isconnected():
sleep(0.3)
print("Successfully connected to Wifi!")
while True:
try:
time.sleep(2)
connect_to_wifi()
mqtt_client = MQTTClient(
"",
MQTT_BROKER,
port=MQTT_PORT,
user="",
password="",
keepalive=0
)
mqtt_client.connect()
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
temp_f = temp * (9/5) + 32.0
client.publish(MQTT_TEMP_TOPIC, temp, qos=0)
client.publish(MQTT_HUM_TOPIC, HUM, qos=0)
print('Temperature: %3.1f C' %temp)
print('Temperature: %3.1f F' %temp_f)
print('Humidity: %3.1f %%' %hum)
except OSError as e:
print(e)
print('Failed to read sensor.')