door lock

door lock

 
  


#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Servo.h>

#define Password_Length 5

Servo myservo;
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);

int pos = 0;

char Data[Password_Length];
char Master[Password_Length] = "1234";
byte data_count = 0, master_count = 0;

bool Pass_is_good;
bool door = false;
char customKey;


/*---preparing 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] = {0, 1, 2, 3};
byte colPins[COLS] = {4, 5, 6, 7};

Keypad customKeypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);


/*--- Main Action ---*/
void setup()
{
  myservo.attach(9, 2000, 2400);
  ServoClose();
  lcd.begin(16, 2);
  lcd.print("Protected Door");
  loading("Loading");
  lcd.clear();
}


void loop()
{
  if (door == true)
  {
    customKey = customKeypad.getKey();
    if (customKey == '#')
    {
      lcd.clear();
      ServoClose();
      lcd.print("Door is closed");
      delay(3000);
      door = false;
    }
  }
  else
    Open();

}

void loading (char msg[]) {
  lcd.setCursor(0, 1);
  lcd.print(msg);

  for (int i = 0; i < 9; i++) {
    delay(1000);
    lcd.print(".");
  }
}

void clearData()
{
  while (data_count != 0)
  { 
    Data[data_count--] = 0;
  }
  return;
}

void ServoClose()
{
  for (pos = 90; pos >= 0; pos -= 10) { 
    myservo.write(pos);
  }
}

void ServoOpen()
{
  for (pos = 0; pos <= 90; pos += 10) {
    myservo.write(pos);  
  }
}

void Open()
{
  lcd.setCursor(0, 0);
  lcd.print("Enter Password");
  
  customKey = customKeypad.getKey();
  if (customKey)
  {
    Data[data_count] = customKey;
    lcd.setCursor(data_count, 1);
    lcd.print(Data[data_count]);
    data_count++;
  }

  if (data_count == Password_Length - 1)
  {
    if (!strcmp(Data, Master))
    {
      lcd.clear();
      ServoOpen();
      lcd.print(" Door is Open ");
      door = true;
      delay(5000);
      loading("Waiting");
      lcd.clear();
      lcd.print(" Time is up! ");
      delay(1000);
      ServoClose();
      door = false;      
    }
    else
    {
      lcd.clear();
      lcd.print(" Wrong Password ");
      door = false;
    }
    delay(1000);
    lcd.clear();
    clearData();
  }
}

Code 2

/*
  Controlling a lock with a keypad and servo
  by L0laB <https://github.com/L0laB/arduino-lock>
  
  component used
  - Arduino UNO & Genuino UNO
  - 4x4 Keypad Matrix
  - 1x Servo
  - 2x LEDs
  - Breadboard
  - Jumper wires

  inspired by 
  - https://www.arduino.cc/en/Tutorial/BuiltInExamples
  - https://create.arduino.cc/projecthub/SurtrTech/keypad-door-lock-with-changeable-code-468b15

  for language references see
  - https://www.arduino.cc/reference/en/

  to install the keypad library do
  - [Tools] > [Manage Libraies] > [search for 'keypad'], than choose
    'Mark Stanley, Alexander Breving, Version 3.11', http://playground.arduino.cc/Code/Keypad

  to debug, check
  - [Tools] > [Serial Monitor]

  last modified on Jan, 2nd 2020
*/

//load mandatory libraries
#include <LiquidCrystal.h>
#include <Keypad.h>
#include <Servo.h>

//configuration for the servo - creating a servo object
Servo myservo;

//configuration for the keypad
const byte numRows = 4;                 //number of rows on the keypad
const byte numCols = 4;                 //number of columns on the keypad

char keymap[numRows][numCols] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[numRows] = {9, 8, 7, 6};   //Rows 0 to 3 //if you modify your pins you should modify this too
byte colPins[numCols] = {5, 4, 3, 2};   //Columns 0 to 3

Keypad myKeypad = Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);

//definition of variables
char keypressed;                        //variable to store the key strokes
char password[] = {'1', '2'};           //the default password
short a = 0, i = 0, j = 0;              //variables used later for iterating through password input sequence

//definition of constants
const int ledGreen = 13;                //connect green LED to pin number 13
const int ledRed = 12;                  //connect red LED to pin number 12

//initialise once various components
void setup() {
  Serial.begin(9600);               //open connection to serial monitor

  pinMode(LED_BUILTIN, OUTPUT);     //initialize the board LED as an output
  digitalWrite(ledGreen, LOW);
  digitalWrite(ledRed, HIGH);

  myservo.attach(11);               //attaches the servo on pin 10 to the servo object
  closeLock();
}

