const int pirPin = 27; // กำหนดขาเซ็นเซอร์ PIR
const int relayPin = 17; // กำหนดขารีเลย์
const int Buzzer = 18; // กำหนดขา buzzer
bool relayState = LOW; // ตัวแปรเก็บสถานะรีเลย์
unsigned long motionStartTime = 0; // ตัวแปรเก็บเวลาเริ่มต้นเมื่อมีการเคลื่อนไหว
const unsigned long motionDuration = 5000; // เวลาที่รีเลย์จะทำงาน (10 วินาที)
void setup() {
Serial.begin(115200); // เริ่มต้น Serial
pinMode(pirPin, INPUT); // กำหนดขา PIR เป็น INPUT
pinMode(relayPin, OUTPUT); // กำหนดขารีเลย์เป็น OUTPUT
digitalWrite(relayPin, relayState); // ตั้งค่ารีเลย์เริ่มต้น
pinMode(Buzzer, OUTPUT);
}
void loop() {
int pirState = digitalRead(pirPin); // อ่านสถานะของ PIR
if (pirState == HIGH && relayState == LOW) { // ถ้ามีการเคลื่อนไหวและรีเลย์ปิด
Serial.println("Have people!"); // แสดงข้อความใน Serial Monitor
digitalWrite(relayPin, HIGH); // เปิดรีเลย์
tone(Buzzer,1000);
relayState = HIGH; // เปลี่ยนสถานะรีเลย์เป็น HIGH
motionStartTime = millis(); // เก็บเวลาเมื่อมีการเคลื่อนไหว
}
// เช็คว่าต้องปิดรีเลย์หรือไม่
if (relayState == HIGH && (millis() - motionStartTime >= motionDuration)) {
Serial.println("No people!");
noTone(Buzzer);
digitalWrite(relayPin, LOW); // ปิดรีเลย์
relayState = LOW; // เปลี่ยนสถานะรีเลย์เป็น LOW
}
delay(100); // รอ 100 มิลลิวินาที
}