import network
import time
from machine import Pin, ADC, PWM
from umqtt.simple import MQTTClient
# ----- CONFIGURACIÓN WIFI -----
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASS = ''
# ----- CONFIGURACIÓN MQTT -----
AIO_USERNAME = 'Usuario'
AIO_KEY = 'Llave'
AIO_SERVER = 'io.adafruit.com'
AIO_TEMP_FEED = f'{AIO_USERNAME}/feeds/temperatura'
AIO_MAX_FEED = f'{AIO_USERNAME}/feeds/temp_maxima'
AIO_LED_FEED = f'{AIO_USERNAME}/feeds/ledrgb'
# ----- CONEXIÓN WIFI -----
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)
while not wlan.isconnected():
time.sleep(0.5)
print('Conectado a WiFi')
# ----- LED RGB (ánodo común) -----
led_r = PWM(Pin(5), freq=1000)
led_g = PWM(Pin(6), freq=1000)
led_b = PWM(Pin(7), freq=1000)
def set_rgb(r, g, b):
led_r.duty(1023 - r)
led_g.duty(1023 - g)
led_b.duty(1023 - b)
def apagar_led():
set_rgb(0, 0, 0)
# ----- SENSOR NTC -----
ntc = ADC(Pin(2))
ntc.atten(ADC.ATTN_11DB)
def leer_temperatura():
raw = ntc.read()
voltage = raw / 4095.0 * 3.3
temp = (3.3 - voltage) * 100
return round(temp, 1)
# ----- Variables de control -----
valor_maximo = 30
led_habilitado = False # Estado del botón ON/OFF
# ----- Callback MQTT -----
def callback_mqtt(topic, msg):
global valor_maximo, led_habilitado
topic_str = topic.decode()
msg_str = msg.decode().upper()
if topic_str.endswith('temp_maxima'):
try:
valor_maximo = float(msg_str)
print(f'[MQTT] Nuevo valor máximo: {valor_maximo} °C')
except:
print('[MQTT] Error en valor máximo.')
elif topic_str.endswith('ledrgb'):
led_habilitado = (msg_str == 'ON')
print(f'[MQTT] LED RGB: {"ENCENDIDO" if led_habilitado else "APAGADO"}')
# ----- MQTT -----
client = MQTTClient('esp32', AIO_SERVER, user=AIO_USERNAME, password=AIO_KEY)
client.set_callback(callback_mqtt)
def conectar_mqtt():
client.connect()
client.subscribe(AIO_MAX_FEED)
client.subscribe(AIO_LED_FEED)
print('[MQTT] Conectado y suscripto a feeds.')
# ----- MAIN LOOP -----
connect_wifi()
conectar_mqtt()
while True:
temp = leer_temperatura()
print(f'Temperatura: {temp} °C')
# Publicar temperatura
client.publish(AIO_TEMP_FEED, str(temp))
# Recibir nuevos valores
client.check_msg()
if led_habilitado:
if temp > valor_maximo:
set_rgb(255, 0, 0) # Rojo
elif temp >= 0.8 * valor_maximo:
set_rgb(255, 255, 0) # Amarillo
else:
set_rgb(0, 255, 0) # Verde
else:
apagar_led()
time.sleep(5)