//main program - runs always in a loop
void loop() {
  keypressed = myKeypad.getKey();   //constantly wait and read for pressed key

  //shows pressed keys in Serial-Monitor to debug
  if (keypressed != NO_KEY) {
    Serial.println(keypressed);
  }

  //check pressed keys to open/close thelock
  if (keypressed == '*') {          //press '*' to enter password sequence to open the lock
    checkPassword();                //call function to read input
    if (a == sizeof(password)) {    //checkPassword function assigns a value to variable 'a' and it's correct when it has the size of the password array
      openLock();                   //open lock if password is correct
    }
  }

  if (keypressed == '#') {          //press '#' to close the lock
    delay(300);
    closeLock();
  }
}

//function to verify password characters
void checkPassword() {
  i = 0;
  a = 0;
  j = 0;

  while (keypressed != 'B') {                                   //to confirm the password press 'B' to 'open Door'
    keypressed = myKeypad.getKey();
    if (keypressed != NO_KEY && keypressed != 'B' ) {           //If the char typed isn't B and neither "nothing"
      Serial.println(keypressed);                               //ATTENTION security risk, password will be shown in Serial Monitor!
      j++;
      if (keypressed == password[i] && i < sizeof(password)) {  //if the char is correct a-/ i-variable increments to verify the next caracter
        a++;                                                    //maybe only one iterator needed: a or i ?
        i++;
      }
      else
        a--;                                                    //if the character typed is wrong a decrements and cannot equal the size of password array
    }
  }
  keypressed = NO_KEY;
}

//function opening the lock and setting statuses
void closeLock() {
  myservo.write(90);
  digitalWrite(LED_BUILTIN, HIGH);
  digitalWrite(ledRed, HIGH);
  digitalWrite(ledGreen, LOW);
  Serial.println("closing the lock");
}

//function closing the lock and setting statuses
void openLock() {
  myservo.write(0);
  digitalWrite(LED_BUILTIN, LOW);
  digitalWrite(ledGreen, HIGH);
  digitalWrite(ledRed, LOW);
  Serial.println("opening the lock");
}




Door lock bloetuut


#include <Servo.h>

Servo myservo;  // create servo object to control a servo

String inputString = "";
String command = "";
String value = "";
String password = "1958654"; // this is the password for opening and closing your door
                            // you can set any pasword you like using digit and symbols
boolean stringComplete = false; 

void setup(){
  //start serial connection
  Serial.begin(9600);  // baud rate is 9600 must match with bluetooth 
  //The String reserve() function allows you to allocate a buffer in memory for manipulating strings.
  inputString.reserve(50);  // reserve 50 bytes in memory to save for string manipulation 
  command.reserve(50);
  value.reserve(50);
  
  boolean stringOK = false;
  
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  
}

void loop(){
  // if arduino receive a string termination character like \n stringComplete will set to true
  if (stringComplete) {
    //Serial.println(inputString);
    delay(100);
    // identified the posiion of '=' in string and set its index to pos variable
    int pos = inputString.indexOf('=');
    // value of pos variable > or = 0 means '=' present in received string.
    if (pos > -1) {
      // substring(start, stop) function cut a specific portion of string from start to stop
      // here command will be the portion of received string till '='
      // let received string is open=test123
      // then command is 'open' 
        command = inputString.substring(0, pos);
      // value will be from after = to newline command
      // for the above example value is test123
      // we just ignoreing the '=' taking first parameter of substring as 'pos+1'
      // we are using '=' as a separator between command and vale
      // without '=' any other character can be used
      // we are using = menas our command or password must not contains any '=', otherwise it will cause error 
        value = inputString.substring(pos+1, inputString.length()-1);  // extract command up to \n exluded
        //Serial.println(command);
        //Serial.println(value);
       
       // password.compareTo(value) compare between password tring and value string, if match return 0 
    if(!password.compareTo(value) && (command == "OPEN")){
          // if password matched and command is 'OPEN' than door should open
           openDoor(); // call openDoor() function
           Serial.println(" OPEN"); // sent open feedback to phone
           delay(100);
           }
    else if(!password.compareTo(value) && (command == "CLOSE")){
          // if password matched and command is 'CLOSE' than door should close
           closeDoor();
           Serial.println(" CLOSE"); // sent " CLOSE" string to the phone 
           delay(100);
           }
    else if(password.compareTo(value)){
          // if password not matched than sent wrong feedback to phone
           Serial.println(" WRONG");
           delay(100);
           } 
        } 
       // clear the string for next iteration
       inputString = "";
       stringComplete = false;
    }
   
}


