Skip to content

Instantly share code, notes, and snippets.

@fajarlabs
Created March 11, 2021 01:45
Show Gist options
  • Save fajarlabs/e6caa7084d593bc4d6efeffa913d0228 to your computer and use it in GitHub Desktop.
Save fajarlabs/e6caa7084d593bc4d6efeffa913d0228 to your computer and use it in GitHub Desktop.
/* Secret Door Knock Detecting Door Lock
Originally from Steve Hoefer http://grathio.com Version 0.1.10.20.10
Updates by Lee Sonko
Licensed under Creative Commons Attribution-Noncommercial-Share Alike 3.0
http://creativecommons.org/licenses/by-nc-sa/3.0/us/
(In short: Do what you want, just be sure to include this line and the four above it, and don't sell it or use it in anything you sell without contacting me.)
Analog Pin 0: Piezo speaker (connected to ground with 1M pulldown resistor)
Digital Pin 2: Switch to enter a new code. Short this to enter programming mode.
Digital Pin 3: DC gear reduction motor attached to the lock. (Or a motor controller or a solenoid or other unlocking mechanisim.)
Digital Pin 4: Red LED.
Digital Pin 5: Green LED.
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
//#include <Servo.h>
//Servo myservo; // create servo object to control a servo
// stateLock
bool stateLock = false;
// Pin definitions
const int knockSensor = A0; // Piezo sensor on pin 0.
const int programSwitch = 2; // If this is high we program a new code.
const int lockMotor = 3; // Gear motor used to turn the lock.
const int redLED = 4; // Status LED
const int greenLED = 5; // Status LED
const int relaySingle = 6; // relay module
// Tuning constants. Could be made vars and hoooked to potentiometers for soft configuration, etc.
const int threshold = 30; // Minimum signal from the piezo to register as a knock
const int rejectValue = 25; // If an individual knock is off by this percentage of a knock we don't unlock..
const int averageRejectValue = 15; // If the average timing of the knocks is off by this percent we don't unlock.
const int knockFadeTime = 150; // milliseconds we allow a knock to fade before we listen for another one. (Debounce timer.)
const int lockTurnTime = 650; // milliseconds that we run the motor to get it to go a half turn.
const int unlockTime = 5000; // milliseconds that the door remains unlocked.
const int maximumKnocks = 20; // Maximum number of knocks to listen for.
const int knockComplete = 1200; // Longest time to wait for a knock before we assume that it's finished.
// Variables.
int secretCode[maximumKnocks] = {50, 25, 25, 50, 100, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // Initial setup: "Shave and a Hair Cut, two bits."
int knockReadings[maximumKnocks]; // When someone knocks this array fills with delays between knocks.
int knockSensorValue = 0; // Last reading of the knock sensor.
int programButtonPressed = false; // Flag so we remember the programming button setting at the end of the cycle.
int buzzerDoor = 12;
int eventLed = 13;
// Variables labels
const String label1 = "Pintu terkunci";
const String label2 = "Initialize...";
const String label3 = "Pentu terbuka";
const String label4 = "Recording";
const String label5 = "Device Ready";
const String label6 = "Ketuk Pintu";
const String label7 = "Ketuk tersimpan";
void setup() {
lcd.begin();
// myservo.attach(lockMotor); // attaches the servo on pin lockMotor to the servo object
// myservo.write(10); // rotate servo into locked position
pinMode(lockMotor, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(programSwitch,INPUT);
pinMode(knockSensor,INPUT);
pinMode(relaySingle, OUTPUT);
pinMode(buzzerDoor, OUTPUT);
pinMode(eventLed, OUTPUT);
Serial.begin(9600); // Uncomment the Serial.bla lines for debugging.
Serial.println("Program start."); // but feel free to comment them out after it's working right.
digitalWrite(greenLED, HIGH); // Green LED on, everything is go.
digitalWrite(relaySingle, HIGH);
clearLCDLine(0);
lcd.print(label2);
delay(2000);
clearLCDLine(0);
lcd.print(label5);
delay(1000);
clearLCDLine(0);
lcd.print(label6);
clearLCDLine(1);
lcd.print(label1);
}
void loop() {
// Listen for any knock at all.
knockSensorValue = analogRead(knockSensor);
if (digitalRead(programSwitch) == HIGH) { // is the program button pressed?
if(programButtonPressed == false) {
clearLCDLine(1);
lcd.print("Recording");
}
programButtonPressed = true; // Yes, so lets save that state
digitalWrite(redLED, HIGH); // and turn on the red light too so we know we're programming.
} else {
if(programButtonPressed == true) {
clearLCDLine(1);
lcd.print("Kunci tertutup");
}
programButtonPressed = false;
digitalWrite(redLED, LOW);
}
if (knockSensorValue >= threshold) {
Serial.println(knockSensorValue);
listenToSecretKnock();
}
}
// Records the timing of knocks.
void listenToSecretKnock() {
// clearLCDLine(1);
// lcd.print("Silahkan ketuk");
int i = 0;
// First lets reset the listening array.
for (i = 0; i < maximumKnocks; i++) {
knockReadings[i] = 0;
}
int currentKnockNumber = 0; // Incrementer for the array.
int startTime = millis(); // Reference for when this knock started.
int now = millis();
digitalWrite(greenLED, LOW); // we blink the LED for a bit as a visual indicator of the knock.
if (programButtonPressed == true) {
digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock.
}
delay(knockFadeTime); // wait for this peak to fade before we listen to the next one.
digitalWrite(greenLED, HIGH);
if (programButtonPressed == true) {
digitalWrite(redLED, HIGH);
}
do {
//listen for the next knock or wait for it to timeout.
knockSensorValue = analogRead(knockSensor);
if (knockSensorValue >= threshold) { //got another knock...
digitalWrite(eventLed, HIGH);
//record the delay time.
// clearLCDLine(1);
// lcd.print("Ketuk");
Serial.println("knock.");
now = millis();
knockReadings[currentKnockNumber] = now - startTime;
currentKnockNumber ++; //increment the counter
startTime = now;
// and reset our timer for the next knock
digitalWrite(greenLED, LOW);
if (programButtonPressed == true) {
digitalWrite(redLED, LOW); // and the red one too if we're programming a new knock.
}
delay(knockFadeTime); // again, a little delay to let the knock decay.
digitalWrite(greenLED, HIGH);
if (programButtonPressed == true) {
digitalWrite(redLED, HIGH);
}
digitalWrite(eventLed, LOW);
}
now = millis();
//did we timeout or run out of knocks?
} while ((now - startTime < knockComplete) && (currentKnockNumber < maximumKnocks));
//we've got our knock recorded, lets see if it's valid
if (programButtonPressed == false) { // only if we're not in progrmaing mode.
if (validateKnock() == true) {
triggerDoorUnlock();
} else {
clearLCDLine(1);
lcd.print("Ketukan salah!");
digitalWrite(greenLED, LOW); // We didn't unlock, so blink the red LED as visual feedback.
for (i = 0; i < 4; i++) {
digitalWrite(redLED, HIGH);
delay(100);
digitalWrite(redLED, LOW);
delay(100);
}
digitalWrite(greenLED, HIGH);
clearLCDLine(1);
lcd.print("Pintu terkunci");
}
} else { // if we're in programming mode we still validate the lock, we just don't do anything with the lock
validateKnock();
// and we blink the green and red alternately to show that program is complete.
// clearLCDLine(0);
// lcd.print("Add New Key");
clearLCDLine(1);
lcd.print(label7);
delay(1000);
clearLCDLine(1);
lcd.print(label1);
Serial.println("New Key Store");
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
for (i = 0; i < 3; i++) {
delay(100);
digitalWrite(redLED, HIGH);
digitalWrite(greenLED, LOW);
delay(100);
digitalWrite(redLED, LOW);
digitalWrite(greenLED, HIGH);
}
}
}
// Runs the motor (or whatever) to unlock the door.
void triggerDoorUnlock() {
digitalWrite(buzzerDoor, HIGH);
clearLCDLine(1);
lcd.print(label3);
Serial.println("Door unlocked!");
// unlock the door!
//myservo.write(0);
// digitalWrite(relaySingle, LOW);
delay(lockTurnTime);
digitalWrite(buzzerDoor, LOW);
//delay(unlockTime);
//Serial.println("Pintu Ditutup");
// lock the door again!
//myservo.write(180);
// first knock open lock, second knock set to lock
stateLock = !stateLock;
if(stateLock){
Serial.println("Door unlocked!");
digitalWrite(relaySingle, LOW);
} else {
Serial.println("Door locked!");
digitalWrite(relaySingle, HIGH);
}
// Blink the green LED a few times for more visual feedback.
// for (int i = 0; i < 5; i++) {
// digitalWrite(greenLED, LOW);
// delay(100);
// digitalWrite(greenLED, HIGH);
// delay(100);
// }
clearLCDLine(1);
lcd.print(label1);
}
// Sees if our knock matches the secret.
// returns true if it's a good knock, false if it's not.
// todo: break it into smaller functions for readability.
boolean validateKnock() {
int i = 0;
// simplest check first: Did we get the right number of knocks?
int currentKnockCount = 0;
int secretKnockCount = 0;
int maxKnockInterval = 0; // We use this later to normalize the times.
for (i = 0; i < maximumKnocks; i++) {
if (knockReadings[i] > 0) {
currentKnockCount++;
}
if (secretCode[i] > 0) { //todo: precalculate this.
secretKnockCount++;
}
if (knockReadings[i] > maxKnockInterval) { // collect normalization data while we're looping.
maxKnockInterval = knockReadings[i];
}
}
// If we're recording a new knock, save the info and get out of here.
if (programButtonPressed == true) {
for (i = 0; i < maximumKnocks; i++) { // normalize the times
secretCode[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);
}
// And flash the lights in the recorded pattern to let us know it's been programmed.
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
delay(1000);
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, HIGH);
delay(50);
for (i = 0; i < maximumKnocks ; i++) {
digitalWrite(greenLED, LOW);
digitalWrite(redLED, LOW);
// only turn it on if there's a delay
if (secretCode[i] > 0) {
delay( map(secretCode[i], 0, 100, 0, maxKnockInterval)); // Expand the time back out to what it was. Roughly.
digitalWrite(greenLED, HIGH);
digitalWrite(redLED, HIGH);
}
delay(50);
}
return false; // We don't unlock the door when we are recording a new knock.
}
if (currentKnockCount != secretKnockCount) {
return false;
}
/* Now we compare the relative intervals of our knocks, not the absolute time between them.
(ie: if you do the same pattern slow or fast it should still open the door.)
This makes it less picky, which while making it less secure can also make it
less of a pain to use if your tempo is a little slow or fast.
*/
int totaltimeDifferences = 0;
int timeDiff = 0;
for (i = 0; i < maximumKnocks; i++) { // Normalize the times
knockReadings[i] = map(knockReadings[i], 0, maxKnockInterval, 0, 100);
timeDiff = abs(knockReadings[i] - secretCode[i]);
if (timeDiff > rejectValue) { // Individual value too far out of whack
return false;
}
totaltimeDifferences += timeDiff;
}
// It can also fail if the whole thing is too inaccurate.
if (totaltimeDifferences / secretKnockCount > averageRejectValue) {
return false;
}
return true;
}
void clearLCDLine(int line){
for(int n = 0; n < 20; n++) { // 20 indicates symbols in line. For 2x16 LCD write - 16
lcd.setCursor(n,line);
lcd.print(" ");
}
lcd.setCursor(0,line); // set cursor in the beginning of deleted line
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment