#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
// ตั้งค่า WiFi
const char* ssid = "Wokwi-GUEST"; // ชื่อ Wi-Fi ของคุณ
const char* password = ""; // รหัสผ่าน Wi-Fi ของคุณ
// ตั้งค่า LINE Notify Token
String lineToken = "mdMZj9Mjn001fQgwjSv0BZhHsdGGsSqGlrqDmJ7eh2z";
// ตั้งค่า DHT22
#define DHTPIN 4 // Pin ที่ต่อกับ DHT22
#define DHTTYPE DHT22 // กำหนดชนิดเซ็นเซอร์ DHT22
DHT dht(DHTPIN, DHTTYPE);
// เวลาสำหรับแจ้งเตือน
unsigned long lastNotifyTime = 0;
const long notifyInterval = 300000; // 1 ชั่วโมง (3600000 milliseconds)
// ตั้งค่าช่วงอุณหภูมิและความชื้น
float tempThreshold = 26.0;
float humidityThreshold = 40.0;
bool tempExceeded = false;
bool humidityExceeded = false;
void setup() {
Serial.begin(115200);
dht.begin();
// เชื่อมต่อ WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
// อ่านค่าอุณหภูมิและความชื้น
float h = dht.readHumidity();
float t = dht.readTemperature();
// เช็คค่าวัดว่าถูกต้องหรือไม่
if (isnan(t) || isnan(h)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// แสดงผลที่ Serial Monitor
Serial.println("Temperature: " + String(t) + "°C, Humidity: " + String(h) + "%");
// ตรวจสอบการแจ้งเตือนเมื่อเวลาผ่านไป 1 ชั่วโมง
if (millis() - lastNotifyTime >= notifyInterval) {
sendLineNotify("Hourly Report:\nTemp: " + String(t) + " °C ❄️\nHumidity: " + String(h) + " % 🌫");
lastNotifyTime = millis();
}
// ตรวจสอบสถานะอุณหภูมิและความชื้น
if (t > tempThreshold && !tempExceeded) {
sendLineNotify("Alert: Temperature out of range!\nTemp: " + String(t) + " °C 🌡");;
tempExceeded = true;
} else if (t <= tempThreshold && tempExceeded) {
sendLineNotify("Info: Temperature back to normal.\nTemp: " + String(t) + " °C ❄️");
tempExceeded = false;
}
if (h < humidityThreshold && !humidityExceeded) {
sendLineNotify("Alert: Humidity out of range!\nHumidity: " + String(h) + " % 🌫");
humidityExceeded = true;
} else if (h >= humidityThreshold && humidityExceeded) {
sendLineNotify("Info: Humidity back to normal.\nHumidity: " + String(h) + " % 🌫");
humidityExceeded = false;
}
delay(2000); // อ่านค่าใหม่ทุก 2 วินาที
}
// ฟังก์ชันสำหรับส่งการแจ้งเตือนผ่าน LINE Notify
void sendLineNotify(String message) {
if (WiFi.status() == WL_CONNECTED) { // เช็คการเชื่อมต่อ WiFi
HTTPClient http;
http.begin("https://notify-api.line.me/api/notify"); // URL สำหรับ LINE Notify
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
http.addHeader("Authorization", "Bearer " + lineToken); // ใส่ Token ที่ได้จาก LINE Notify
String postData = "message=" + message;
int httpResponseCode = http.POST(postData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}