#include <WiFi.h>
#include "ThingSpeak.h"
#include "DHTesp.h"

#define SECRET_CH_ID 2118852
#define SECRET_WRITE_APIKEY "V6V15XK82XLAB4JR"
#define WIFI_SSID "Po"
#define WIFI_PASSWORD "10181441"
#define LED 25
const int DHT_PIN = 15;
DHTesp dhtSensor;
WiFiClient client;

unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;

int D_value, A_value;
unsigned long dateMillis = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(MQ2_A, INPUT);
  pinMode(MQ2_D, INPUT);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  
  WiFi.begin(WIFI_SSID,WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ThingSpeak.begin(client);
}

void loop() {
  // put your main code here, to run repeatedly:
  A_value = analogRead(MQ2_A);
  D_value = digitalRead(MQ2_D);

  ThingSpeak.setField(1, A_value);
  ThingSpeak.setField(2, !D_value);

  if (millis() - dateMillis >20000)
  {
    Serial.printf("Analog value: %d\n", A_value);
    Serial.printf("Digital value: %d\n", D_value);
    int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
    if(x==200)
    {
      Serial.println("Channel update successful.");
    }
    else
    {
      Serial.println("Problem updating channel. HTTP error code " + String(x));
    }
  }
  if(!D_value)
  {
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
}