#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
#define FIREBASE_HOST "esp-mq2-67190-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "WhX8PV1vZeNcuLg9V5sBmBLdtpKsv4hVfYbw93ZP"
const char* databaseURL="https://esp-mq2-67190-default-rtdb.firebaseio.com/data.json";
#define DHT_PIN 5
#define ledred 27
#define ledblue 26
#define BUTTON 25
int button_state;
#define SCREEN_WIDTH 128 // OLED width, in pixels
#define SCREEN_HEIGHT 64 // OLED height, in pixels
DHT dht(DHT_PIN, DHT22);
void setup(){
// mở cổng giao tiếp serial để mở thông báo bên màn hình
Serial.begin(9600);
// kết nối wifi
WiFi.begin(ssid, password);
// kiểm tra wifi
while(WiFi.status() != WL_CONNECTED){
Serial.println("Connecting to wifi.........");
}
Serial.println("Connected to wifi");
// bat dau cho cam bien doc
dht.begin();
pinMode(ledred,OUTPUT);
pinMode(ledblue,OUTPUT);
}
void loop(){
int but = digitalRead(25);
// bien doc du lieu
float DoAm = dht.readHumidity();
float NhietDo = dht.readTemperature();
// kiem tra du lieu xem co doc thanh cong kh( nan = error)
// thanh cong dong goi sang goi chuoi JSON
Serial.printf("do am: %.2f%% , nhiet do: %.2f°C\n", DoAm, NhietDo);
if((NhietDo>40)&&(NhietDo<70)){
digitalWrite(ledred, HIGH);
//digitalWrite(ledblue, LOW);
}
else{
//digitalWrite(ledblue, HIGH);
digitalWrite(ledred, LOW);
}
delay(1000);
// send data to firebase = protocol HTTP
String data= String("{\"nhiet do\":") + String(NhietDo) + String(",\"do am\":") + String(DoAm) + String("}");
HTTPClient http;
http.begin(databaseURL);
http.addHeader("Content-Type", "application/json");
http.addHeader("Authorization", FIREBASE_AUTH);
int httpResponseCode = http.PUT(data);
if(httpResponseCode > 0){
Serial.print("Data sent successfully, respon code: ");
Serial.println(httpResponseCode);
}
else{
Serial.print("error sending data, response code: ");
Serial.println(httpResponseCode);
}
http.end();
delay(500);
if(httpResponseCode == 200){
String response = http.getString();
float nhietDoFirebase = response.toFloat();
}
delay(500);
}