#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include "DHT.h"
#define PIR_PIN 5 // PIR Sensor ที่ GPIO5
#define BUZZER_PIN 6 // Buzzer ที่ GPIO6
#define DHTPIN 2 // DHT22 ที่ GPIO2
#define DHTTYPE DHT22
const char* ssid = "pon";
const char* password = "flash567";
const char* LINE_TOKEN = "YOUR_LINE_TOKEN"; // แก้ไขให้เป็นของคุณ
const char* host = "https://YOUR_SERVER_URL"; // ใส่ URL ของคุณ
DHT dht(DHTPIN, DHTTYPE);
WiFiClientSecure client;
HTTPClient http;
bool isIntruderDetected = false;
bool isSensorEnabled = true;
unsigned long lastAlertTime = 0;
void sendLineMessage(String message) {
client.setInsecure();
if (!client.connect("api.line.me", 443)) {
Serial.println("เชื่อมต่อ LINE API ไม่ได้");
return;
}
String postData = "{\"messages\":[{\"type\":\"text\",\"text\":\"" + message + "\"}]}";
client.print(String("POST /v2/bot/message/broadcast HTTP/1.1\r\n") +
"Host: api.line.me\r\n" +
"Authorization: Bearer " + String(LINE_TOKEN) + "\r\n" +
"Content-Type: application/json\r\n" +
"Content-Length: " + String(postData.length()) + "\r\n\r\n" +
postData);
client.stop();
}
void checkSensorStatus() {
client.setInsecure();
http.begin(client, String(host) + "/status");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
if (payload == "off" && isSensorEnabled) {
isSensorEnabled = false;
Serial.println("เซ็นเซอร์ถูกปิดใช้งาน");
digitalWrite(BUZZER_PIN, LOW);
} else if (payload == "on" && !isSensorEnabled) {
isSensorEnabled = true;
Serial.println("เซ็นเซอร์ถูกเปิดใช้งาน");
}
}
http.end();
}
void checkPIRSensor() {
if (!isSensorEnabled) return;
bool motion = digitalRead(PIR_PIN);
if (motion) {
digitalWrite(BUZZER_PIN, HIGH);
if (!isIntruderDetected || millis() - lastAlertTime >= 2000) {
Serial.println("⚠️ ตรวจพบการเคลื่อนไหว!");
sendLineMessage("⚠️ พื้นที่ถูกบุกรุก!");
lastAlertTime = millis();
isIntruderDetected = true;
}
} else {
digitalWrite(BUZZER_PIN, LOW);
if (isIntruderDetected) {
Serial.println("✅ ไม่มีการเคลื่อนไหว");
sendLineMessage("✅ พื้นที่ปลอดภัยแล้ว");
isIntruderDetected = false;
}
}
}
void checkDHTSensor() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("❌ ไม่สามารถอ่านค่าจาก DHT22 ได้");
return;
}
Serial.print("🌡 อุณหภูมิ: "); Serial.print(t); Serial.println(" °C");
Serial.print("💧 ความชื้น: "); Serial.print(h); Serial.println(" %");
}
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
dht.begin();
Serial.print("เชื่อมต่อ WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\n✅ เชื่อมต่อ WiFi สำเร็จ!");
}
void loop() {
checkSensorStatus();
checkPIRSensor();
checkDHTSensor();
delay(2000);
}