void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    //Serial.write(inChar);
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline or a carriage return, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n' || inChar == '\r') {
      stringComplete = true;
    } 
  }
}

void openDoor(){
  myservo.write(-45); 
  delay(100);   
}

void closeDoor(){
  myservo.write(165);
  delay(100); 
}














/*
 * Fingerprint Door Lock System
 * 
 * Designed for Novita Palilati's Final Project
 * 
 * The circuit:
 * Using DFRobot LCD Keypad Shield
 * Fingerprint Sensor: TX to D2; RX to D3; Vcc to 3.3V;
 * Passive Buzzer to A1 pin
 * Solenoid driver to A2 pin (active low)
 * 
 * ADC Value for Analog Keypad:
 * Key RIGHT  = 0
 * Key UP     = 131
 * Key DOWN   = 306
 * Key LEFT   = 479
 * Key SELECT = 720
 * 
 * 
 * Created 2 May 2018
 * @Gorontalo, Indonesia
 * by ZulNs
 */

#include <EEPROM.h>
#include <LiquidCrystal.h>
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

#define LCD_RS 8
#define LCD_EN 9
#define LCD_D4 4
#define LCD_D5 5
#define LCD_D6 6
#define LCD_D7 7

#define SS_RX 2
#define SS_TX 3

#define KEY_NONE   0
#define KEY_RIGHT  1
#define KEY_UP     2
#define KEY_DOWN   3
#define KEY_LEFT   4
#define KEY_SELECT 5

#define MENU_ENROLL         0
#define MENU_DELETE         1
#define MENU_EMPTY_DATABASE 2
#define MENU_TEMPLATE_COUNT 3
#define MENU_CHANGE_PIN     4
#define MENU_LCD_TIMEOUT    5
#define MENU_KEY_TIMEOUT    6
#define MENU_RETURN         7

const uint16_t EEPROM_PIN = EEPROM.length() - 7; // Max 6 chrs + zero chr
const uint16_t EEPROM_LCD_TIMEOUT = EEPROM.length() - 11; // Max 6 chrs + zero chr
const uint16_t EEPROM_KEY_TIMEOUT = EEPROM.length() - 15; // Max 6 chrs + zero chr

LiquidCrystal lcd(LCD_RS, LCD_EN, LCD_D4, LCD_D5, LCD_D6, LCD_D7);
SoftwareSerial mySerial(SS_RX, SS_TX);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

char pin[7] = "908576";
char keyBuffer[7];
uint8_t oldKey;
uint32_t lcdTimeout, keyTimeout, lcdTimer, keyTimer;

void setup()  
{
  finger.begin(57600);
  lcd.begin(16, 2);
  lcd.print(F("  FINGERPRINT"));
  bitSet(DDRB, 2);   // Set D10 as output
  bitSet(PORTB, 2);  // Set D10 high (LCD backlight on)
  bitSet(DDRC, 2);   // Set A2 as output
  bitSet(PORTC, 2);  // Set A2 high (Solenoid Driver off)
  delay(2000);
  
  EEPROM.get(EEPROM_PIN, pin);
  EEPROM.get(EEPROM_LCD_TIMEOUT, lcdTimeout);
  EEPROM.get(EEPROM_KEY_TIMEOUT, keyTimeout);

  lcdPrintL1(F("Init fingerprint"));
  while (!finger.verifyPassword());
  lcdPrintL2(F("Tmpl count: "));
  finger.getTemplateCount();
  lcd.print(finger.templateCount);
  delay(2000);
  
  oldKey = getKey();
  printWaiting();
  enableLcdTimeout();
}

void loop()
{
  uint8_t id, key = getKey();
  id = getFingerprintId();
  if (id > 0)
  {
    printWaiting();
  }
  isLcdTimeout();
  if (key != oldKey)
  {
    if (oldKey == KEY_NONE)
    {
      soundTick();
      enableLcdTimeout();
      if (key == KEY_SELECT)
      {
        keyTimer = lcdTimer;
        if (getPin())
        {
          mainMenu();
        }
        enableLcdTimeout();
        printWaiting();
      }
    }
    oldKey = key;
  }
}

// returns 0 if failed, otherwise returns ID #
uint8_t getFingerprintId()
{
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)
  {
    return 0;
  }
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)
  {
    return 0;
  }
  enableLcdTimeout();
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)
  {
    lcdPrintL1(F("Unrecognized"));
  }
  else
  {
    lcdPrintL1(F("Found ID #"));
    lcd.print(finger.fingerID);
    lcdPrintL2(F("Confidence: "));
    lcd.print(finger.confidence);
    delay(2000);
    bitClear(PORTC, 2);  // Set A2 low (Solenoid Driver on)
    lcdPrintL2(F("Box unlocked.."));
    delay(20000);
    bitSet(PORTC, 2);  // Set A2 high (Solenoid Driver off)
    lcdPrintL2(F("Box locked.."));
    delay(2000);
  }
  while (finger.getImage() != FINGERPRINT_NOFINGER);
  return (p == FINGERPRINT_OK) ? finger.fingerID : 255;
}

uint8_t getFingerprintEnroll(const uint8_t id)
{
  uint8_t p;
  lcdPrintL1(F("Finger #"));
  lcd.print(id);
  p = fingerGetImage();
  if (p != FINGERPRINT_OK)
  {
    return p;
  }
  p = fingerImage2Tz(1);
  if (p != FINGERPRINT_OK)
  {
    return p;
  }
  lcdPrintL2(F("Remove finger"));
  while (finger.getImage() != FINGERPRINT_NOFINGER);
  lcdPrintL1(F("Finger again"));
  p = fingerGetImage();
  if (p != FINGERPRINT_OK)
  {
    return p;
  }
  p = fingerImage2Tz(2);
  if (p != FINGERPRINT_OK)
  {
    return p;
  }
  lcdPrintL1(F("Creating model"));
  p = finger.createModel();
  if (p == FINGERPRINT_OK)
  {
    lcdPrintL2(F("Prints matched!"));
  }
  else if (p == FINGERPRINT_PACKETRECIEVEERR)
  {
    lcdPrintL2(F("Comm error"));
  }
  else if (p == FINGERPRINT_ENROLLMISMATCH)
  {
    lcdPrintL2(F("Did not match"));
  }
  else
  {
    lcdPrintL2(F("Unknown error"));
  }
  delay(2000);
  if (p != FINGERPRINT_OK)
  {
    return p;
  }
  lcdPrintL1(F("Storing model"));
  p = finger.storeModel(id);
  if (p == FINGERPRINT_OK)
  {
    lcdPrintL2(F("Stored #"));
    lcd.print(id);
  }
  else if (p == FINGERPRINT_PACKETRECIEVEERR)
  {
    lcdPrintL2(F("Comm error"));
  }
  else if (p == FINGERPRINT_BADLOCATION)
  {
    lcdPrintL2(F("Could not store"));
  }
  else if (p == FINGERPRINT_FLASHERR)
  {
    lcdPrintL2(F("Error flashing"));
  }
  else
  {
    lcdPrintL2(F("Unknown error"));
  }
  delay(2000);
  return p;   
}

uint8_t fingerGetImage()
{
  uint8_t p;
  while (true)
  {
    p = finger.getImage();
    switch (p)
    {
      case FINGERPRINT_OK:
        lcdPrintL2(F("Image taken"));
        break;
      case FINGERPRINT_NOFINGER:
        if (isKeyTimeout())
        {
          return -1;
        }
        break;
      case FINGERPRINT_PACKETRECIEVEERR:
        lcdPrintL2(F("Comm error"));
        break;
      case FINGERPRINT_IMAGEFAIL:
        lcdPrintL2(F("Imaging error"));
        break;
      default:
        lcdPrintL2(F("Unknown error"));
    }
    if (p != FINGERPRINT_NOFINGER)
    {
      delay(2000);
      keyTimer = millis();
      return p;
    }
  }
}

uint8_t fingerImage2Tz(const uint8_t slot)
{
  uint8_t p = finger.image2Tz(slot);
  switch (p)
  {
    case FINGERPRINT_OK:
      lcdPrintL1(F("Image converted"));
      break;
    case FINGERPRINT_IMAGEMESS:
      lcdPrintL1(F("Image too messy"));
      break;
    case FINGERPRINT_PACKETRECIEVEERR:
      lcdPrintL1(F("Comm error"));
      break;
    case FINGERPRINT_FEATUREFAIL:
      lcdPrintL1(F("Features fail"));
      break;
    case FINGERPRINT_INVALIDIMAGE:
      lcdPrintL1(F("Invalid image"));
      break;
    default:
      lcdPrintL1(F("Unknown error"));
  }
  delay(2000);
  return p;
}

uint8_t deleteFingerprint(const uint8_t id)
{
  uint8_t p = finger.deleteModel(id);
  if (p == FINGERPRINT_OK)
  {
    lcdPrintL1(F("Deleted #"));
    lcd.print(id);
  }
  else if (p == FINGERPRINT_PACKETRECIEVEERR)
  {
    lcdPrintL1(F("Comm error"));
  }
  else if (p == FINGERPRINT_BADLOCATION)
  {
    lcdPrintL1(F("Bad location"));
  }
  else if (p == FINGERPRINT_FLASHERR)
  {
    lcdPrintL1(F("Flashing error"));
  }
  else
  {
    lcdPrintL1(F("Unknown error"));
  }
  delay(2000);
  return p;   
}

void mainMenu()
{
  uint8_t key, menu = MENU_ENROLL;
  char chrBuffer[7];
  boolean isYes;
  lcdPrintL1(F("Select:"));
  while (true)
  {
    switch (menu)
    {
      case MENU_ENROLL:
        lcdPrintL2(F("Enroll"));
        break;
      case MENU_DELETE:
        lcdPrintL2(F("Delete"));
        break;
      case MENU_EMPTY_DATABASE:
        lcdPrintL2(F("Empty database"));
        break;
      case MENU_TEMPLATE_COUNT:
        lcdPrintL2(F("Template count"));
        break;
      case MENU_CHANGE_PIN:
        lcdPrintL2(F("Change PIN"));
        break;
      case MENU_LCD_TIMEOUT:
        lcdPrintL2(F("LCD timeout"));
        break;
      case MENU_KEY_TIMEOUT:
        lcdPrintL2(F("Key timeout"));
        break;
      case MENU_RETURN:
        lcdPrintL2(F("Return"));
    }
    key = getAKey();
    switch (key)
    {
      case KEY_DOWN:
        menu++;
        if (menu == MENU_RETURN + 1)
        {
          menu = MENU_ENROLL;
        }
        break;
      case KEY_UP:
        menu--;
        if (menu == 255)  // 255 is rollover value after decrement of 0
        {
          menu = MENU_RETURN;
        }
        break;
      case KEY_SELECT:
        switch (menu)
        {
          case MENU_ENROLL:
            if (!enrollOrDelete(true))
            {
              return;
            }
            break;
          case MENU_DELETE:
            if (!enrollOrDelete(false))
            {
              return;
            }
            break;
          case MENU_EMPTY_DATABASE:
            key = getSureness();
            if (key == 255)
            {
              return;
            }
            else if (key == 0)
            {
              finger.emptyDatabase();
              lcdPrintL1(F("Now database is"));
              lcdPrintL2(F("empty"));
              delay(2000);
            }
            break;
          case MENU_TEMPLATE_COUNT:
            finger.getTemplateCount();
            lcdPrintL1(F("Template: "));
            lcd.print(finger.templateCount);
            delay(2000);
            break;
          case MENU_CHANGE_PIN:
            if (!getNewPin(F("New PIN:"), 9))
            {
              return;
            }
            if (keyBuffer[0] != 0)
            {
              strcpy(chrBuffer, keyBuffer);
              if (!getNewPin(F("Confirm:"), 9))
              {
                return;
              }
              if (keyBuffer[0] != 0)
              {
                if (strcmp(chrBuffer, keyBuffer) == 0)
                {
                  strcpy(pin, keyBuffer);
                  savePin();
                  lcdPrintL1(F("PIN changed"));
                }
                else
                {
                  lcdPrintL1(F("PIN unchanged"));
                }
                delay(2000);
              }
            }
            break;
          case MENU_LCD_TIMEOUT:
            if (!getTimeout(F("LCD T/O: "), 9, true))
            {
              return;
            }
            break;
          case MENU_KEY_TIMEOUT:
            if (!getTimeout(F("Key T/O: "), 9, false))
            {
              return;
            }
            break;
          case MENU_RETURN:
            return;
        }
        lcdPrintL1(F("Select:"));
        keyTimer = millis();
        break;
      case 255:
        return;
    }
  }
}

boolean enrollOrDelete(const boolean isEnroll)
{
  uint8_t id;
  while (true)
  {
    if (!getNumber(F("ID#"), 3, 6, false))
    {
      return false;
    }
    id = atoi(keyBuffer);
    if (id > 127)
    {
      lcdPrintL1(F("0 < ID < 128"));
      if (getAKey() == 255)
      {
        return false;
      }
      continue;
    }
    if (id == 0)
    {
      return true;
    }
    if (isEnroll)
    {
      if (getFingerprintEnroll(id) == 255)
      {
        return false;
      }
    }
    else
    {
      deleteFingerprint(id);
    }
    keyTimer = millis();
  }
}

