#define BLYNK_TEMPLATE_ID "TMPL6UKUG6yP0"
#define BLYNK_TEMPLATE_NAME "PERCOBAAN BARU"
#define BLYNK_AUTH_TOKEN "LQDixn3lYNO0NMtopFwb9tycCkUJoozQ"

#include <Keypad.h>      
#include <WiFi.h> 
#include <BlynkSimpleEsp32.h>

char auth [] = BLYNK_AUTH_TOKEN;
char ssid [] = "Wokwi-GUEST";
char pass [] = "";

#define LED1_PIN 26 
#define buzzerPin 33

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] = {23, 22, 21, 19};
byte colPins[COLS] = {17, 16, 4, 2}; 

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

const int relayPin = 35;  // Pin untuk relay
const int ledPin = 26; // Pin untuk LED
int failed_attempts = 0;

// Password
String password = "1234"; 
String input = ""; 

void setup() {
  pinMode(relayPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  pinMode(ledPin, OUTPUT);

  digitalWrite(relayPin, HIGH);  
  digitalWrite(buzzerPin, LOW);
  digitalWrite(ledPin, LOW);

  Serial.begin(115200);
  Serial.println("Sistem Keypad, Relay, dan Buzzer Siap.");
  Blynk.begin(auth, ssid, pass);
}

void loop() {
  char key = keypad.getKey(); // Baca tombol yang ditekan
  Blynk.run();

  if (key) { // Jika ada tombol yang ditekan
    Serial.print("Key Pressed: ");
    Serial.println(key);
    tone(buzzerPin, 1000, 10); // Suara buzzer sebentar

    if (key == '*') { // Reset input jika tombol * ditekan
      input = "";
      Serial.println("Input direset.");
    } 
    else if (key == '#') { // Verifikasi password jika tombol # ditekan
      if (input == password) {
        Serial.println("Password benar! Pintu Terbuka.");
        digitalWrite(relayPin, HIGH); 
        digitalWrite(ledPin, HIGH);
        delay(5000); // Relay tetap aktif selama 5 detik
        digitalWrite(relayPin, LOW); // Matikan relay
        digitalWrite(ledPin, LOW);

        Blynk.logEvent("percobaan_baru", "PINTU TERBUKA");
      } else if (input.length() > 0) {
        Serial.println("Password salah! Buzzer aktif.");
        Blynk.logEvent("percobaan_baru", "PASSWORD SALAH");
        failed_attempts++;

        if (failed_attempts >= 3) {
          Serial.println("Gagal masuk: Kesalahan 3 kali");
          tone(buzzerPin, 500, 3000); // Aktifkan buzzer untuk 3 detik
          Blynk.logEvent("gagal_masuk_3_kali", "GAGAL MASUK");
          failed_attempts = 0;
        }
      }
      
      input = ""; // Reset input setelah verifikasi password
    } 
    else { 
      input += key; // Tambahkan karakter ke input
    }

    Serial.print("Input saat ini: ");
    Serial.println(input);
  }
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module