#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* FIREBASE_HOST = "https://esp32-35a4e-default-rtdb.firebaseio.com/";
const char* FIREBASE_AUTH = " ceH0OcpT2HmGY8OmQtQH4E6u8bbiUsX6ALT13biR";
#define DHT_PIN 15
#define LAMP_PIN 27
DHT dht(DHT_PIN, DHT22);
bool lampStatus = false; // Initialize lamp status as false (OFF)
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
Serial.println("Connecting to wifi.........");
delay(500);
}
Serial.println("Connected to wifi");
dht.begin();
pinMode(LAMP_PIN, OUTPUT);
}
void loop() {
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
int den = lampStatus;
Serial.printf("Humidity: %.2f%%, Temperature: %.2fC\n,Den: %.2fC\n", humidity, temperature, den);
// Create JSON data for the sensor readings
String sensorData = String("{\"nhiet do\":") + String(temperature) + String(",\"do am\":") + String(humidity) + String("}");
// Send sensor data to Firebase
HTTPClient http;
String url = String(FIREBASE_HOST) + ".json"; // Append .json to Firebase host URL
http.begin(url);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", FIREBASE_AUTH);
int httpResponseCode = http.PUT(sensorData);
// Handle response from Firebase
if (httpResponseCode == 200) {
Serial.println("----------------------------------");
Serial.print("Data sent successfully, response code: ");
Serial.println(httpResponseCode);
Serial.println("----------------------------------");
} else {
Serial.print("Error sending data, response code: ");
Serial.println(httpResponseCode);
}
// Control lamp from Firebase
int httpgetData = http.GET();
if (httpgetData == 200) {
String payload = http.getString();
Serial.print("Firebase response: ");
if (payload.indexOf("\"Den\":\"1\"") != -1) {
// Lamp should be ON
if (!lampStatus) {
digitalWrite(LAMP_PIN, HIGH);
Serial.println("Lamp is ON");
lampStatus = true; // Update lamp status
}
} else {
// Lamp should be OFF
if (lampStatus) {
digitalWrite(LAMP_PIN, LOW);
Serial.println("Lamp is OFF");
lampStatus = false; // Update lamp status
}
}
} else {
Serial.print("Error getting data from Firebase, HTTP error code: ");
Serial.println(httpResponseCode);
}
http.end();
delay(5000); // Delay between readings
}