#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
// --- Network Configuration ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// --- Firebase Configuration ---
String firebaseHost = "https://dash--board-iot-default-rtdb.asia-southeast1.firebasedatabase.app/";
// --- Hardware Pins ---
#define LED_PIN 2
#define DHT_PIN 4
#define DHTTYPE DHT11
DHT dht(DHT_PIN, DHTTYPE);
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
dht.begin();
// --- Connect to Wi-Fi ---
Serial.print("Connecting to Wi-Fi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected successfully!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// --- 1. UPLOAD DATA (Nhiệt độ & Độ ẩm) ---
float t = dht.readTemperature();
float h = dht.readHumidity();
if (!isnan(t) && !isnan(h)) {
String jsonData = "{\"nhietdo\":" + String(t, 1) +
",\"doam\":" + String(h, 1) + "}";
http.begin(firebaseHost + "/cambien.json");
http.addHeader("Content-Type", "application/json");
int patchCode = http.PATCH(jsonData);
if (patchCode > 0) Serial.println("Upload Success!");
else Serial.println("Upload Failed: " + String(patchCode));
http.end();
}
// --- 2. DOWNLOAD DATA (Điều khiển LED) ---
http.begin(firebaseHost + "/dieukhien.json");
int getCode = http.GET();
if (getCode == 200) {
String payload = http.getString();
Serial.println("Received: " + payload);
// Logic kiểm tra chuỗi đơn giản
if (payload.indexOf("\"button\":\"ON\"") != -1) {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED is ON");
} else {
digitalWrite(LED_PIN, LOW);
Serial.println("LED is OFF");
}
}
http.end();
}
delay(5000); // Đợi 5 giây mỗi lần lặp
}