#include <ESP8266WiFi.h>
#include <time.h>
#include <FirebaseArduino.h>
#include <DHT.h>
#define DHTPIN D1 //pin connect DHT
#define DHTTYPE DHT11 //DHT11, DHT22 type of Sensor
#define WIFI_SSID "wifi_name"
#define WIFI_PASSWORD "wifi_password"
#define FIREBASE_HOST "host_firebase"
#define FIREBASE_AUTH "secret_code"
char ntp_server1[20] = "pool.ntp.org";
char ntp_server2[20] = "time.nist.gov";
char ntp_server3[20] = "time.uni.net.th";
int timezone = 7*3600;
int dst = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
Serial.println("");
configTime(timezone, dst, ntp_server1, ntp_server2, ntp_server3);
Serial.println("\nWaiting for time");
while (!time(nullptr)) {
Serial.print(".");
delay(1000);
}
Serial.println("");
dht.begin();
Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}
void loop() {
Serial.println(NowTime());
delay(1000);
float h = dht.readHumidity();
float t = dht.readTemperature();
int adc=analogRead(A0);
if (isnan(t) || isnan(h))
{
Serial.println("Error reading DHT!");
delay(1000);
return;
}
digitalWrite(D0,LOW);
Serial.print("Analog value: ");
Serial.print(adc);
Serial.print("\t");
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("\t");
Serial.print("Temp: ");
Serial.println(t);
Serial.println("...............................");
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["analog"] = adc;
root["temperature"] = t;
root["humidity"] = h;
root["time"] = NowTime();
String name = Firebase.push("logDevice01", root);
if (Firebase.failed()) {
Serial.print("pushing /logs failed:");
Serial.println(Firebase.error());
return;
}
Serial.print("pushed: /logDevice01/");
Serial.println(name);
delay(30000);
}
String NowTime() {
time_t now = time(nullptr);
struct tm* p_tm=localtime(&now);
String timeNow = "";
timeNow += String(p_tm->tm_hour);
timeNow += ":";
timeNow += String(p_tm->tm_min);
timeNow += ":";
timeNow += String(p_tm->tm_sec);
timeNow += " ";
timeNow += String(p_tm->tm_mday);
timeNow += "-";
timeNow += String(p_tm->tm_mon + 1);
timeNow += "-";
timeNow += String(p_tm->tm_year + 1900);
return timeNow;
}