#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

const char* ssid = "Wokwi-GUEST"; // isi dengan "Wokwi-GUEST"
const char* password = "";  // ngga perlu password buat wokwi

// Setelan Thingspeak
const char* server = "api.thingspeak.com";
String apiKey = "4VXPM3QDCO1YX5O2";  // Ganti dengan WRITE API KEY channel kamu

#define DHTPIN 4      
#define DHTTYPE DHT22 

DHT dht(DHTPIN, DHTTYPE);

LiquidCrystal_I2C lcd(0x27, 16, 2); 

void setup() {
  Serial.begin(115200);
  dht.begin();
  
  lcd.begin(16, 2);
  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);

  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("\nConnected to WiFi");
  lcd.setCursor(0, 1);
  lcd.print("nyambung");
  delay(2000);
  lcd.clear();
}

void loop() {
  delay(2000);

  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Failed to read from DHT sensor!");
    return;
  }

  
  int hRounded = round(h);
  int tRounded = round(t);

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Nama :Rafi");
  lcd.setCursor(0, 1);
  lcd.print("Suhu:");
  lcd.print(tRounded);
  lcd.print("C");
  lcd.print(" Hum:");
  lcd.print(hRounded);
  lcd.print("%");

  // Kirim data ke ThingSpeak
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;

    String url = String("http://") + server + "/update?api_key=" + apiKey + "&field1=" + String(tRounded) + "&field2=" + String(hRounded);

    http.begin(url.c_str());
    int httpCode = http.GET();

    if (httpCode > 0) {
      Serial.printf("Kode HTTP GET: %d\n", httpCode);
      if (httpCode == HTTP_CODE_OK) {
        String payload = http.getString();
        Serial.println("Payload: " + payload);
      }
    } else {
      Serial.printf("HTTP GET failed, error: %s\n", http.errorToString(httpCode).c_str());
    }

    http.end();
  }
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND
lcd1:GND
lcd1:VCC
lcd1:SDA
lcd1:SCL