#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#include "time.h"
#define DHTPIN 5 // Pin ที่ต่อกับ DHT22
#define DHTTYPE DHT22 // ชนิดของเซ็นเซอร์ DHT22
const char* LINE_TOKEN = "N8undfjQ1lhCDROVgH8flaMtJWjN8uOUYrsFnsMax60"; // ใส่ Token ของ LINE Notify ที่นี่
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "Wokwi-GUEST"; // ใส่ SSID ของ WiFi ที่นี่
const char* password = ""; // ใส่รหัสผ่านของ WiFi ที่นี่
// ตั้งค่า Time Zone ให้ตรงกับประเทศไทย (UTC+7)
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 7 * 3600;
const int daylightOffset_sec = 0;
void setup() {
Serial.begin(115200);
dht.begin();
// เชื่อมต่อ WiFi
WiFi.begin("Wokwi-GUEST", "",6);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// ตั้งค่าเวลา
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}
void loop() {
// อ่านค่าอุณหภูมิและความชื้นจาก DHT22
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// แสดงข้อมูลอุณหภูมิและความชื้นใน Serial Monitor ทุก ๆ 10 วินาที
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
delay(10000);
// เช็คเงื่อนไขและส่งแจ้งเตือน
time_t now;
struct tm timeinfo;
time(&now);
localtime_r(&now, &timeinfo);
// ถ้าอุณหภูมิ < 26 แจ้งเตือนตามเวลาที่กำหนด
if (temperature < 26) {
if ((timeinfo.tm_hour == 9 || timeinfo.tm_hour == 12 || timeinfo.tm_hour == 15 ||
timeinfo.tm_hour == 18 || timeinfo.tm_hour == 21 || timeinfo.tm_hour == 0) &&
timeinfo.tm_min == 0) {
sendLineNotify("อุณหภูมิปกติ: " + String(temperature) + " °C");
}
}
// ถ้าอุณหภูมิ > 26 แจ้งเตือนทุก ๆ 30 นาที
else if (temperature > 26) {
if (timeinfo.tm_min % 30 == 0) {
sendLineNotify("อุณหภูมิสูง: " + String(temperature) + " °C");
}
}
// ถ้าความชื้น < 40 แจ้งเตือนทุก ๆ 30 นาที
if (humidity < 40) {
if (timeinfo.tm_min % 30 == 0) {
sendLineNotify("ความชื้นต่ำ: " + String(humidity) + " %");
}
}
}
void sendLineNotify(String message) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin("https://notify-api.line.me/api/notify");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.addHeader("Authorization", "Bearer " + String(LINE_TOKEN));
String payload = "message=" + message;
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Line Notify Response: " + response);
} else {
Serial.println("Error sending message: " + String(httpResponseCode));
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}