import network
import time
from machine import Pin, PWM
from utime import sleep, sleep_ms
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT Server Parameters
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "ACTIVIDAD_1"
# Configuración del sensor DHT22 y SERVO
sensor_dht = dht.DHT22(Pin(18))
servo = PWM (Pin(4), freq =50)
# Conexión a la red Wi-Fi
print("Conectando a la red 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(" ¡Conectado!")
# Conexión al servidor MQTT
print("Conectando al servidor MQTT... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("¡Conectado!")
# Variables para comparar con las lecturas anteriores
prev_weather = ""
while True:
for i in range (100, 8000):
servo.duty_u16(i)
sleep_ms(1)
# Medir condiciones meteorológicas con el sensor DHT22
sensor_dht.measure()
temperature = sensor_dht.temperature()
humidity = sensor_dht.humidity()
message = ujson.dumps({
"temp": temperature,
"humedad": humidity,
})
if message != prev_weather :
print("Reporte {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
else:
print (message)
time.sleep_ms(1)