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


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

int temperatureC;
int humidity;
int nilaiAnalog= 34;

DHTesp dhtSensor;

WiFiClient client;


void setup() {
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(nilaiAnalog, INPUT);
  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;

  int value = analogRead(nilaiAnalog);
  Serial.print("Suhu : ");
  Serial.println(temperatureC);
  Serial.print("Kelembaban : ");
  Serial.println(humidity);
  Serial.print("Nilai Analog : ");
  Serial.println(value);
  
  delay(2000);
  ThingSpeak.setField(1,temperatureC);
  ThingSpeak.setField(2,humidity);
  ThingSpeak.setField(3,value);

  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));
  }
  
}