// Incluimos librería
#include <WiFi.h>
#include "DHTesp.h"
#include "ThingSpeak.h"

// Definimos el pin digital donde se conecta el sensor
#define DHTPIN 14

//CAMBIAR A DHT11 !!!!!!!!!!!!!!!!!!!!!!!!!
#define DHTTYPE DHT22
DHTesp dht;

const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber = 2342052;
const char* myWriteApiKey = "LLBIZUAXYJ8M4AGS";
const char* myReadApiKey = "B5WTHFN4V3TUC8C8";
const char* server = "http://api.thingspeak.com/update";
int statusCode = 0;

WiFiClient client;

#define LED_PIN 25
int enable_led = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(LED_PIN, OUTPUT);
  dht.setup(DHTPIN, DHTesp::DHTTYPE);

  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.println("Wifi not connected");
  }
  Serial.println("Wifi connected !");
  Serial.println("Local IP: " + String(WiFi.localIP()));
  WiFi.mode(WIFI_STA);
  ThingSpeak.begin(client);

}

void loop() {
    statusCode = ThingSpeak.readMultipleFields(myChannelNumber, myReadApiKey) ;
    
    if(statusCode == 200)
    {
      // Fetch the stored data

      int LED = ThingSpeak.getFieldAsInt(3); // Field 1
      Serial.println(LED);  
      if(LED==1)
      {
        enable_led = 1;
      }
     if(LED==0)
      {
        enable_led = 0;
      }
    }
    else{
      Serial.println("Problem reading channel. HTTP error code " + String(statusCode)); 
    }

  TempAndHumidity  data = dht.getTempAndHumidity();
  ThingSpeak.setField(1,data.temperature);
  ThingSpeak.setField(2,data.humidity);
  if (data.temperature > 20 && enable_led == 1) {
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
  // Leemos la humedad relativa
  float h = data.humidity;
  // Leemos la temperatura en grados centígrados (por defecto)
  float t = data.temperature;
  int x = ThingSpeak.writeFields(myChannelNumber, myWriteApiKey);
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
  delay(3000);
 }
$abcdeabcde151015202530354045505560fghijfghij