## DHT22
## 1- Alimentación:+5V (VCC)
## 2- Datos (DATA)
## 3- No Usado (NC)
## 4- Tierra (GND)
import network
import time
from time import sleep
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
import _thread
import time
import machine
# my leds
coldLed = Pin(13, machine.Pin.OUT)
normalLed = Pin(12, machine.Pin.OUT)
warmLed = Pin(14, machine.Pin.OUT)
# turn off/on leds
def turnOnLed(led):
coldLed.off()
normalLed.off()
warmLed.off()
led.on()
# callback for the messages from mqtt broker
def on_mqtt_message(topic, msg):
print("Incoming message:", msg)
try:
print(msg)
msg = ujson.loads(msg)
except Exception as e:
print("Error:", e)
print("Connecting to WiFi...", end="")
import network
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect("Wokwi-GUEST", "")
while not wifi.isconnected():
sleep(0.5)
print(".", end="")
print("Done")
print("Connecting to MQTT...")
client = MQTTClient("esp32_00001", "broker.hivemq.com")
client.set_callback(on_mqtt_message)
client.connect()
client.subscribe("topics/esp32_00001")
print("ESP32 Connected!")
def wait_message_from_mqtt(name):
while True:
client.wait_msg() # enabling the listening mode for the messages..
_thread.start_new_thread(wait_message_from_mqtt, (1,))
sensor = dht.DHT22(Pin(15))
lastMessage = None
while True:
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if (lastMessage != sensor.temperature()):
lastMessage = sensor.temperature()
client.publish("TOPIC/mobile_00001/RQ", message)
print(message)
if(sensor.temperature() > 41):
turnOnLed(warmLed)
elif(sensor.temperature() > 15 and sensor.temperature() < 40):
turnOnLed(normalLed)
elif(sensor.temperature() < 15):
turnOnLed(coldLed)
time.sleep(1)