#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// กำหนดที่อยู่ของจอ LCD I2C
LiquidCrystal_I2C lcd(0x27, 20, 4);
// กำหนดขา Trig และ Echo
const int trigPin = 6;
const int echoPin = 5;
// กำหนดขา Servo
Servo myServo;
const int servoPin = 9;
// กำหนดขาบัซเซอร์
const int buzzerPin = 7;
// กำหนดขา PIR
const int pirPin = 4;
// โน๊ตเพลง Silent Night
int melody[] = {
262, 262, 392, 392, 440, 440, 392, // Silent night, holy night
349, 349, 330, 330, 294, 294, 262, // All is calm, all is bright
392, 392, 440, 440, 392, 349, 349, // 'Round yon Virgin, Mother and Child
330, 330, 294, 294, 262 // Holy infant so tender and mild
};
// ความยาวโน๊ต
int noteDurations[] = {
4, 4, 4, 4, 4, 4, 2, // 1st line
4, 4, 4, 4, 4, 4, 2, // 2nd line
4, 4, 4, 4, 4, 4, 2, // 3rd line
4, 4, 4, 4, 4, 4, 2 // 4th line
};
void setup() {
// เริ่มต้นจอ LCD และตั้งค่าให้พร้อมใช้งาน
lcd.init();
lcd.backlight();
// ตั้งค่า pin สำหรับ HC-SR04
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// ตั้งค่า pin สำหรับ PIR
pinMode(pirPin, INPUT);
// เริ่มต้น servo
myServo.attach(servoPin);
myServo.write(0); // เริ่มที่ 0 องศา
// ตั้งค่าบัซเซอร์
pinMode(buzzerPin, OUTPUT);
// แสดงข้อความเบื้องต้นบนจอ LCD
lcd.setCursor(0, 0);
lcd.print("Distance Sensor");
}
void loop() {
// ส่งสัญญาณ ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// รับสัญญาณ echo
long duration = pulseIn(echoPin, HIGH);
// คำนวณระยะทาง (เซนติเมตร)
long distance = duration * 0.034 / 2;
// ล้างจอและแสดงผลระยะทาง
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// ตรวจจับการเคลื่อนไหวจาก PIR
int pirState = digitalRead(pirPin);
if (pirState == HIGH) {
// ถ้ามีการเคลื่อนไหว ให้ส่งเสียงไซเรน
playSiren();
} else {
// ถ้าไม่มีการเคลื่อนไหว ตรวจสอบระยะทางและควบคุม Servo และบัซเซอร์
if (distance < 50) {
myServo.write(180); // ถ้าน้อยกว่า 50 cm หมุนไปที่ 180 องศา
playSilentNight(); // เล่นเพลง Silent Night
} else {
myServo.write(0); // ถ้ามากกว่า 50 cm หมุนไปที่ 0 องศา
noTone(buzzerPin); // หยุดเสียงบัซเซอร์
}
}
delay(500); // หน่วงเวลา 500ms ก่อนคำนวณใหม่
}
void playSilentNight() {
for (int thisNote = 0; thisNote < 24; thisNote++) {
// คำนวณความยาวโน๊ต
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration); // เล่นโน๊ต
// คำนวณระยะเวลาในการหยุด
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes); // หน่วงระหว่างโน๊ต
noTone(buzzerPin); // หยุดเสียง
}
}
void playSiren() {
// เล่นเสียงไซเรนด้วยการเปลี่ยนความถี่อย่างต่อเนื่อง
for (int i = 0; i < 3; i++) {
tone(buzzerPin, 1000); // ความถี่สูง
delay(500);
tone(buzzerPin, 500); // ความถี่ต่ำ
delay(500);
}
noTone(buzzerPin); // หยุดเสียง
}