uint8_t getSureness()
{
  uint8_t key, pos = 8;
  lcd.cursor();
  lcd.blink();
  lcdPrintL1(F("Sure? Y/N"));
  while (true)
  {
    lcd.setCursor(pos, 0);
    key = getAKey();
    switch (key)
    {
      case KEY_LEFT:
        pos = 6;
        break;
      case KEY_RIGHT:
        pos = 8;
        break;
      default:
        lcd.noCursor();
        lcd.noBlink();
        return (key == 255 ? -1 : pos == 6 ? 0 : 1);
    }
  }
}

boolean getTimeout(const __FlashStringHelper *flashStr, const uint8_t pos, const boolean isLcd)
{
  uint16_t to = isLcd ? lcdTimeout / 1000 : keyTimeout / 1000;  // convert milliseconds to seconds
  uint16_t newTo;
  while (true)
  {
    itoa(to, keyBuffer, 10);
    if (!getNumber(flashStr, pos, 6, true))
    {
      return false;
    }
    newTo = atoi(keyBuffer);
    if (keyBuffer[0] == 0 || isLcd && newTo * 1000 == lcdTimeout || !isLcd && newTo * 1000 == keyTimeout)
    {
      lcdPrintL1(F("T/O unchanged"));
      delay(2000);
      return true;
    }
    if (9 < newTo && newTo < 3601)
    {
      break;
    }
    lcdPrintL1(F("9 < T/O < 3601"));
    if (getAKey() == 255)
    {
      return false;
    }
  }
  if (isLcd)
  {
    lcdTimeout = newTo * 1000;
    EEPROM.put(EEPROM_LCD_TIMEOUT, lcdTimeout);
    lcdPrintL1(F("LCD"));
  }
  else
  {
    keyTimeout = newTo * 1000;
    EEPROM.put(EEPROM_KEY_TIMEOUT, keyTimeout);
    lcdPrintL1(F("Key"));
  }
  lcd.print(F(" T/O changed"));
  delay(2000);
  return true;
}

boolean getNewPin(const __FlashStringHelper *flashStr, const uint8_t pos)
{
  uint8_t len;
  do
  {
    if (!getNumber(flashStr, pos, 6, false))
    {
      return false;
    }
    len = strlen(keyBuffer);
  }
  while (0 < len && len < 4);
  return true;
}

boolean getPin()
{
  return getNumber(F("PIN:"), 5, 6, false) && (strcmp(pin, keyBuffer) == 0);
}

boolean getNumber(const __FlashStringHelper *flashStr, const uint8_t pos, const uint8_t len, const boolean preVal)
{
  uint8_t srcCtr = 6, destCtr = preVal ? strlen(keyBuffer) : 0, key;
  char chr;
  lcdPrintL1(F("      0123456789"));
  lcdPrintL2(flashStr);
  if (preVal)
  {
    lcd.print(keyBuffer);
  }
  lcd.setCursor(srcCtr, 0);
  lcd.cursor();
  lcd.blink();
  while (true)
  {
    key = getAKey();
    switch (key)
    {
      case KEY_RIGHT:
        srcCtr++;
        if (srcCtr == 16)
        {
          srcCtr = 6;
        }
        lcd.setCursor(srcCtr, 0);
        break;
      case KEY_LEFT:
        srcCtr--;
        if (srcCtr == 5)
        {
          srcCtr = 15;
        }
        lcd.setCursor(srcCtr, 0);
        break;
      case KEY_DOWN:
        chr = 42 + srcCtr;
        if (destCtr == len)
        {
          destCtr--;
        }
        keyBuffer[destCtr] = chr;
        lcd.setCursor(pos + destCtr, 1);
        lcd.print(chr);
        lcd.setCursor(srcCtr, 0);
        destCtr++;
        break;
      case KEY_UP:
        if (destCtr > 0)
        {
          destCtr--;
          lcd.setCursor(pos + destCtr, 1);
          lcd.print(F(" "));
          lcd.setCursor(srcCtr, 0);
        }
        break;
      case KEY_SELECT:
        keyBuffer[destCtr] = 0;
        lcd.noCursor();
        lcd.noBlink();
        return true;
      case 255:
        return false;
    }
  }
}

uint8_t getAKey()
{
  uint8_t key, key0 = getKey();
  while (true)
  {
    if (isKeyTimeout())
    {
      return -1;
    }
    key = getKey();
    if (key != key0)
    {
      if (key0 == KEY_NONE)
      {
        soundTick();
        enableLcdTimeout();
        keyTimer = lcdTimer;
        return key;
      }
      key0 = key;
    }
  }
}

