// Learn about the ESP32 WiFi simulation in
// https://docs.wokwi.com/guides/esp32-wifi

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

//Deklarasi untuk ThingSpeak
const char* ssid = "Wokwi-GUEST" ;
const char* pass = "";

WiFiClient client;
unsigned long myChannelNumber = 2010508;
const char* ReadAPIKey = "9ETDH41X2T4M621N";
const char* server = "api.thingspeak.com";

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);

const int DHT_PIN = 23;

DHTesp dhtSensor;

void setup() {
  Serial.begin(115200);

  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  LCD.init();
  LCD.backlight();
  LCD.setCursor(0, 0);
  LCD.print("Connecting to ");
  LCD.setCursor(0, 1);
  LCD.print("WiFi ");

 WiFi.begin(ssid, pass);
  ThingSpeak.begin(client);

  while(WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.println(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

}

void loop() {
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  LCD.setCursor(0, 0);
  LCD.println("Temp: " + String(data.temperature, 2) + " C");
  LCD.setCursor(0, 1);
  LCD.println("Humidity: " + String(data.humidity, 1) + "%");
  delay(1000);


  ThingSpeak.setField(1, data.temperature);
  ThingSpeak.setField(2, data.humidity);

  int x = ThingSpeak.writeFields(myChannelNumber, ReadAPIKey);
  vTaskDelay(120000/ portTICK_PERIOD_MS); // delay 120 sekon = 2 menit 
    
}