import machine
from machine import ADC, Pin
import time
from umqtt.simple import MQTTClient
import network
import math
ssid = 'Wokwi-GUEST'
wifipassword = ''
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'tai2204'
password = 'aio_HIdv83Idid3iRj9D9EAIfO2YvC94'
client_id = "esp32_control_temperatura"
topic_1 = 'tai2204/feeds/ventilador'
topic_2 = 'tai2204/feeds/temperatura'
pin_simulador_lm35 = ADC(Pin(34))
pin_simulador_lm35.atten(ADC.ATTN_11DB) # Lee rango completo de 0 a 3.3V
pin_ventilador = Pin(2, Pin.OUT)
UMBRAL_TEMPERATURA = 30.0
estado_ventilador_ant = 0
def funcion_callback(topic, msg):
global estado_ventilador_ant
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print("\nMensaje recibido en " + topicrec + ": " + dato)
if topicrec == topic_1:
if "OFF" in dato:
pin_ventilador.value(0)
estado_ventilador_ant = 0
elif "ON" in dato:
pin_ventilador.value(1)
estado_ventilador_ant = 1
def conectar_wifi():
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
time.sleep(1)
print("Conectando")
sta_if.connect(ssid, wifipassword)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("\nConectado a red wifi")
#convertidor de NTC a LM35, para medir temperatura
def leer_temperatura_ntc():
lectura = pin_simulador_lm35.read()
# Evitamos división por cero si la lectura es máxima
if lectura >= 4095:
lectura = 4094
if lectura <= 0:
lectura = 1
# Algoritmo de Steinhart-Hart para el NTC de 10k de Wokwi
resistencia = 10000.0 / ((4095.0 / lectura) - 1.0)
# Cálculo matemático para pasar a Kelvin y luego a Celsius
temperatura_k = 1.0 / (1.0 / 298.15 + (1.0 / 3950.0) * math.log(resistencia / 10000.0))
temperatura_c = temperatura_k - 273.15
return temperatura_c
# Inicio
conectar_wifi()
print("Conectando al broker MQTT")
try:
conexionMQTT = MQTTClient(client_id, mqtt_server, user=user, password=password, port=int(port))
conexionMQTT.set_callback(funcion_callback)
conexionMQTT.connect()
conexionMQTT.subscribe(topic_1)
print("Conectado con Broker MQTT")
except OSError as e:
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
while True:
try:
conexionMQTT.check_msg()
temp_actual = leer_temperatura_ntc()
print(f"Temperatura: {temp_actual:.1f} °C")
conexionMQTT.publish(topic_2, f"{temp_actual:.1f}")
# Lógica de control automática
if temp_actual >= UMBRAL_TEMPERATURA:
nuevo_estado = 1
else:
nuevo_estado = 0
if nuevo_estado != estado_ventilador_ant:
pin_ventilador.value(nuevo_estado)
msg_vent = "ON" if nuevo_estado == 1 else "OFF"
conexionMQTT.publish(topic_1, msg_vent)
print(f"Ventilador modificado automáticamente: {msg_vent}")
estado_ventilador_ant = nuevo_estado
time.sleep(3)
except OSError as e:
print("Error en la conexión, reiniciando...")
time.sleep(5)
machine.reset()