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


const int DHT_PIN = 15;
const char* apikey = "0DQT03B9LY4VBXR7";
const char* ssid = "Wokwi-GUEST";
const char* pass = "";
const char* server = "api.thingspeak.com";
unsigned long channelnumber = 1;

int temperatureC;
int humidity;

DHTesp dhtSensor;

WiFiClient client;

// int led = 2;
void setup() {
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Serial.begin(115200);
  Serial.println("Hello Thingspeak");
  WiFi.begin(ssid,pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
  ThingSpeak.begin(client);
  WiFi.mode(WIFI_STA);
}

void loop() {
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  temperatureC = data.temperature;
  humidity = data.humidity;

  Serial.print("Suhu : ");
  Serial.println(temperatureC);
  Serial.print("Kelembaban : ");
  Serial.println(humidity);
  

  ThingSpeak.setField(1,temperatureC);
  ThingSpeak.setField(2,humidity);


  int x = ThingSpeak.writeFields(channelnumber,apikey);

  if(x == 200){
    Serial.println("Data berhasil dikirim ke Thingspeak");
  } else {
    Serial.println("Gagal upload data, Kode HTTP Error" + String(x));
  }
  
}