#include <WiFi.h>
#include <HTTPClient.h>
#include "LiquidCrystal_I2C.h"
#include "DHTesp.h"
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>

const char* ssid = "Wokwi-GUEST";
const char* password = "";
String server = "https://api.thingspeak.com/update?api_key=";
String fieldsuhu = "&field1=";
String fieldkelembaban = "&field2=";
String apiKey = "JRSDIWGSARG8KFXT";

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);
DHTesp dhtSensor;
HTTPClient http;
RTC_DS1307 rtc;
void setup() {
  Serial.begin(9600);
  LCD.init();
  LCD.backlight();

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    LCD.setCursor(0, 0);LCD.print("Connecting. ");
    delay(100);
    LCD.clear();
    LCD.setCursor(0, 0);LCD.print("Connecting.. ");
    delay(100);
    LCD.clear();
    LCD.setCursor(0, 0);LCD.print("Connecting...");
    delay(100);
    LCD.clear();
    Serial.println("Connecting to WiFi...");
  }
  LCD.setCursor(0, 0);
  LCD.print("Wifi Connected");  
  Serial.println("Wifi Connected");
  delay(1000);

  dhtSensor.setup(15, DHTesp::DHT22);
  LCD.clear();
  Wire.begin();
  if (!rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
  
  if (!rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
  LCD.setCursor(0, 0);LCD.print("RTC is running");  
  delay(1000);
  LCD.clear();
}

void loop() {
  TempAndHumidity data = dhtSensor.getTempAndHumidity();
  float t = data.temperature;
  float h = data.humidity;

  if (isnan(h) || isnan(t)) 
  {
    Serial.println("Failed to read from DHT sensor!");
    LCD.setCursor(0, 0);LCD.print("Failed to read from DHT sensor!");  
    return;
  }
  else
  {
  LCD.setCursor(0, 0);LCD.print("Temp : ");
  LCD.setCursor(6, 0);LCD.print(t);
  LCD.setCursor(12, 0);LCD.print("C'");

  LCD.setCursor(0, 1);LCD.print("Humd : ");
  LCD.setCursor(6, 1);LCD.print(h);
  LCD.setCursor(12, 1);LCD.print("RH");
  }
  String url = server+apiKey+fieldsuhu+String(t)+fieldkelembaban+String(h);
  Serial.println(url);
  if(WiFi.status() == WL_CONNECTED){
    Serial.println("Start update data to thingspeak");
    http.begin(url); 
    int httpCode = http.GET();
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("HTTP GET request successful");
      Serial.println("Response:");
      Serial.println(payload);
  } else {
    Serial.println("Unexpected error");
  }
  http.end();
  }
  delay(15000);
  LCD.clear();
}




GND5VSDASCLSQWRTCDS1307+