#include <WiFi.h>
#include "DHT.h"
#include <HTTPClient.h>
#define DHTPIN 15 // ขา DATA ของ DHT22
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Wokwi-GUEST"; // ใส่ WiFi ของคุณถ้ารันบนบอร์ดจริง
const char* password = "";
const String scriptURL = "https://script.google.com/macros/s/AKfycbyU1r12bi_gu9YE9l26MzbVjE2k-A_xn60CtJRYk1CSsL2AtJaqwcD6vLcRP9VSfLKoyQ/exec";
unsigned long lastTime = 0;
const long interval = 60000; // 10 วินาที
void setup() {
Serial.begin(115200);
delay(100);
dht.begin();
Serial.print("Connecting to WiFi");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nWiFi connected!");
}
void loop() {
if (millis() - lastTime >= interval) {
lastTime = millis();
float h = dht.readHumidity();
float t = dht.readTemperature(); // Celsius
// ตรวจสอบค่าที่อ่านมา
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT!");
return;
}
// สร้าง query string
String url = scriptURL +
"?temp=" + String(t, 1) +
"&hum=" + String(h, 1) +
"&ts=" + String(time(nullptr)); // ส่ง epoch ได้ (หรือเว้นให้ GAS ใส่ให้)
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // ⭐ เพิ่มบรรทัดนี้
http.begin(url);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
Serial.println("Row added → Google Sheets");
} else {
Serial.printf("Error sending data (%d)\n", httpCode);
}
http.end();
}
}
}