#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
// === Inisialisasi LCD I2C ===
LiquidCrystal_I2C lcd(0x27, 16, 2);
// === Setup Keypad ===
const byte ROWS = 4;
const byte COLS = 4;
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};
byte colPins[COLS] = {5, 4, 3, 2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// === Pin LED & Buzzer ===
const int ledMerah = 10;
const int ledHijau = 11;
const int buzzer = 12;
// === Variabel System ===
String password = "1234";
String inputPassword = "";
int countdown = 60;
bool bombActive = false;
bool bombDefused = false;
unsigned long previousMillis = 0;
void setup() {
lcd.init();
lcd.backlight();
pinMode(ledMerah, OUTPUT);
pinMode(ledHijau, OUTPUT);
pinMode(buzzer, OUTPUT);
lcd.setCursor(0,0);
lcd.print("Press A to Start");
}
void loop() {
char key = keypad.getKey();
if (key) {
if (!bombActive && key == 'A') {
startBomb();
}
else if (bombActive && !bombDefused) {
if (key != 'A') {
inputPassword += key;
lcd.setCursor(0, 1);
lcd.print("Code: ");
lcd.print(inputPassword);
if (inputPassword.length() >= password.length()) {
checkPassword();
}
}
}
}
if (bombActive && !bombDefused) {
updateTimer();
}
}
// === Fungsi Start Bom ===
void startBomb() {
bombActive = true;
bombDefused = false;
countdown = 10;
inputPassword = "";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Timer: ");
lcd.print(countdown);
digitalWrite(ledHijau, LOW);
}
// === Fungsi Update Timer ===
void updateTimer() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= 1000) {
previousMillis = currentMillis;
countdown--;
lcd.setCursor(0, 0);
lcd.print("Timer: ");
lcd.print(countdown);
lcd.print(" ");
digitalWrite(ledMerah, !digitalRead(ledMerah));
if (countdown <= 10) {
tone(buzzer, 1000, 100);
}
if (countdown == 0) {
explodeBomb();
}
}
}
// === Fungsi Cek Password ===
void checkPassword() {
if (inputPassword == password) {
defuseBomb();
} else {
wrongPassword();
}
}
// === Fungsi Defuse ===
void defuseBomb() {
bombDefused = true;
bombActive = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Bomb Defused!");
digitalWrite(ledHijau, HIGH);
digitalWrite(ledMerah, LOW);
noTone(buzzer);
}
// === Fungsi Password Salah ===
void wrongPassword() {
lcd.setCursor(0, 1);
lcd.print("Wrong Code! ");
tone(buzzer, 500, 300);
delay(1000);
lcd.setCursor(0, 1);
lcd.print(" ");
inputPassword = "";
}
// === Fungsi Bom Meledak ===
void explodeBomb() {
bombActive = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("BOOM!!!");
tone(buzzer, 2000, 3000);
digitalWrite(ledMerah, HIGH);
}