liman chen
Published

Security Access Using Seeeduino Lotus

When you knock on the door or close to the door, the door will open automatically.

IntermediateProtip8 hours1,796
Security Access Using Seeeduino Lotus

Things used in this project

Hardware components

Seeed Studio Seeeduino Lotus v1.1
×1
Seeed Studio Grove - Ultrasonic Ranger
×1
Seeed Studio Grove - Loudness Sensor
×1
Seeed Studio Grove – Chainable RGB Led V2.0
×1
Seeed Studio Grove - Green LED
×1
Seeed Studio Grove - Button(P)
×1
Seeed Studio Grove - Universal 4 Pin Buckled 50cm Cable
×1

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

ReExitButton.ino

Arduino
/*
  ReExitButton by Eric Pan, Bill Yu, Rolla Wu, Liman Chen, Shawn Zhang, Weizhi Lin, 
  The participant project for Seeed hackathon 2018e01, details could be found: https://www.hackster.io/limanchen/security-access-using-seeeduino-lotus-7eb90f 
  v0.1 2018/2/12
  
  Code and idea derives from the famous Secret knock detecting door lock by Grathio
  http://www.instructables.com/id/Secret-Knock-Detecting-Door-Lock/

  This example code is in the public domain.

*/

#include "Ultrasonic.h"
#include "ChainableLED.h"
#define NUM_LEDS  2
ChainableLED leds(3, 4, NUM_LEDS);
Ultrasonic ultrasonic(7); //Pin 7
byte pos = 0;
const int  buttonPin = 2;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
int door = 6;
const int knockSensor = A0;         // Piezo sensor on pin 0.
const int programSwitch = A2;       // If this is high we program a new code.
const int redLED = A6;            // Status LED

// Tuning constants.  Could be made vars and hoooked to potentiometers for soft configuration, etc.
const int threshold = 200;           // 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 maximumKnocks = 10;       // 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.

//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." - long version
int secretCode[maximumKnocks] = {0, 100, 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.


void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(redLED, OUTPUT);
  leds.init();
  pinMode(buttonPin, INPUT);
  pinMode(programSwitch, INPUT);
  Serial.begin(9600);
  Serial.println("Program start.");        // but feel free to comment them out after it's working right.
}


void loop()
{
  long RangeInCentimeters;
  long knocklevel;
  int door_status = 0; // 0 - locked (default), 1- unlocked; 2- knock failed; 3- learning new knock

  //#ultrasonic sensing
  RangeInCentimeters = ultrasonic.MeasureInCentimeters(); // two measurements should keep an interval
  if (RangeInCentimeters < 100 ) { //tells if people approaching
    door_status = 1; //unlock
    Serial.println("Homie incoming!");
    Serial.println(RangeInCentimeters);        // but feel free to comment them out after it's working right.
  }

  //#knock sensing
  knockSensorValue = analogRead(knockSensor);

  if (digitalRead(programSwitch) == HIGH) { // is the program button pressed?
    programButtonPressed = true;          // Yes, so lets save that state
    Serial.println("New lock recording.");

  } else {
    programButtonPressed = false;
  }

  if (knockSensorValue >= threshold) {
    listenToSecretKnock();
  }

  //#unlock status
  if (door_status == 1) {
    triggerDoorUnlock();
  }
  else {  // guard status (locked)

    leds.setColorRGB(0, 255, 0, 0);
    leds.setColorRGB(1, 0, 0, 255);
  }
  door_status = 0; // close door end of loop

}


// Records the timing of knocks.
void listenToSecretKnock() {
  int currentKnockNumber = 0;               // Incrementer for the array.
  int startTime = millis();                 // Reference for when this knock started.
  int now = millis();
  int i = 0;
  // First lets reset the listening array.
  for (i = 0; i < maximumKnocks; i++) {
    knockReadings[i] = 0;
  }
  //# listen
  do {
    //listen for the next knock or wait for it to timeout.
    knockSensorValue = analogRead(knockSensor);

    if (knockSensorValue >= threshold) {                 //got another knock...
      //record the delay time.
      Serial.println("knock.");
      leds.setColorRGB(0, 100, 100, 100); //left eye white
      leds.setColorRGB(1, 100, 100, 100); //right eye white                     // and the red one too if we're programming a new knock.

      now = millis();
      knockReadings[currentKnockNumber] = now - startTime;
      currentKnockNumber ++;                             //increment the counter
      startTime = now;
      // and reset our timer for the next knock

      //indicate knock
      if (programButtonPressed == true) {
        leds.setColorRGB(0, 0, 255, 0); //left eye white
        leds.setColorRGB(1, 0, 255, 0); //right eye white      }
      } else {

      }
      delay(knockFadeTime);                              // again, a little delay to let the knock decay.
      leds.setColorRGB(0, 0, 0, 255); //left eye blue
      leds.setColorRGB(1, 0, 0, 255); //right eye blue      }

    }
    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) {          // not in progrmaing mode.
    if (validateKnock() == true) {
      triggerDoorUnlock();
    } else {
      Serial.println("Secret knock failed.");
      for (i = 0; i < 4; i++) {
        leds.setColorRGB(0, 255, 0, 0); //left eye red
        leds.setColorRGB(1, 0, 0, 0); //right eye red
        delay(100);
        leds.setColorRGB(0, 0, 0, 0); //left eye dark
        leds.setColorRGB(1, 255, 0, 0); //right eye dark
        delay(100);
      }
    }
  } else { // IN progrmaing mode.
    // if we're in programming mode we still validate the lock, we just don't do anything with the lock
    validateKnock(); //record the new knock
    // and we blink the green and red alternately to show that program is complete.
    Serial.println("New lock stored.");
    for (i = 0; i < 3; i++) {
      delay(100);
      leds.setColorRGB(0, 0, 0, 255); //left eye blue
      leds.setColorRGB(0, 0, 0, 255); //left eye blue

      delay(100);
      leds.setColorRGB(0, 0, 0, 0); //left eye dark
      leds.setColorRGB(0, 0, 0, 0); //right eye dark    }
    }

  }

  for (i = 0; i < 5; i++) {
    //debug info for comparing input and record
    Serial.print(secretCode[i]);
    Serial.print("\t");    // prints a tab
    Serial.print(knockReadings[i]);
    Serial.println();

  }
}

// Runs the motor (or whatever) to unlock the door.
void triggerDoorUnlock() {
  Serial.println("Door unlocked!");
  // turn the motor on for a bit.
  digitalWrite(door, HIGH);
  leds.setColorRGB(0, 0, 255, 0); //left eye green
  leds.setColorRGB(1, 0, 255, 0);  //right eye green
  delay (500);
  delay (lockTurnTime);                    // Wait a bit.
  digitalWrite(door, LOW);            // Turn the motor off.

}

// 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.
    leds.setColorRGB(0, 255, 0, 0); //left eye green
    leds.setColorRGB(1, 255, 0, 0); //left eye green
    delay(1000);
    leds.setColorRGB(0, 255, 0, 0); //left eye green
    leds.setColorRGB(1, 255, 0, 0); //left eye green
    delay(50);
    for (i = 0; i < maximumKnocks ; i++) {
      // 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.
      }
      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 you're 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;

}

Credits

liman chen

liman chen

1 project • 4 followers

Comments