uint8_t getKey()
{
  int16_t adc0, adc;
  do
  {
    adc0 = analogRead(0);
    delay(10);
    adc = analogRead(0);
  }
  while (abs(adc - adc0) > 10);
  if (adc < 50)
  {
    return KEY_RIGHT;
  }
  else if (adc < 181)
  {
    return KEY_UP;
  }
  else if (adc < 356)
  {
    return KEY_DOWN;
  }
  else if (adc < 524)
  {
    return KEY_LEFT;
  }
  else if (adc < 770)
  {
    return KEY_SELECT;
  }
  return KEY_NONE;
}

void soundTick()
{
  tone(A1, 4000, 25);
}

void printWaiting()
{
  lcdPrintL1(F("Waiting 4 finger"));
}

void lcdPrintL1(const __FlashStringHelper *flashStr)
{
  lcd.clear();
  lcd.print(flashStr);
}

void lcdPrintL2(const __FlashStringHelper *flashStr)
{
  lcd.setCursor(0, 1);
  lcd.print(F("                "));
  lcd.setCursor(0, 1);
  lcd.print(flashStr);
}

void enableLcdTimeout()
{
  bitSet(PORTB, 2);
  lcdTimer = millis();
}

void isLcdTimeout()
{
  if (millis() - lcdTimer >= lcdTimeout)
  {
    bitClear(PORTB, 2);
  }
}

boolean isKeyTimeout()
{
  return (millis() - keyTimer >= keyTimeout);
}

void savePin()
{
  uint8_t ctr = 0, chr;
  do
  {
    chr = pin[ctr];
    EEPROM.update(EEPROM_PIN + ctr, chr);
    ctr++;
  }
  while (chr != 0);
}







/*
* Arduino Door Lock Access Control Project
* by Dejan Nedelkovski, www.HowToMechatronics.com
* Library: MFRC522, https://github.com/miguelbalboa/rfid
*/
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal.h>
#include <Servo.h>
#define RST_PIN 9
#define SS_PIN 10
byte readCard[4];
char* myTags[100] = {};
int tagsCount = 0;
String tagID = "";
boolean successRead = false;
boolean correctTag = false;
int proximitySensor;
boolean doorOpened = false;
// Create instances
MFRC522 mfrc522(SS_PIN, RST_PIN);
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //Parameters: (rs, enable, d4, d5, d6, d7)
Servo myServo; // Servo motor
void setup() {
// Initiating
SPI.begin(); // SPI bus
mfrc522.PCD_Init(); // MFRC522
lcd.begin(16, 2); // LCD screen
myServo.attach(8); // Servo motor
myServo.write(10); // Initial lock position of the servo motor
// Prints the initial message
lcd.print("-No Master Tag!-");
lcd.setCursor(0, 1);
lcd.print(" SCAN NOW");
// Waits until a master card is scanned
while (!successRead) {
successRead = getID();
if ( successRead == true) {
myTags[tagsCount] = strdup(tagID.c_str()); // Sets the master tag into position 0 in the array
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Master Tag Set!");
tagsCount++;
}
}
successRead = false;
printNormalModeMessage();
}
void loop() {
int proximitySensor = analogRead(A0);
// If door is closed...
if (proximitySensor > 200) {
if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
return;
}
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
return;
}
tagID = "";
// The MIFARE PICCs that we use have 4 byte UID
for ( uint8_t i = 0; i < 4; i++) { //
readCard[i] = mfrc522.uid.uidByte[i];
tagID.concat(String(mfrc522.uid.uidByte[i], HEX)); // Adds the 4 bytes in a single String variable
}
tagID.toUpperCase();
mfrc522.PICC_HaltA(); // Stop reading
correctTag = false;
// Checks whether the scanned tag is the master tag
if (tagID == myTags[0]) {
lcd.clear();
lcd.print("Program mode:");
lcd.setCursor(0, 1);
lcd.print("Add/Remove Tag");
while (!successRead) {
successRead = getID();
if ( successRead == true) {
for (int i = 0; i < 100; i++) {
if (tagID == myTags[i]) {
myTags[i] = "";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Tag Removed!");
printNormalModeMessage();
return;
}
}
myTags[tagsCount] = strdup(tagID.c_str());
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Tag Added!");
printNormalModeMessage();
tagsCount++;
return;
}
}
}
successRead = false;
// Checks whether the scanned tag is authorized
for (int i = 0; i < 100; i++) {
if (tagID == myTags[i]) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Access Granted!");
myServo.write(170); // Unlocks the door
printNormalModeMessage();
correctTag = true;
}
}
if (correctTag == false) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Access Denied!");
printNormalModeMessage();
}
}
// If door is open...
else {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(" Door Opened!");
while (!doorOpened) {
proximitySensor = analogRead(A0);
if (proximitySensor > 200) {
doorOpened = true;
}
}
doorOpened = false;
delay(500);
myServo.write(10); // Locks the door
printNormalModeMessage();
}
}
uint8_t getID() {
// Getting ready for Reading PICCs
if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
return 0;
}
if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue
return 0;
}
tagID = "";
for ( uint8_t i = 0; i < 4; i++) { // The MIFARE PICCs that we use have 4 byte UID
readCard[i] = mfrc522.uid.uidByte[i];
tagID.concat(String(mfrc522.uid.uidByte[i], HEX)); // Adds the 4 bytes in a single String variable
}
tagID.toUpperCase();
mfrc522.PICC_HaltA(); // Stop reading
return 1;
}
void printNormalModeMessage() {
delay(1500);
lcd.clear();
lcd.print("-Access Control-");
lcd.setCursor(0, 1);
lcd.print(" Scan Your Tag!");
}



