#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define FIREBASE_HOST "sonia-melani-default-rtdb.asia-southeast1.firebasedatabase.app"
// Pin
#define DHTPIN 15
#define DHTTYPE DHT22
#define LDR 34
#define BUZZER 12
#define LED_LDR 13
#define LED_FB 14
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
unsigned long sinkron = 0;
void setup() {
Serial.begin(115200);
pinMode(BUZZER, OUTPUT);
pinMode(LED_LDR, OUTPUT);
pinMode(LED_FB, OUTPUT);
dht.begin();
lcd.init();
lcd.backlight();
// Koneksi WiFi
Serial.print("Konek WiFi");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Terhubung!");
}
// ================== FIREBASE ==================
void sendToFirebase(String path, String value) {
if (WiFi.status() != WL_CONNECTED) return;
HTTPClient http;
String url = "https://" + String(FIREBASE_HOST) + "/" + path + ".json";
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.PUT(value);
http.end();
}
int getFromFirebase(String path) {
if (WiFi.status() != WL_CONNECTED) return 0;
HTTPClient http;
String url = "https://" + String(FIREBASE_HOST) + "/" + path + ".json";
http.begin(url);
int code = http.GET();
int result = 0;
if (code > 0) {
String payload = http.getString();
result = payload.toInt();
}
http.end();
return result;
}
// ================== LOOP ==================
void loop() {
float temp = dht.readTemperature();
int ldrRaw = analogRead(LDR);
float lux = map(ldrRaw, 4063, 0, 0, 1000);
if (isnan(temp)) {
Serial.println("Gagal baca DHT!");
return;
}
// ===== BUZZER (jika suhu panas) =====
bool buzzerStatus = (temp > 40.0);
digitalWrite(BUZZER, buzzerStatus ? HIGH : LOW);
// ===== LAMPU SELALU ON =====
bool lampuStatus = true;
digitalWrite(LED_LDR, HIGH);
// ================= LCD =================
lcd.clear();
// Baris 1: Suhu
lcd.setCursor(0, 0);
lcd.print("Suhu:");
lcd.print(temp, 1);
lcd.print(" C");
// Baris 2: Lampu
lcd.setCursor(0, 1);
lcd.print("Lampu:");
lcd.print("ON");
// ================= FIREBASE =================
if (millis() - sinkron > 5000) {
sinkron = millis();
sendToFirebase("data/suhu", String(temp));
sendToFirebase("data/lux", String(lux));
sendToFirebase("status/buzzer", buzzerStatus ? "true" : "false");
int ledRemote = getFromFirebase("control/led_remote");
digitalWrite(LED_FB, ledRemote == 1 ? HIGH : LOW);
}
delay(500);
}