/*
* CÓDIGO CORREGIDO Y FUNCIONAL PARA BOTÓN INTELIGENTE CON DEEP SLEEP
* --------------------------------------------------------------------
* Problema Solucionado:
* - Se ha reestructurado la función setup() para comprobar correctamente la
* causa del despertar (primer arranque vs. pulsación de botón).
* - Esto evita el bucle de reinicio infinito y estabiliza la simulación.
* - Se mantiene el uso de la resistencia pull-down interna para evitar
* despertares falsos por un pin flotante.
*/
#include <esp_sleep.h>
// Define el pin del pulsador
#define BUTTON_PIN 15 // Ejemplo: pin GPIO 2
#define LED_PIN 22 //
void setup() {
// Configura el pin como entrada con resistencia pull-up interna
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// Habilita el despertar por interrupción externa en el pin 2 en estado bajo (al pulsar)
esp_sleep_enable_ext0_wakeup(GPIO_NUM_15, 0); // 0 para nivel bajo, 1 para nivel alto
digitalWrite(LED_PIN, HIGH);
Serial.println("Entrando en Deep Sleep...");
delay(1000); // Pequeño retraso antes de dormir
digitalWrite(LED_PIN, LOW);
esp_deep_sleep_start();
}
void loop() {
// Código para tu aplicación...
// Entra en modo Deep Sleep
}
/*
#include <esp_sleep.h>
#include <driver/rtc_io.h>
#include "driver/gpio.h"
// --- 1. ¡IMPORTANTE! RELLENA CON TUS CREDENCIALES DE TUYA ---
// Pega aquí el PID, UUID y AUTH_KEY que obtuviste de la plataforma Tuya.
const char* pid = "REEMPLAZA_CON_TU_PID";
const char* uuid = "REEMPLAZA_CON_TU_UUID";
const char* auth_key = "REEMPLAZA_CON_TU_AUTH_KEY";
// --- 2. CONFIGURACIÓN DEL HARDWARE ---
// Pin GPIO donde conectas el pulsador.
#define BUTTON_PIN GPIO_NUM_15
// Pin GPIO para el LED de estado
#define LED_PIN GPIO_NUM_22
// El ID de la función (Data Point) de tu botón en la plataforma Tuya. Suele ser 1.
#define DP_ID_BUTTON 1
// This function runs ONLY when the ESP32 wakes up from a button press.
// Esta función se ejecuta SÓLO cuando el ESP32 se despierta por una pulsación.
void perform_action_on_wakeup() {
Serial.println("¡Botón presionado! Realizando acción...");
// Your action code goes here. For now, we just blink the LED.
// Tu código de acción va aquí. Por ahora, solo parpadeamos el LED.
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
Serial.println("Acción completada.");
}
void setup() {
Serial.begin(115200);
delay(1000); // Wait for Serial Monitor to connect
// Configure the LED pin as an output
pinMode(LED_PIN, OUTPUT);
// Check the reason why the ESP32 woke up
// Comprueba la razón por la que el ESP32 se despertó
esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause();
if (wakeup_reason == ESP_SLEEP_WAKEUP_EXT0) {
// If it woke up from the external pin (the button), perform the action.
// Si se despertó por el pin externo (el botón), realiza la acción.
perform_action_on_wakeup();
} else {
// If it's the first boot or another type of reset, print a message.
// Si es el primer arranque u otro tipo de reseteo, imprime un mensaje.
Serial.println("Iniciando por primera vez. Configurando modo de sueño.");
}
// --- Configure Wake-up Source ---
// This part runs every time, right before going to sleep.
// Esta parte se ejecuta siempre, justo antes de ir a dormir.
// To prevent the pin from "floating" and causing false wake-ups,
// we enable the internal pull-down resistor. This holds the pin LOW.
// Para evitar que el pin "flote" y cause despertares falsos,
// activamos la resistencia pull-down interna. Esto mantiene el pin en BAJO.
rtc_gpio_pullup_dis(BUTTON_PIN);
rtc_gpio_pulldown_en(BUTTON_PIN);
// Now that the pin is stable, we can set the wake-up trigger.
// We want to wake up when the button is pressed, sending a HIGH signal.
// Ahora que el pin está estable, podemos configurar el disparador de despertar.
// Queremos despertar cuando se presione el botón, enviando una señal ALTA.
esp_sleep_enable_ext0_wakeup(BUTTON_PIN, 0); // Wake on HIGH signal
Serial.println("Entrando en modo de sueño profundo. Presiona el botón para despertar.");
Serial.flush(); // Ensure the message is sent before sleeping
// Enter deep sleep mode
// Entrar en modo de sueño profundo
esp_deep_sleep_start();
}
void loop() {
// The main loop is intentionally empty because all the logic occurs in setup()
// after waking up. This saves the maximum amount of energy.
// El loop principal está intencionadamente vacío porque toda la lógica ocurre en setup()
// después de despertar. Esto ahorra la máxima energía posible.
}
*/