// #include <U8g2lib.h>
// #include <Wire.h>
// #include "DHT.h"

// // Pines
// #define DHTPIN 4
// #define DHTTYPE DHT22
// #define LDR_PIN 34

// // Umbrales para clasificar el momento del día
// #define DIA_UMBRAL 1500
// #define TARDE_UMBRAL 3000

// // Inicializar pantalla SH1107 (Grove 128x128)
// U8G2_SH1107_SEEED_128X128_F_HW_I2C display(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

// // Inicializar sensor DHT
// DHT dht(DHTPIN, DHTTYPE);

// void setup() {
//   Serial.begin(115200);

//   pinMode(LDR_PIN, INPUT);
//   dht.begin();
//   display.begin();
//   display.setFont(u8g2_font_ncenB08_tr);

//   mostrarMensaje("Iniciando sensores...");
//   delay(1500);
// }

// void loop() {
//   float temperatura = dht.readTemperature();
//   float humedad = dht.readHumidity();
//   int luz = analogRead(LDR_PIN);

//   if (isnan(temperatura) || isnan(humedad)) {
//     Serial.println("Error al leer DHT22");
//     mostrarMensaje("Error en sensor\nDHT22");
//     delay(2000);
//     return;
//   }

//   // Clasificar el momento del día según la luz
//   String momentoDia;
//   if (luz < DIA_UMBRAL) {
//     momentoDia = "DIA";
//   } else if (luz < TARDE_UMBRAL) {
//     momentoDia = "TARDE";
//   } else {
//     momentoDia = "NOCHE";
//   }

//   // Mostrar por serial (opcional)
//   Serial.printf("Temp: %.1f °C, Humedad: %.1f %%\n", temperatura, humedad);
//   Serial.printf("Luz: %d => %s\n", luz, momentoDia.c_str());

//   // Mostrar en pantalla
//   display.clearBuffer();
//   display.setCursor(0, 12);  display.print("Temp: ");     display.print(temperatura); display.print(" C");
//   display.setCursor(0, 26);  display.print("Humedad: ");  display.print(humedad);    display.print(" %");
//   display.setCursor(0, 40);  display.print("Luz: ");      display.print(luz);
//   display.setCursor(0, 54);  display.print("Momento: ");  display.print(momentoDia);
//   display.sendBuffer();

//   delay(1000); // refresco cada segundo
// }

// // Función para mostrar mensajes en pantalla centrados
// void mostrarMensaje(const char* mensaje) {
//   display.clearBuffer();
//   int y = 40;
//   const char* ptr = mensaje;

//   while (*ptr) {
//     char linea[32];
//     int i = 0;
//     while (*ptr && *ptr != '\n' && i < 31) {
//       linea[i++] = *ptr++;
//     }
//     linea[i] = '\0';

//     display.setCursor(10, y);
//     display.print(linea);
//     y += 14;

//     if (*ptr == '\n') ptr++;
//   }

//   display.sendBuffer();
// }


#include <U8g2lib.h>
#include <Wire.h>
#include "DHT.h"

// Pines
#define BOTON_INICIO_PIN 2     // botón para encender
#define BOTON_APAGADO_PIN 16   // botón para apagar
#define DHTPIN 4               // pin del DHT22
#define DHTTYPE DHT22
#define LDR_PIN 34             // pin de lectura LDR

// Umbrales de luz
#define DIA_UMBRAL 1500
#define TARDE_UMBRAL 3000

// Pantalla SH1107 Grove 128x128
U8G2_SH1107_SEEED_128X128_F_HW_I2C display(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);

// Sensor DHT
DHT dht(DHTPIN, DHTTYPE);

// Estado del sistema
bool sistemaIniciado = false;
bool estadoAnteriorInicio = HIGH;
bool estadoAnteriorApagado = HIGH;

void setup() {
  Serial.begin(115200);

  pinMode(BOTON_INICIO_PIN, INPUT_PULLUP);
  pinMode(BOTON_APAGADO_PIN, INPUT_PULLUP);
  pinMode(LDR_PIN, INPUT);

  dht.begin();
  display.begin();
  display.setFont(u8g2_font_ncenB08_tr);

  mostrarMensaje("Presiona INICIO\npara comenzar");
}

void loop() {
  bool estadoActualInicio = digitalRead(BOTON_INICIO_PIN);
  bool estadoActualApagado = digitalRead(BOTON_APAGADO_PIN);

  // Encender sistema
  if (estadoAnteriorInicio == HIGH && estadoActualInicio == LOW) {
    delay(50);  // antirrebote
    sistemaIniciado = true;
    Serial.println("Sistema iniciado");
    mostrarMensaje("Sistema iniciado");
    delay(1000);
  }

  // Apagar sistema
  if (estadoAnteriorApagado == HIGH && estadoActualApagado == LOW) {
    delay(50);  // antirrebote
    sistemaIniciado = false;
    Serial.println("Sistema apagado");
    mostrarMensaje("Sistema apagado\nPresiona INICIO");
    delay(1000);
  }

  estadoAnteriorInicio = estadoActualInicio;
  estadoAnteriorApagado = estadoActualApagado;

  // Mostrar datos solo si está encendido
  if (sistemaIniciado) {
    float temperatura = dht.readTemperature();
    float humedad = dht.readHumidity();
    int luz = analogRead(LDR_PIN);

    if (isnan(temperatura) || isnan(humedad)) {
      Serial.println("Error al leer DHT22");
      mostrarMensaje("Error en sensor\nDHT22");
      delay(2000);
      return;
    }

    String momentoDia;
    if (luz < DIA_UMBRAL) {
      momentoDia = "DIA";
    } else if (luz < TARDE_UMBRAL) {
      momentoDia = "TARDE";
    } else {
      momentoDia = "NOCHE";
    }

    Serial.printf("Temp: %.1f °C, Humedad: %.1f %%\n", temperatura, humedad);
    Serial.printf("Luz: %d => %s\n", luz, momentoDia.c_str());

    display.clearBuffer();
    display.setCursor(0, 12);  display.print("Temp: ");     display.print(temperatura); display.print(" C");
    display.setCursor(0, 26);  display.print("Humedad: ");  display.print(humedad);    display.print(" %");
    display.setCursor(0, 40);  display.print("Luz: ");      display.print(luz);
    display.setCursor(0, 54);  display.print("Momento: ");  display.print(momentoDia);
    display.sendBuffer();
  }

  delay(500); // menor delay para mejor respuesta
}

// Mostrar mensajes simples
void mostrarMensaje(const char* mensaje) {
  display.clearBuffer();
  int y = 40;
  const char* ptr = mensaje;

  while (*ptr) {
    char linea[32];
    int i = 0;
    while (*ptr && *ptr != '\n' && i < 31) {
      linea[i++] = *ptr++;
    }
    linea[i] = '\0';

    display.setCursor(10, y);
    display.print(linea);
    y += 14;

    if (*ptr == '\n') ptr++;
  }

  display.sendBuffer();
}

$abcdeabcde151015202530354045505560fghijfghij