#Sistema de alarma de prevencion contra incendio. El sistema funciona con sensores MQ2
# que al detectar una cierta concentracion de humo en el ambiente enciende una alarma y un led que hay en el lugar
#enviando tambien un mensaje al usuario en que ambiente se detecto el humo, y el usuario puede controlar la alarma
# para encederla o apagarla.
#MATERIA: Fundamentos de Sistemas Embebidos
#UNIVERSIDAD: Univerdad Nacional de La Matanza
#INTEGRANTES: Villafañe Lautaro daniel,CABA Tobias Fernando, Segovia Dante ian
import time
import machine
import network
from machine import Pin, PWM, ADC
from umqtt.simple import MQTTClient
# --- CONFIG WIFI ---
ssid = 'Wokwi-GUEST'
wifipassword = ''
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'lautyVilla'
password = 'aio_QGBf01UszAVjLpl1URenN7L7oFzP' # <- Asegurate que este es tu AIO Key real
client_id = 'MiAlarma'
# --- TOPICOS ---
topic_MQ2 = 'lautyVilla/feeds/sensorcocina'
topic2_MQ2 = 'lautyVilla/feeds/sensorhabitacion'
topic3_MQ2 = 'lautyVilla/feeds/sensorliving'
topic_humo_x_usuario = 'lautyVilla/feeds/umbral-usuario'
topic_ALARMA_ESTADO = 'lautyVilla/feeds/buzzeralarma'
topic_ALARMA_CONTROL = 'lautyVilla/feeds/controlremoto'
UMBRAL_HUMO = None
control_remoto_activo = True
ultimo_estado_publicado = "INICIO"
# --- HARDWARE ---
mq2_1 = ADC(Pin(33))
mq2_2 = ADC(Pin(34))
mq2_3 = ADC(Pin(35))
mq2_1.atten(ADC.ATTN_11DB)
mq2_2.atten(ADC.ATTN_11DB)
mq2_3.atten(ADC.ATTN_11DB)
LED_COCINA = Pin(25, Pin.OUT)
LED_HABITACION = Pin(26, Pin.OUT)
LED_LIVIN = Pin(27, Pin.OUT)
SIRENA = PWM(Pin(5), freq=1200, duty=0)
# --- CALLBACK MQTT ---
def callback_alarma(topic, msg):
global UMBRAL_HUMO, control_remoto_activo, ultimo_estado_publicado
top = topic.decode()
data = msg.decode()
print("TOPIC:", top, "VALOR:", data)
# CONTROL REMOTO
if top == topic_ALARMA_CONTROL:
if data.upper() == "ON":
control_remoto_activo = True
print("Control remoto ACTIVADO")
elif data.upper() == "OFF":
control_remoto_activo = False
SIRENA.duty(0)
print("Control remoto DESACTIVADO")
# UMBRAL DE HUMO
if top == topic_humo_x_usuario:
try:
UMBRAL_HUMO = int(data)
print("Nuevo UMBRAL:", UMBRAL_HUMO)
except:
print("Umbral inválido")
# --- CONEXION WIFI ---
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect(ssid, wifipassword)
while not sta.isconnected():
print(".", end="")
time.sleep(0.2)
print("\nWiFi OK")
# --- CONEXION MQTT ---
client = MQTTClient(client_id, mqtt_server, user=user, password=password, port=port)
client.set_callback(callback_alarma)
client.connect()
client.subscribe(topic_humo_x_usuario.encode())
client.subscribe(topic_ALARMA_CONTROL.encode())
print("MQTT OK — Monitoreando MQ2...")
def reconnect_mqtt(): #solo si falla la conexion al momento de enviar muchos mensajes
global client
print("Reconectando MQTT...")
try:
client.connect()
client.subscribe(topic_humo_x_usuario.encode())
client.subscribe(topic_ALARMA_CONTROL.encode())
print("MQTT Reconectado")
except:
print("Fallo reconexión, reintentando en 2s...")
time.sleep(2)
reconnect_mqtt()
# --- LOOP ---
while True:
try:
client.check_msg()
except OSError:
reconnect_mqtt() #por si falla client.check_msg
continue
if UMBRAL_HUMO is None:
time.sleep(0.5)
continue
# --- LECTURAS REALES DE ADC (0–4095) ---
adc1 = mq2_1.read()
adc2 = mq2_2.read()
adc3 = mq2_3.read()
# APAGAR TODOS LOS LEDS
LED_COCINA.off()
LED_HABITACION.off()
LED_LIVIN.off()
estado = "Sin humo"
# SENSOR COCINA
if adc1 >= UMBRAL_HUMO:
LED_COCINA.on()
estado = "Humo en Cocina"
# SENSOR HABITACION
if adc2 >= UMBRAL_HUMO:
LED_HABITACION.on()
estado = "Humo en Habitación"
# SENSOR LIVING
if adc3 >= UMBRAL_HUMO:
LED_LIVIN.on()
estado = "Humo en Living"
# PUBLICAR SOLO SI CAMBIA EL ESTADO
if estado != ultimo_estado_publicado:
print("CAMBIO:", estado)
client.publish(topic_ALARMA_ESTADO.encode(), estado)
ultimo_estado_publicado = estado
# SIRENA SOLO SI HAY HUMO EN CUALQUIER SENSOR
if estado != "Sin humo" and control_remoto_activo:
SIRENA.duty(400)
else:
SIRENA.duty(0)
time.sleep(0.3)