#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#define soundSensor A0
#define relayPin 13
#define servoPin 7
int buzzer = 8;
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myservo;
int tapThreshold = 100;
unsigned long lastTapTime = 0;
int tapCounter = 0;
void setup() {
Serial.begin(115200);
pinMode(relayPin, OUTPUT);
pinMode(buzzer, OUTPUT);
lcd.begin(16, 2);
myservo.attach(servoPin);
}
void loop() {
int soundLevel = analogRead(soundSensor);
Serial.println(soundLevel);
if (abs(soundLevel - 512) > tapThreshold && millis() - lastTapTime > 500) {
lastTapTime = millis();
tapCounter++;
if (tapCounter == 2) {
digitalWrite(relayPin, HIGH);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" UNLOCK WELCOME ");
buka(); // Membuka servo
beepBuzzer(3, 1500, 50);
} else if (tapCounter == 4) {
digitalWrite(relayPin, LOW);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" LOCK!!GET-AWAY ");
tutup(); // Tutup servo
beepBuzzer(1, 1000, 50);
tapCounter = 0;
delay(30);
}
}
}
void buka() {
myservo.write(0);
delay(30);
}
void tutup() {
myservo.write(90);
delay(30);
}
void beepBuzzer(int beeps, int frequency, int dutyCycle) {
for (int i = 0; i < beeps; i++) {
tone(buzzer, frequency, dutyCycle);
delay(300);
noTone(buzzer);
delay(30);
}
}