from machine import Pin, ADC
import ubluetooth
import time
# -----------------------------
# Configuración de pines
# -----------------------------
mq7 = ADC(Pin(34)) # MQ-7 en pin 34
mq7.atten(ADC.ATTN_11DB) # Rango hasta 3.3V
mq7.width(ADC.WIDTH_10BIT) # 10 bits -> 0 a 1023
led = Pin(2, Pin.OUT) # LED rojo
# -----------------------------
# Función para limpiar consola
# -----------------------------
def clear_console():
print("\033[2J\033[H", end="") # Secuencia de escape ANSI para limpiar consola
# -----------------------------
# Configuración de Bluetooth
# -----------------------------
class BLE():
def __init__(self, name="ESP32_CO_SENSOR"):
self.ble = ubluetooth.BLE()
self.ble.active(True)
self.ble.config(gap_name=name)
self.ble.irq(self.bt_irq)
self.register_services()
self.advertiser()
def register_services(self):
UART_UUID = ubluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
UART_TX = (ubluetooth.UUID("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"),
ubluetooth.FLAG_NOTIFY,)
UART_RX = (ubluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"),
ubluetooth.FLAG_WRITE,)
UART_SERVICE = (UART_UUID, (UART_TX, UART_RX,))
SERVICES = (UART_SERVICE,)
((self.tx, self.rx,),) = self.ble.gatts_register_services(SERVICES)
def bt_irq(self, event, data):
if event == 1:
print("✅ Dispositivo conectado por Bluetooth")
elif event == 2:
print("❌ Dispositivo desconectado")
self.advertiser()
def send(self, data):
self.ble.gatts_notify(0, self.tx, data)
def advertiser(self):
name = bytes(self.ble.config('gap_name'), 'utf-8')
adv_data = b'\x02\x01\x06' + bytes((len(name) + 1, 0x09)) + name
self.ble.gap_advertise(100, adv_data)
# -----------------------------
# Programa principal
# -----------------------------
ble = BLE()
UMBRAL = 400 # valor arbitrario, se ajusta en pruebas
start_time = time.time() # inicio del programa
last_clear = time.time() # tiempo de la última limpieza
clear_interval = 10 # limpiar consola cada 10 segundos
# Limpiar consola al inicio
clear_console()
print("=== SENSOR DE MONÓXIDO DE CARBONO (MQ-7) ===")
print("Iniciando mediciones...")
print("Valor umbral:", UMBRAL)
print("--------------------------------------------")
while True:
valor = mq7.read()
tiempo = time.time() - start_time # segundos desde inicio
# Limpiar consola periódicamente
if time.time() - last_clear > clear_interval:
clear_console()
print("=== SENSOR DE MONÓXIDO DE CARBONO (MQ-7) ===")
print("Tiempo transcurrido:", round(tiempo, 1), "s")
print("Valor umbral:", UMBRAL)
print("--------------------------------------------")
last_clear = time.time()
# Mostrar en pantalla serie
print("Tiempo:", round(tiempo,1), "s | Lectura MQ-7:", valor, "| Estado:", "ALERTA" if valor > UMBRAL else "Normal")
# LED según el umbral
if valor > UMBRAL:
led.value(1)
else:
led.value(0)
# Enviar por Bluetooth
mensaje = "Tiempo: {} s, Valor: {}\n".format(round(tiempo,1), valor)
ble.send(mensaje)
time.sleep(1) # Esperar 1 segundo entre lecturas