import network
import urequests
from machine import Pin, ADC
import dht
import time
# ========== CONFIGURACIÓN ==========
# WiFi (Wokwi)
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# ThingSpeak - CAMBIAR POR TU API KEY
THINGSPEAK_API_KEY = "X6DKOCOC81SABLPO"
THINGSPEAK_URL = "http://api.thingspeak.com/update"
# Pines
dht_sensor = dht.DHT22(Pin(15))
sensor_gas = ADC(Pin(34))
sensor_gas.atten(ADC.ATTN_11DB)
sensor_gas.width(ADC.WIDTH_12BIT)
led = Pin(2, Pin.OUT)
# ========== FUNCIONES ==========
def conectar_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("🌐 Conectando WiFi...")
timeout = 10
while not wlan.isconnected() and timeout > 0:
print(f"⏳ {timeout}...")
time.sleep(1)
timeout -= 1
if wlan.isconnected():
print(f"✅ WiFi OK - IP: {wlan.ifconfig()[0]}")
return True
else:
print("❌ WiFi Error")
return False
def enviar_datos(temp, hum, gas):
try:
# Crear URL con parámetros GET (más compatible con Wokwi)
gas_volt = gas * (3.3/4095)
url = f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}&field3={gas}&field4={gas_volt:.2f}"
print("📤 Enviando a ThingSpeak...")
response = urequests.get(url)
if response.status_code == 200 and response.text.strip() != "0":
print(f"✅ Enviado - ID: {response.text.strip()}")
response.close()
return True
else:
print("❌ Error en envío")
response.close()
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
# ========== PROGRAMA PRINCIPAL ==========
print("🚀 ESP32 IoT Monitor - WiFi + ThingSpeak")
# Conectar WiFi
conectar_wifi()
# Precalentar MQ-2
print("🔥 Calentando MQ-2... (5s)")
time.sleep(5)
print("✅ Sistema listo!\n")
ultimo_envio = 0
while True:
try:
# Leer sensores
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
gas = sensor_gas.read()
# Control LED
if gas > 2000:
led.on()
estado = "🚨 ALARMA"
else:
led.off()
estado = "✅ Normal"
# Mostrar datos
print(f"🌡️ {temp:.1f}°C | 💧 {hum:.1f}% | 🔥 {gas} ADC {estado}")
# Enviar cada 15 segundos
if time.time() - ultimo_envio >= 15:
if THINGSPEAK_API_KEY != "TU_API_KEY_AQUI":
if enviar_datos(temp, hum, gas):
ultimo_envio = time.time()
else:
print("⚠️ Configurar API KEY de ThingSpeak")
ultimo_envio = time.time()
time.sleep(2)
except Exception as e:
print(f"Error: {e}")
time.sleep(2)