#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
// กำหนดที่อยู่ของจอ LCD I2C (ส่วนใหญ่เป็น 0x27 หรือ 0x3F)
LiquidCrystal_I2C lcd(0x27, 20, 4);
// กำหนดขา Trig, Echo, Servo, และ Buzzer
const int trigPin = 6;
const int echoPin = 5;
const int servoPin = 9;
const int buzzerPin = 7;
Servo myServo; // สร้างอ็อบเจ็กต์ Servo
// Melody notes for "Loy Kratong" (frequencies in Hz)
int melody[] = {
262, 262, 294, 262, 349, 330, // Loy Kratong
262, 262, 294, 262, 392, 349, // Loy Kratong
262, 262, 523, 440, 349, 330, 294, // Loy Kratong [Name]
466, 466, 440, 349, 392, 349 // Loy Kratong
};
// Durations of each note (4 = quarter note, 8 = eighth note, etc.)
int noteDurations[] = {
4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 4, 2,
4, 4, 4, 4, 4, 2
};
void setup() {
// เริ่มต้นจอ LCD และตั้งค่าให้พร้อมใช้งาน
lcd.init();
lcd.backlight(); // เปิดแสง backlight
// ตั้งค่า pin สำหรับ HC-SR04
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// ตั้งค่า pin สำหรับ Buzzer
pinMode(buzzerPin, OUTPUT);
// เริ่มต้น servo และกำหนดตำแหน่งเริ่มต้นเป็น 0 องศา
myServo.attach(servoPin);
myServo.write(0); // เริ่มที่ 0 องศา
// แสดงข้อความเบื้องต้นบนจอ 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");
// ควบคุม Servo ตามระยะทาง
if (distance < 50) {
myServo.write(180); // ถ้าน้อยกว่า 50 cm หมุนไปที่ 180 องศา
playMelody(); // เล่นเพลงถ้าน้อยกว่า 50 cm
} else {
myServo.write(0); // ถ้ามากกว่า 50 cm หมุนไปที่ 0 องศา
noTone(buzzerPin); // หยุดเสียงถ้ามากกว่า 50 cm
}
delay(500); // หน่วงเวลา 500ms ก่อนคำนวณใหม่
}
void playMelody() {
for (int thisNote = 0; thisNote < 25; thisNote++) {
// คำนวณความยาวโน้ต
int noteDuration = 1000 / noteDurations[thisNote];
tone(buzzerPin, melody[thisNote], noteDuration);
// หน่วงเวลาให้โน้ตหยุดเล่น
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// หยุดเสียงหลังจากแต่ละโน้ต
noTone(buzzerPin);
}
}