/*RFID tag scan code
 * https://srituhobby.com
 */
 
#include <LiquidCrystal_I2C.h>
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9
#define SS_PIN  10
byte readCard[4];
byte a = 0;

LiquidCrystal_I2C lcd(0x27, 16, 2);
MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  while (!Serial);
  SPI.begin();
  mfrc522.PCD_Init();
  delay(4);
  mfrc522.PCD_DumpVersionToSerial();
  lcd.setCursor(2, 0);
  lcd.print("Put your card");
}

void loop() {
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return 0;
  }

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Scanned UID");
  a = 0;
  Serial.println(F("Scanned PICC's UID:"));
  for ( uint8_t i = 0; i < 4; i++) {  //
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
    Serial.print(" ");
    lcd.setCursor(a, 1);
    lcd.print(readCard[i], HEX);
    lcd.print(" ");
    delay(500);
    a += 3;
  }
  Serial.println("");
  mfrc522.PICC_HaltA();
  return 1;
}




/*
 * Hello,Welcome TO Techno-E-Solution
 * Check out Video Tutorial of this project:- https://www.youtube.com/watch?v=mmF7q6Nuj6Y
 * Here is the Arduino Code for "RFID Based Door Lock System Using Arduino"
 */
#include <Wire.h>
#include <SPI.h>
#include <MFRC522.h>
#include <LiquidCrystal_I2C.h> 
LiquidCrystal_I2C lcd(0x27, 16, 2);
 
#define SS_PIN 10
#define RST_PIN 9
#define LED_G 4 // Green LED pin
#define LED_R 5 // Red LED pin
#define lock 3

MFRC522 mfrc522(SS_PIN, RST_PIN);
int Btn = 6;
 
void setup() 
{
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  pinMode(LED_G, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(Btn,INPUT);
  pinMode(lock,OUTPUT);
  Serial.println("Place your card on reader...");
  Serial.println();
  lcd.init();
  lcd.backlight();
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(" Scan Your RFID "); 
  lcd.setCursor(0,1);
  lcd.print("   Door Locked   ");

 }
void loop() 
{

if(digitalRead(Btn) == HIGH){
  
    Serial.println("Access Granted");
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    lcd.setCursor(0,1);
    lcd.print(" Door Un-Locked ");
    digitalWrite(lock,HIGH);
    delay(3000);
    digitalWrite(lock,LOW);
    delay(100);
    digitalWrite(LED_G, LOW);
    lcd.setCursor(0,1);
    lcd.print("   Door Locked   ");
  }


  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) 
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) 
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++) 
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();


  
 if (content.substring(1) == "6A 7F 65 B3") //change here the UID of card/cards or tag/tags that you want to give access
  {
    Serial.println("Access Granted");
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    lcd.setCursor(0,1);
    lcd.print(" Door Un-Locked ");
    digitalWrite(lock,HIGH);
    delay(3000);
    digitalWrite(lock,LOW);
    delay(100);
    digitalWrite(LED_G, LOW);
    lcd.setCursor(0,1);
    lcd.print("   Door Locked   ");
  }

else
{
    lcd.setCursor(0,1);
    lcd.print("Invalid RFID Tag");
    Serial.println(" Access denied");
    digitalWrite(LED_R, HIGH);
    digitalWrite(LED_R, LOW);
    delay(100);
    digitalWrite(LED_R, HIGH);
    delay(500);
    digitalWrite(LED_R, LOW);
    delay(100);
    digitalWrite(LED_R, HIGH);
    delay(500);
    digitalWrite(LED_R, LOW);
    lcd.setCursor(0,1);
    lcd.print("   Door Locked   ");
 }
 delay (100);
 }


Komentar

Postingan populer dari blog ini

jam digital

3 phase