#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <Servo.h>
// Setup untuk LCD dengan I2C address 0x27
LiquidCrystal_I2C lcd(0x27, 16, 2);
Servo myservo;
const byte ROWS = 4; // Empat baris
const byte COLS = 4; // Empat kolom
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
byte rowPins[ROWS] = {9, 8, 7, 6}; // Hubungkan ke pin baris keypad
byte colPins[COLS] = {5, 4, 3, 2}; // Hubungkan ke pin kolom keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
const int buzzerPin = 11; // Buzzer pin
const int servoPin = 10; // Servo pin
const int buttonPin = 12; // Push button pin
String correctPIN = "0212"; // PIN yang benar
String inputPIN = ""; // Variable untuk menyimpan input dari keypad
bool locked = true; // Status kunci, dimulai dalam keadaan terkunci
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
myservo.attach(servoPin);
lcd.begin(16, 2);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
myservo.write(0); // Servo pada posisi terkunci
}
void loop() {
char key = keypad.getKey();
if (key) {
if (key == '#') {
if (inputPIN == correctPIN) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("PIN Correct");
myservo.write(90); // Buka kunci
tone(buzzerPin, 1000, 500); // Buzzer berbunyi 500 ms
locked = false;
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
} else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wrong PIN");
tone(buzzerPin, 500, 1000); // Buzzer berbunyi 1000 ms
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
}
inputPIN = ""; // Reset input setelah mengecek PIN
} else if (key == '*') {
inputPIN = ""; // Reset input jika * ditekan
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
} else {
inputPIN += key; // Tambahkan karakter ke inputPIN
lcd.setCursor(0, 1);
lcd.print(inputPIN);
}
}
if (locked && inputPIN.length() == 4 && inputPIN != correctPIN) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Wrong PIN");
tone(buzzerPin, 500, 1000); // Buzzer berbunyi 1000 ms
delay(2000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
inputPIN = ""; // Reset input setelah PIN salah
}
if (digitalRead(buttonPin) == LOW) { // Cek apakah push button ditekan
myservo.write(0); // Kunci kembali
locked = true;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Enter PIN:");
tone(buzzerPin, 1000, 500); // Buzzer berbunyi singkat saat reset
delay(500); // Debounce delay
}
}
void tone(int pin, int freq, int duration) {
int period = 1000000L / freq;
long elapsedTime = 0;
while (elapsedTime < duration * 1000L) {
digitalWrite(pin, HIGH);
delayMicroseconds(period / 2);
digitalWrite(pin, LOW);
delayMicroseconds(period / 2);
elapsedTime += period;
}
}
void noTone(int pin) {
digitalWrite(pin, LOW);
}