#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <ESP32Servo.h>
// Pin Definitions
#define PIR_PIN 12
#define SERVO_PIN 13
#define BUZZER_PIN 16
// Create Objects
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C LCD
Servo myServo; // Servo Motor
bool isMovementDetected = false; // Flag to track PIR sensor state
void setup() {
// Initialize Serial
Serial.begin(115200);
// Initialize PIR sensor, Servo, and Buzzer
pinMode(PIR_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
myServo.attach(SERVO_PIN, 500, 2400); // Set servo signal range for ESP32
// Initialize LCD
lcd.init();
lcd.setBacklight(1);
lcd.print("System Init...");
Serial.println("Sistem Inisialisasi...");
}
void loop() {
// Check PIR sensor for movement
if (digitalRead(PIR_PIN) == HIGH) {
// Gerakan terdeteksi
if (!isMovementDetected) {
isMovementDetected = true;
Serial.println("Gerakan Terdeteksi");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Hama Terdeteksi");
// Activate Buzzer for Sound Alert
tone(BUZZER_PIN, 1000); // Play sound at 1000Hz
delay(1000); // Sound duration 1 second
noTone(BUZZER_PIN); // Stop the sound
}
// Sweep the servo from 0 to 180 degrees and back to 0
for (int pos = 0; pos <= 180; pos++) { // Sweep from 0 to 180 degrees
myServo.write(pos);
delay(15); // Small delay for smooth motion
}
delay(500); // Wait for a while at 180 degrees
for (int pos = 180; pos >= 0; pos--) { // Sweep back from 180 to 0 degrees
myServo.write(pos);
delay(15); // Small delay for smooth motion
}
delay(500); // Wait for a while at 0 degrees before checking again
} else {
// Tidak ada gerakan terdeteksi
if (isMovementDetected) {
isMovementDetected = false;
Serial.println("Tidak Ada Gerakan");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("No Movement");
// Stop servo from moving when no movement is detected
myServo.write(0); // Set servo to 0 degrees to stop movement
}
}
delay(100); // Small delay before checking the PIR sensor again
}