#
# Inicializacion de los parametros del Servomotor
import machine
import time
p23=machine.Pin(23,machine.Pin.OUT)
servo1=machine.PWM(p23)
print('servo1')
servo1.freq(50)
servo1.duty(0)
# Inicializacion de los parametros del DHT22
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# Inicializacion de los parametros del MQTT Server
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "wokwi-weather"
sensor = dht.DHT22(Pin(15))
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!")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
print("Connected!")
# Asignacion de valores y mapeo de los mismos para el Servomotor
def map(x, in_min, in_max, out_min, out_max):
return int((x-in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
def servo(pin,angle):
pin.duty(map(angle,0,180,20,120))
ang = 45
servo(servo1,ang)
# Ciclo infinito
# Cuando el DHT22 registre una temperatura mayor a 75 grados una valvula de enfriamiento
# se abrira mediante el Servomotor. Cuando la lectura de temperatura sea menor de 50
# grados el Servomotor cerrara la valvula de enfriamiento.
prev_weather = ""
while True:
print("Measuring weather conditions... ", end="")
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity(),
})
if message != prev_weather:
time.sleep(1)
print("Updated!")
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
prev_weather = message
if sensor.temperature() > 75:
print('System Overheated. Opening cooling valve.')
ang = 135
servo(servo1,ang)
if sensor.temperature() <= 50:
print('System Temperature Normal. Closing cooling valve.')
ang = 45
servo(servo1,ang)
else:
print("No change")
time.sleep(1)