import time
time.sleep(2)
import machine
import time
import random
# Configurar I2C
i2c = machine.I2C(0, scl=machine.Pin(22), sda=machine.Pin(21), freq=400000)
# Detectar dispositivos I2C
print("Buscando dispositivos I2C...")
devices = i2c.scan()
if len(devices) == 0:
print("¡No se encontraron dispositivos I2C!")
print("Revisa las conexiones:")
print("OLED SDA → GPIO21")
print("OLED SCL → GPIO22")
print("OLED VCC → 3V3")
print("OLED GND → GND")
else:
print("Dispositivos I2C encontrados:", [hex(device) for device in devices])
# Intentar importar SSD1306 solo si hay dispositivos I2C
if devices:
try:
from ssd1306 import SSD1306_I2C
oled = SSD1306_I2C(128, 64, i2c)
print("Pantalla OLED inicializada correctamente")
oled_connected = True
except Exception as e:
print("Error al inicializar OLED:", e)
oled_connected = False
else:
oled_connected = False
def mostrar_datos(hr, spo2, dedo_detectado):
"""Muestra los datos en la pantalla OLED"""
if oled_connected:
try:
oled.fill(0)
oled.text("MONITOR CARDIACO", 0, 0)
oled.text("----------------", 0, 10)
oled.text("Ritmo: {:.1f} bpm".format(hr), 0, 20)
oled.text("SpO2: {:.1f} %".format(spo2), 0, 35)
status = "DETECTADO" if dedo_detectado else "AUSENTE"
oled.text("Dedo: {}".format(status), 0, 50)
oled.show()
except:
print("Error al actualizar OLED")
def main():
"""Función principal"""
print("\n==================================")
print(" MONITOR CARDIACO CON ESP32")
print("==================================")
if not oled_connected:
print("MODO SOLO SERIAL - Sin pantalla")
contador = 0
while True:
contador += 1
# Simular detección de dedo (alterna cada 5 segundos)
dedo_detectado = (contador % 10) < 5
if dedo_detectado:
heart_rate = 72 + random.randint(-3, 3) + random.random()
spO2 = 98 + random.randint(-1, 1) + random.random()
mensaje_serial = "LATIDO DETECTADO"
else:
heart_rate = 0.0
spO2 = 0.0
mensaje_serial = "SIN SEÑAL"
# Mostrar datos
mostrar_datos(heart_rate, spO2, dedo_detectado)
# Mostrar en monitor serial
print("\n" + "="*40)
print("ESTADO: {}".format(mensaje_serial))
print("-"*40)
print("Ritmo cardiaco: {:.1f} bpm".format(heart_rate))
print("Nivel de Oxigeno: {:.1f} %".format(spO2))
print("Dedo: {}".format("DETECTADO" if dedo_detectado else "AUSENTE"))
print("="*40)
time.sleep(2)
# Ejecutar el programa
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nPrograma terminado")
except Exception as e:
print("Error inesperado:", e)