// https://script.google.com/macros/s/AKfycbwrqGMMpcXs222FFPca6ceiciPsnK9xTrpDi8ypLL6Hlsbl_ZcHGZh4AqAJLzni769vWA/exec
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <HTTPClient.h>
// ข้อมูล WiFi
#define ssid "Wokwi-GUEST"
#define password ""
// URL ของ Google Apps Script
const char* googleScriptURL = "https://script.google.com/macros/s/AKfycbwrqGMMpcXs222FFPca6ceiciPsnK9xTrpDi8ypLL6Hlsbl_ZcHGZh4AqAJLzni769vWA/exec";
const int sensorPin = 36; // Pin ของเซ็นเซอร์
// ตั้งค่า NTP สำหรับประเทศไทย (UTC+7)
const long gmtOffset_sec = 7 * 3600; // UTC+7 = 25200 วินาที
const int daylightOffset_sec = 0; // ไม่มี Daylight Saving Time
const char* ntpServer = "th.pool.ntp.org"; // เซิร์ฟเวอร์ NTP
LiquidCrystal_I2C lcd(0x27, 16, 2); // ตั้งค่า I2C Address (0x27 สำหรับโมดูล I2C ทั่วไป)
void setup() {
Serial.begin(115200);
// ตั้งค่าจอ LCD
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Connecting WiFi");
// เชื่อมต่อ WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi");
lcd.setCursor(0, 0);
lcd.print("WiFi Connected!");
delay(2000);
// ตั้งค่าเวลา NTP
lcd.clear();
lcd.print("Syncing Time...");
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
while (!time(nullptr)) {
delay(1000);
Serial.print(".");
}
lcd.clear();
lcd.print("Time Synced!");
delay(2000);
lcd.clear();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
// อ่านค่าจากเซ็นเซอร์
int sensorValue = analogRead(sensorPin);
// แสดงค่าบนจอ LCD
lcd.setCursor(0, 0);
lcd.print("Value: ");
lcd.print(sensorValue);
// เตรียมข้อมูล JSON
String jsonData = "{";
jsonData += "\"date\":\"" + getDate() + "\",";
jsonData += "\"time\":\"" + getTime() + "\",";
jsonData += "\"sensorValue\":" + String(sensorValue);
jsonData += "}";
// ส่งข้อมูลไปยัง Google Sheets
http.begin(googleScriptURL);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(jsonData);
// แสดงผลการส่งข้อมูล
lcd.setCursor(0, 1);
if (httpResponseCode > 0) {
lcd.print("Sent!");
Serial.println("Data sent to Google Sheets.");
} else {
lcd.print("Err: ");
lcd.print(httpResponseCode);
Serial.print("Error sending data: ");
Serial.println(httpResponseCode);
}
http.end();
}
delay(300000); // ส่งข้อมูลทุก 5 นาที
}
String getDate() {
time_t now = time(nullptr);
struct tm* p_tm = localtime(&now);
char buffer[11];
sprintf(buffer, "%04d-%02d-%02d",
p_tm->tm_year + 1900, p_tm->tm_mon + 1, p_tm->tm_mday);
return String(buffer);
}
String getTime() {
time_t now = time(nullptr);
struct tm* p_tm = localtime(&now);
char buffer[9];
sprintf(buffer, "%02d:%02d:%02d",
p_tm->tm_hour, p_tm->tm_min, p_tm->tm_sec);
return String(buffer);
}