#include <WiFi.h>
#include "DHT.h"
#include "ThingSpeak.h"
const int DHT_PIN = 15;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASS = "";
//thingspeak details
const int myChannelNumber = 2385325;
const char* write_API_Key = "3CC6KN2HDISLFAPC";
const char* server = "api.thingspeak.com";
float hum=10;
float temp=10;
//DHT22 details
#define DHTTYPE DHT22   
DHT dht(DHT_PIN, DHTTYPE);
WiFiClient client;

void setup() {
  Serial.begin(115200);
  dht.begin();
  WiFi.begin(WIFI_NAME, WIFI_PASS);
  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() {
  //TempAndHumidity  data = dhtSensor.getTempAndHumidity();
   hum = dht.readHumidity();
   temp = dht.readTemperature();  
  if (isnan(hum) || isnan(temp)  ){
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }
  //
  sendDataToThingSpeak();

  delay(16000);
}
void sendDataToThingSpeak(){
  ThingSpeak.setField(1,temp);
    delay(500);
  ThingSpeak.setField(2,hum);
  
  
  int writeResult = ThingSpeak.writeFields(myChannelNumber,write_API_Key);
  
  Serial.println("Temp: " + String(temp, 2) + "°C");
  Serial.println("Humidity: " + String(hum, 1) + "%");
  
  if(writeResult == 200){
    Serial.println("Data pushed successfull");
  }else{
    Serial.println("Push error" + String(writeResult));
  }
  Serial.println("---");
}