#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <time.h>
// กำหนดพอร์ตของ DHT22
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// ข้อมูลสำหรับเชื่อมต่อ WiFi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ข้อมูลสำหรับ Line Notify
const String lineNotifyToken = "V785KvHsZ1s5dUjMeS64pJ4Hez9mhVOp7OyuvmJsJTD";
const String lineNotifyUrl = "https://notify-api.line.me/api/notify";
// เวลาแจ้งเตือน
unsigned long lastTempAlertTime = 0;
unsigned long lastHumAlertTime = 0;
unsigned long lastSerialTime = 0;
const unsigned long tempAlertInterval = 30 * 60 * 1000; // 30 นาที
const unsigned long humAlertInterval = 30 * 60 * 1000; // 30 นาที
const unsigned long serialInterval = 10 * 1000; // 10 วินาที
void setup() {
Serial.begin(115200);
dht.begin();
connectToWiFi();
configTime(7 * 3600, 0, "pool.ntp.org", "time.nist.gov"); // Timezone for Thailand
}
void loop() {
// อ่านค่าจาก DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// เช็คการอ่านค่าผิดพลาด
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// แสดงผลผ่าน Serial Monitor ทุก 10 วินาที
unsigned long currentMillis = millis();
if (currentMillis - lastSerialTime >= serialInterval) {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
lastSerialTime = currentMillis;
}
// แจ้งเตือนอุณหภูมิ
if (temperature > 26 && (currentMillis - lastTempAlertTime >= tempAlertInterval)) {
sendLineNotify("Temp is High: " + String(temperature) + " °C");
lastTempAlertTime = currentMillis;
}
// แจ้งเตือนความชื้น
if (humidity < 40 && (currentMillis - lastHumAlertTime >= humAlertInterval)) {
sendLineNotify("Hum is Low: " + String(humidity) + " %");
lastHumAlertTime = currentMillis;
} else if (humidity > 100 && (currentMillis - lastHumAlertTime >= humAlertInterval)) {
sendLineNotify("Hum is High: " + String(humidity) + " %");
lastHumAlertTime = currentMillis;
} else if (humidity >= 40 && humidity <= 100 && (currentMillis - lastHumAlertTime >= humAlertInterval)) {
sendLineNotify("Temp is normal and Hum is Normal");
lastHumAlertTime = currentMillis;
}
}
void connectToWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
void sendLineNotify(String message) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(lineNotifyUrl);
http.addHeader("Authorization", "Bearer " + lineNotifyToken);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String httpRequestData = "message=" + message;
int httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println("Line Notify response: " + response);
} else {
Serial.println("Error on sending POST");
}
http.end();
}
}