//Incluimos las librerias
#include "DHTesp.h"
#define LED 2     //Arranque
#define LED2 4    //Humectacion activa

#define LEDh1 14    //Humectador 1
#define LEDh2 23    //Humectador 2

boolean arranco=false;

hw_timer_t *My_timer = NULL;

void IRAM_ATTR onTimer(){
  if (arranco) {
    digitalWrite(LEDh1, !digitalRead(LEDh1));
    digitalWrite(LEDh2, digitalRead(LEDh1));
  }
}
//Decaramos el variable que almacena el pin a conectar el DHT11
int pinDHTm = 15;
int pinDHTs = 12;
int pinDHTe = 13;
//Instanciamos el DHT
DHTesp dhtm;
DHTesp dhte;
DHTesp dhts;

void setup() {
  pinMode(LED, OUTPUT);
  pinMode(LED2, OUTPUT);
  Serial.begin(115200);
  //Inicializamos el dht
  dhtm.setup(pinDHTm, DHTesp::DHT22);
  dhte.setup(pinDHTe, DHTesp::DHT22);
  dhts.setup(pinDHTs, DHTesp::DHT22);

  pinMode(LEDh2, OUTPUT);
  pinMode(LEDh1, OUTPUT);
  digitalWrite(LEDh1, HIGH);
  digitalWrite(LEDh2, LOW);

  My_timer = timerBegin(0, 800000, true);
  timerAttachInterrupt(My_timer, &onTimer, true);
  timerAlarmWrite(My_timer, 15000, true);// 26 segundos
  //timerAlarmWrite(My_timer, 1500000, true) 260 segundos
  timerAlarmEnable(My_timer);

}
void loop() {
 
  //Obtenemos el arreglo de datos (humedad y temperatura)
  TempAndHumidity datam = dhtm.getTempAndHumidity();
  TempAndHumidity datae = dhte.getTempAndHumidity();

  if(datam.temperature > datae.temperature+5){
    arranco = true;
    digitalWrite(LEDh1, HIGH);
    digitalWrite(LED, HIGH);
    TempAndHumidity datas = dhts.getTempAndHumidity();

    //Mostramos los datos de la temperatura y humedad
    Serial.println("Temperatura entrada: " + String(datae.temperature, 2) + "°C");
    Serial.println("Humedad entrada: " + String(datae.humidity, 1) + "%");
    Serial.println("Temperatura salida: " + String(datas.temperature, 2) + "°C");
    Serial.println("Humedad salida: " + String(datas.humidity, 1) + "%");
    Serial.println("Temperatura del motor: " + String(datam.temperature, 2) + "°C");
    Serial.println("---");
    Serial.println(digitalRead(LEDh2));

    if(datas.humidity - 10 > datae.humidity ){
      digitalWrite(LED2,HIGH);
    }
    else {
      digitalWrite(LED2, LOW);
    }

    delay(1000);
  }
  else {
    digitalWrite(LED, LOW);
    digitalWrite(LED2, LOW);
    digitalWrite(LEDh1, LOW);
    digitalWrite(LEDh2, LOW);
    arranco = false;
  }

}