void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
}
void loop() {
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# Parámetros del servidor MQTT
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
# Configuración de pines
DHT_PIN = 15
TEMP_LED_PIN = 14
HUMID_LED_PIN = 13
BUTTON_TEMP_PIN = 26
BUTTON_HUMID_PIN = 27
# Inicialización de componentes
sensor = dht.DHT22(Pin(DHT_PIN))
temp_led = Pin(TEMP_LED_PIN, Pin.OUT)
humid_led = Pin(HUMID_LED_PIN, Pin.OUT)
button_temp = Pin(BUTTON_TEMP_PIN, Pin.IN, Pin.PULL_UP)
button_humid = Pin(BUTTON_HUMID_PIN, Pin.IN, Pin.PULL_UP)
# Conexión a WiFi
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!")
# Conexión a servidor MQTT
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()
temperature = sensor.temperature()
humidity = sensor.humidity()
# Verificación de umbrales y control de LEDs
if temperature > 45:
temp_led.on()
else:
temp_led.off()
if humidity < 25 or humidity > 60:
humid_led.on()
else:
humid_led.off()
# Control de LEDs con botones
if button_temp.value() == 0: # Botón presionado
temp_led.off()
if button_humid.value() == 0: # Botón presionado
humid_led.off()
# Preparación y envío del mensaje MQTT
message = ujson.dumps({
"temp": temperature,
"humidity": 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)
delay(10); // this speeds up the simulation
}