#include <WiFi.h>
#include "DHTesp.h"
#include <HTTPClient.h>
#include <RTClib.h>
DHTesp dhtSensor;
RTC_DS3231 rtc;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(4, OUTPUT);
dhtSensor.setup(15, DHTesp::DHT22);
// initialise the rtc
if (!rtc.begin()) {
Serial.println("Couldn't find RTC. Dead now.");
while(1);
}
connectWiFi();
}
String displayDigit (int num) {
String number = "";
if (num < 10) {
number = "0" + String(num);
}
else {
number = String(num);
}
return number;
}
void loop() {
// get the current time and date
DateTime now = rtc.now();
String str_time = "Time%3A%20" + /*Time: */
displayDigit(now.hour()) +
"%3A" + /*:*/
displayDigit(now.minute()) +
"%3A" + /*:*/
displayDigit(now.second()) +
"%20Date%3A%20" + /* Date: */
displayDigit(now.day()) +
"-" +
displayDigit(now.month()) +
"-" +
now.year() ;
TempAndHumidity data = dhtSensor.getTempAndHumidity();
Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");
Serial.println("---");
String str_temperature = String(data.temperature, 2);
String str_humidity = String(data.humidity, 1);
doSaveData(str_time, str_temperature, str_humidity);
doLoadData();
delay(1000); // this speeds up the simulation
}
void connectWiFi() {
Serial.print("Connecting to WiFi");
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connected!");
}
void doSaveData(String str_time ,String str_temperature, String str_humidity) {
Serial.println("doSaveData!");
String id = "AKfycbyWLGF26x2uxMRALf6s1ryqMP6F_C7BEQwAP1siP3Q9AY_kVSpY9bSdwRg96nfUX9yPag";
String url = "https://script.google.com/macros/s/"+ id +
"/exec?time=" + str_time + "&sensor=溫溼度&value=" + str_temperature + "%2F" + str_humidity;
HTTPClient http;
http.begin(url);
int httpCode = http.GET();
Serial.println(httpCode);
/*if ( httpCode > 0) {
String httpCode = http.getString();
Serial.println("httpCode: " + httpCode);
}*/
http.end();
}
void doLoadData() {
Serial.println("doLoadData!");
String id = "AKfycbzh5k0rS5MGGAVP07fYMywAQMEnJgJoGgudrqKWHTxBZgQd-oHCzJKjwVo_vkOFffz7RQ";
String url = "https://script.google.com/macros/s/" + id +
"/exec?load";
HTTPClient http;
http.begin(url);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
int httpCode = http.GET();
Serial.println(httpCode);
String payload = http.getString();
Serial.println(payload);
http.end();
}