//Rezki Pratama - F55120124

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

const int DHT_PIN = 15;
const char* ssid = "Wokwi-GUEST";
const char* pass = "";

WiFiClient client;

unsigned long myChannelNumber = 2;
const char* myWriteAPIKey = "YT25RBJPKMQPPR6E";
const char* server = "api.thingspeak.com";

unsigned long lastTime = 0;
unsigned long timerDelay = 30000;

int temperatureC;
int humidity;

DHTesp dhtSensor;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  dhtSensor.getPin();
  delay(10);
  WiFi.begin(ssid, pass);
  while(WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.println(".");
  }
  Serial.println("WiFI Connected!");
  Serial.println(WiFi.localIP());

  WiFi.mode(WIFI_STA);

  ThingSpeak.begin(client);
}

void loop() {
  // put your main code here, to run repeatedly:
  temperatureC = dhtSensor.getTemperature();
  Serial.println("Temperature (°C): ");
  Serial.println(temperatureC);
  humidity = dhtSensor.getHumidity();
  Serial.println("Humidity (%): ");
  Serial.println(humidity);

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

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