Otevirani dveri pomoci RFID + klavesnice

Nedaří se vám s projektem a nenašli jste vhodné místo, kde se zeptat? Napište sem.
Pravidla fóra
Tohle subfórum je určeno pro konzultaci ucelených nápadů, popřípadě řešení komplexnějších projektů, které opravdu není možné rozdělit na menší části.
Většinu problémů jde rozdělit na menší a ptát se na ně v konkrétních subfórech.
Odpovědět
Kony
Příspěvky: 382
Registrován: 09 dub 2020, 11:43
Reputation: 0

Otevirani dveri pomoci RFID + klavesnice

Příspěvek od Kony » 16 lis 2021, 23:49

Ahoj... mám projekt který mi funguje na RFID klice, ale chtel bych tam pridat jeste klavesnici, ale vubec nemam tuseni kam pridat kod, ktery pri zadani spravneho kodu na klavesnici vykona ukon "povoleno" a nebo pri zadani spatneho ukon "zakazano"

funkcni na RFID

Kód: Vybrat vše

/*
  Arduino RFID Access Control

  Security !

  To keep it simple we are going to use Tag's Unique IDs

  as only method of Authenticity. It's simple and not hacker proof.
  If you need security, don't use it unless you modify the code

  Copyright (C) 2015 Omer Siar Baysal

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices
#include "U8glib.h"   // Library for display
#include <Keypad.h>

/*
  Instead of a Relay maybe you want to use a servo
  Servos can lock and unlock door locks too
  There are examples out there.
*/

// #include <Servo.h>

/*
  For visualizing whats going on hardware
  we need some leds and
  to control door lock a relay and a wipe button
  (or some other hardware)
  Used common anode led,digitalWriting HIGH turns OFF led
  Mind that if you are going to use common cathode led or
  just seperate leds, simply comment out #define COMMON_ANODE,
*/

#define COMMON_ANODE

#ifdef COMMON_ANODE
#define LED_ON LOW
#define LED_OFF HIGH
#else
#define LED_ON HIGH
#define LED_OFF LOW
#endif

#define redLed 7    // Set Led Pins
#define greenLed 6

#define relay 4     // Set Relay Pin
#define wipeB 3     // Button pin for WipeMode

boolean match = false;          // initialize card match to false
boolean programMode = false;  // initialize programming mode to false
boolean replaceMaster = false;

int successRead;    // Variable integer to keep if we have Successful Read from Reader

byte storedCard[4];   // Stores an ID read from EEPROM
byte readCard[4];   // Stores scanned ID read from RFID Module
byte masterCard[4];   // Stores master card's ID read from EEPROM
int count;

/*
  We need to define MFRC522's pins and create instance
  Pin layout should be as follows (on Arduino Uno):
  MOSI: Pin 11 / ICSP-4
  MISO: Pin 12 / ICSP-1
  SCK : Pin 13 / ICSP-3
  SS : Pin 10 (Configurable)
  RST : Pin 9 (Configurable)
  look MFRC522 Library for
  other Arduinos' pin configuration
*/

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
U8GLIB_SSD1306_128X32 mujOled(U8G_I2C_OPT_NONE);

// vytvoření proměnných údávajících
// počet řádků a sloupců klávesnice
const byte radky = 4;
const byte sloupce = 3;
// vytvoření pole s rozmístěním kláves
char keys[radky][sloupce] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
// nastavení čísel pinů pro spojení s klávesnicí
byte pinyRadku[radky] = {2, 5, A3, A1};
byte pinySloupcu[sloupce] = {A0, 8, A2};
// vytvoření instance klavesnice z knihovny Keypad
Keypad klavesnice = Keypad( makeKeymap(keys), pinyRadku, pinySloupcu, radky, sloupce); 
const String password = "1234"; // change your password here
String input_password;


///////////////////////////////////////// Main napisy display ///////////////////////////////////
void vstup_do_setup(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 15); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode");
  mujOled.setPrintPos(50, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(": zaznamu");  
  mujOled.setPrintPos(5, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(count);  
}
void vstup_do_setup2(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode"); 
}
void pridano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP pridan");
}
void smazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP smazan");
}
void povoleno(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP POVOLEN");
}
void zakazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP ZAKAZAN");
}
void bez_master(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("vytvor master"); 
}
void master_vytvoren(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("master vytvoren"); 
}
void restart(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Restartuj"); 
}

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
  //Arduino Pin Configuration
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(wipeB, INPUT_PULLUP);   // Enable pin's pull up resistor
  pinMode(relay, OUTPUT);
  pinMode(A0, OUTPUT); 
  pinMode(A1, OUTPUT); 
  pinMode(A2, OUTPUT); 
  pinMode(A3, OUTPUT); 
  //Be careful how relay circuit behave on while resetting or power-cycling your Arduino
  digitalWrite(relay, HIGH);    // Make sure door is locked
  digitalWrite(redLed, LED_OFF);  // Make sure led is off
  digitalWrite(greenLed, LED_OFF);  // Make sure led is off

  //Protocol Configuration
  Serial.begin(9600);  // Initialize serial communications with PC
  SPI.begin();           // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init();    // Initialize MFRC522 Hardware

  //If you set Antenna Gain to Max it will increase reading distance
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

  Serial.println(F("Access Control v3.4"));   // For debugging purposes
  ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details

  //Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM
  if (digitalRead(wipeB) == LOW) {  // when button pressed pin should get low, button connected to ground
    digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
    Serial.println(F("Wipe Button Pressed"));
    Serial.println(F("You have 15 seconds to Cancel"));
    Serial.println(F("This will be remove all records and cannot be undone"));
    delay(15000);                        // Give user enough time to cancel operation
    if (digitalRead(wipeB) == LOW) {    // If button still be pressed, wipe EEPROM
      Serial.println(F("Starting Wiping EEPROM"));
      for (int x = 0; x < EEPROM.length(); x = x + 1) {    //Loop end of EEPROM address
        if (EEPROM.read(x) == 0) {              //If EEPROM address 0
          // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
        }
        else {
          EEPROM.write(x, 0);       // if not write 0 to clear, it takes 3.3mS
        }
      }
      Serial.println(F("EEPROM Successfully Wiped"));
      digitalWrite(redLed, LED_OFF);  // visualize successful wipe
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
    }
    else {
      Serial.println(F("Wiping Cancelled"));
      digitalWrite(redLed, LED_OFF);
    }
  }
  // Check if master card defined, if not let user choose a master card
  // This also useful to just redefine Master Card
  // You can keep other EEPROM records just write other than 143 to EEPROM address 1
  // EEPROM address 1 should hold magical number which is '143'
  if (EEPROM.read(1) != 143) {
    Serial.println(F("No Master Card Defined"));
    Serial.println(F("Scan A PICC to Define as Master Card"));
          mujOled.firstPage();  
          do {
            bez_master();
          } while( mujOled.nextPage() );
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0

    }
    while (!successRead);                  // Program will not go further while you not get a successful read
    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
      EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
    Serial.println(F("Master Card Defined"));
          mujOled.firstPage();  
          do {
            master_vytvoren();
          } while( mujOled.nextPage() );
  }
  Serial.println(F("-------------------"));
  Serial.println(F("Master Card's UID"));
  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
    Serial.print(masterCard[i], HEX);
  }
  Serial.println("");
  Serial.println(F("-------------------"));
  Serial.println(F("Everything Ready"));
  Serial.println(F("Waiting PICCs to be scanned"));
  cycleLeds();    // Everything ready lets give user some feedback by cycling leds
    mujOled.firstPage();
do {
} while( mujOled.nextPage() );
}

///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {
  do {
    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
    if (digitalRead(wipeB) == LOW) {
      digitalWrite(redLed, LED_ON);  // Make sure led is off
      digitalWrite(greenLed, LED_OFF);  // Make sure led is off
      Serial.println(F("Wipe Button Pressed"));
      Serial.println(F("Master Card will be Erased! in 10 seconds"));
      delay(10000);
      if (digitalRead(wipeB) == LOW) {
        EEPROM.write(1, 0);                  // Reset Magic Number.
        Serial.println(F("Restart device to re-program Master Card"));
          mujOled.firstPage();  
          do {
            restart();
          } while( mujOled.nextPage() );
        while (1);
      }
    }
    if (programMode) {
      cycleLeds();              // Program Mode cycles through RGB waiting to read a new card
    }
    else {
      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
    }
  }
  while (!successRead);   //the program will not go further while you not get a successful read
  if (programMode) {
    if ( isMaster(readCard) ) { //If master card scanned again exit program mode
      Serial.println(F("Master Card Scanned"));
      Serial.println(F("Exiting Program Mode"));
        mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      Serial.println(F("-----------------------------"));
      programMode = false;
      return;
    }
    else {
      if ( findID(readCard) ) { // If scanned card is known delete it
        Serial.println(F("I know this PICC, removing..."));
        deleteID(readCard);
        Serial.println("-----------------------------");
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
      else {                    // If scanned card is not known add it
        Serial.println(F("I do not know this PICC, adding..."));
        writeID(readCard);
        Serial.println(F("-----------------------------"));
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
    }
  }
  else {
    if ( isMaster(readCard)) {    // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println(F("Hello Master - Entered Program Mode"));
      count = EEPROM.read(0);   // Read the first Byte of EEPROM that
      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(F(" record(s) on EEPROM"));
      Serial.println("");
      Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      Serial.println(F("Scan Master Card again to Exit Program Mode"));
      Serial.println(F("-----------------------------"));
      mujOled.firstPage();  
          do {
            vstup_do_setup();
          } while( mujOled.nextPage() );
    }
    else {
      if ( findID(readCard) ) { // If not, see if the card is in the EEPROM
        Serial.println(F("Welcome, You shall pass"));
           mujOled.firstPage();  
          do {
            povoleno();
          } while( mujOled.nextPage() );
        granted(5000);         // Open the door lock for 300 ms
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
      else {      // If not, show that the ID was not valid
        Serial.println(F("You shall not pass"));
           mujOled.firstPage();  
          do {
            zakazano();
          } while( mujOled.nextPage() );
        denied();
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
    }
  }
}

/////////////////////////////////////////  Access Granted    ///////////////////////////////////
void granted (int setDelay) {
  digitalWrite(redLed, LED_OFF);  // Turn off red LED
  digitalWrite(greenLed, LED_ON);   // Turn on green LED
  digitalWrite(relay, LOW);     // Unlock door!
  delay(setDelay);          // Hold door lock open for given seconds
  digitalWrite(relay, HIGH);    // Relock door
  delay(1000);            // Hold green LED on for a second
}

///////////////////////////////////////// Access Denied  ///////////////////////////////////
void denied() {
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  digitalWrite(redLed, LED_ON);   // Turn on red LED
  delay(1000);
}


///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
int 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;
  }
  // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
  // I think we should assume every PICC as they have 4 byte UID
  // Until we support 7 byte PICCs
  Serial.println(F("Scanned PICC's UID:"));
  for (int i = 0; i < 4; i++) {  //
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
  }
  Serial.println("");
  mfrc522.PICC_HaltA(); // Stop reading
  return 1;
}

void ShowReaderDetails() {
  // Get the MFRC522 software version
  byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
  Serial.print(F("MFRC522 Software Version: 0x"));
  Serial.print(v, HEX);
  if (v == 0x91)
    Serial.print(F(" = v1.0"));
  else if (v == 0x92)
    Serial.print(F(" = v2.0"));
  else
    Serial.print(F(" (unknown),probably a chinese clone?"));
  Serial.println("");
  // When 0x00 or 0xFF is returned, communication probably failed
  if ((v == 0x00) || (v == 0xFF)) {
    Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
    Serial.println(F("SYSTEM HALTED: Check connections."));
    while (true); // do not go further
  }
}

///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
void cycleLeds() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
}

//////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
void normalModeOn () {
  digitalWrite(redLed, LED_OFF);  // Make sure Red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure Green LED is off
  digitalWrite(relay, HIGH);    // Make sure Door is Locked
}

//////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
void readID( int number ) {
  int start = (number * 4 ) + 2;    // Figure out starting position
  for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
    storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
  }
}

///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
void writeID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
    int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
    int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
    num++;                // Increment the counter by one
    EEPROM.write( 0, num );     // Write the new count to the counter
    for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
      EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
    }
    successWrite();
    Serial.println(F("Succesfully added ID record to EEPROM"));
            mujOled.firstPage();  
          do {
            pridano();
          } while( mujOled.nextPage() );
           delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
  else {
    failedWrite();
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
}

///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
void deleteID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
    failedWrite();      // If not
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
  else {
    int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
    int slot;       // Figure out the slot number of the card
    int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
    int looping;    // The number of times the loop repeats
    int j;
    int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
    slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
    start = (slot * 4) + 2;
    looping = ((num - slot) * 4);
    num--;      // Decrement the counter by one
    EEPROM.write( 0, num );   // Write the new count to the counter
    for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
      EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
    }
    for ( int k = 0; k < 4; k++ ) {         // Shifting loop
      EEPROM.write( start + j + k, 0);
    }
    successDelete();
    Serial.println(F("Succesfully removed ID record from EEPROM"));
          mujOled.firstPage();  
          do {
            smazano();
          } while( mujOled.nextPage() );
          delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
}

///////////////////////////////////////// Check Bytes   ///////////////////////////////////
boolean checkTwo ( byte a[], byte b[] ) {
  if ( a[0] != NULL )       // Make sure there is something in the array first
    match = true;       // Assume they match at first
  for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
    if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
      match = false;
  }
  if ( match ) {      // Check to see if if match is still true
    return true;      // Return true
  }
  else  {
    return false;       // Return false
  }
}

///////////////////////////////////////// Find Slot   ///////////////////////////////////
int findIDSLOT( byte find[] ) {
  int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      // is the same as the find[] ID card passed
      return i;         // The slot number of the card
      break;          // Stop looking we found it
    }
  }
}

///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
boolean findID( byte find[] ) {
  int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      return true;
      break;  // Stop looking we found it
    }
    else {    // If not, return false
    }
  }
  return false;
}

///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
// Flashes the green LED 3 times to indicate a successful write to EEPROM
void successWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
}

///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
// Flashes the red LED 3 times to indicate a failed write to EEPROM
void failedWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
}

///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
// Flashes the blue LED 3 times to indicate a success delete to EEPROM
void successDelete() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);

}

////////////////////// Check readCard IF is masterCard   ///////////////////////////////////
// Check to see if the ID passed is the master programing card
boolean isMaster( byte test[] ) {
  if ( checkTwo( test, masterCard ) )
    return true;
  else
    return false;
}
a potreboval bych tam pridat kod pro klavesnici a kontrolu :

Kód: Vybrat vše

char key = klavesnice.getKey();

  if (key){
    Serial.println(key);

    if(key == '*') {
      input_password = ""; // clear input password
    } else if(key == '#') {
      if(password == input_password) {
        Serial.println("Vstup je povolen");
        // DO YOUR WORK HERE
        
      } else {
        Serial.println("Vstup neni povolen");
      }

      input_password = ""; // clear input password
    } else {
      input_password += key; // append new character to input password string
    }
  }
ale vubec nemam tuseni kam to pridat nebo vlozit.. protoze mi kod na RFID ceka na nacteni ctecky a nechce brat zaznam z klavesnice... Nasel by se prosim nekdo kdo by mi to upravil ??

Uživatelský avatar
gilhad
Příspěvky: 779
Registrován: 07 bře 2018, 11:22
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od gilhad » 17 lis 2021, 02:45

Disclaimer: Kdybych to dělal, tak bych to rozhodně nedělal takhle, ale úplně jinak!

Ale pokud by se to nemělo přepsat od začátku a znova, tak zflikovat se to dá celkem jednoduše a bude z toho ještě typičtější Arduino mazanina, ale bude stačit pár úprav.

---

Problém číslo jedna - Ošetření čtečky karet si v loop() dělá vlastní "loop" a unese výpočet
"Řešení" - hodíme mu do toho vidle a výpočet mu prostě sebereme (jak vy k my, tak my k vy)

zavedeme proměnnou klavesnice_rulez, pokud bude nastavena, tak si delame veci z klavesnice, pokud nebude, beží ze čtečky

místo

Kód: Vybrat vše

///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {
  do {
přijde

Kód: Vybrat vše

int klavesnice_rulez = 0; // 0 = čtečka postaru, cokoli jineho klavesnice rulez, čtečku ignorujeme
char key; // naplníme ho až na to bude vhodná chvíle

void loop () {
// sem přijde nastavení klavesnice_rulez, čili následující kod_A
// kod_A
  if (klavesnice_rulez) {
   // tady bude náš kód
   // kod_B
   // a protože jsme udělali vše, co se v tomto průchodu udělat dalo, tak vzhůru do dalšího provádění loop()  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   return;
 };
// dál to bude pokračovat postaru
  do {
a pokud už to čtečce půjčíme na hraní a čtečka nic nenačte, tak ji to donutíme vrátit, takže ten konec toho do { cyklu změníme z

Kód: Vybrat vše

      }
      while (!successRead);   //the program will not go further while you not get a successful read
na tohleto :

Kód: Vybrat vše

      if (!successRead) return;  // když se čtečka nenačetla, hybaj dělat znova loop()
      }
      while (!successRead);   //the program will not go further while you not get a successful read ( ale read byl úspěšný, jinak by to odchytil už ten return )

---

Problém číslo dva - čtečka, nebo klávesnice ?
Řešení - mystický kod_A

Kód: Vybrat vše

// kod_A je tento kus
  key = klavesnice.getKey(); // pokud nic není stisknuto, je to nula, jinak je to načtený znak
  if (key) klavesnice_rulez=1; // po stisku první klávesy si to zprivatizujeme my a pustíme to až se nám zachce
    // za povšimnutí stojí, že klavesnice_rulez je mimo loop a jakmile ji tu jednou nastavíme, zůstává nastavená pořád, dokud ji jinde nenastavíme jinak
---

Problém číslo tři - zpracování klávesnice
Řešení - kod_B,
čili ten tvůj kód, jenom bez načítání key ( to už udělal kod_A )

Kód: Vybrat vše

   // kod_B je tento kus
  if (key){
    Serial.println(key);

    if(key == '*') {
      input_password = ""; // clear input password
    } else if(key == '#') {
      if(password == input_password) {
        Serial.println("Vstup je povolen");
        // DO YOUR WORK HERE
        
      } else {
        Serial.println("Vstup neni povolen");
      }

      input_password = ""; // clear input password
      klavesnice_rulez = 0; // a vzdáme se výlučného držení klávesnice !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    } else {
      input_password += key; // append new character to input password string
    }
  }

Uživatelský avatar
gilhad
Příspěvky: 779
Registrován: 07 bře 2018, 11:22
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od gilhad » 18 lis 2021, 09:37

Tady je to poskládané dohromady. Ale budeš tam muset ještě dodělat nějaké věci, které máš v té úvodní otázce jen naznačené, například

Kód: Vybrat vše

 if(password == input_password) {
        Serial.println("Vstup je povolen");
        // DO YOUR WORK HERE
tak DO YOUR WORK HERE by mělo asi ten vstup povolit a ty proměnné jako password a input_password by taky měly být někde definované (podobně jako tam, odkud jsi to vzal), jinak ti na to bude nadávat překladač.

Kód: Vybrat vše


/*
  Arduino RFID Access Control

  Security !

  To keep it simple we are going to use Tag's Unique IDs

  as only method of Authenticity. It's simple and not hacker proof.
  If you need security, don't use it unless you modify the code

  Copyright (C) 2015 Omer Siar Baysal

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices
#include "U8glib.h"   // Library for display
#include <Keypad.h>

/*
  Instead of a Relay maybe you want to use a servo
  Servos can lock and unlock door locks too
  There are examples out there.
*/

// #include <Servo.h>

/*
  For visualizing whats going on hardware
  we need some leds and
  to control door lock a relay and a wipe button
  (or some other hardware)
  Used common anode led,digitalWriting HIGH turns OFF led
  Mind that if you are going to use common cathode led or
  just seperate leds, simply comment out #define COMMON_ANODE,
*/

#define COMMON_ANODE

#ifdef COMMON_ANODE
#define LED_ON LOW
#define LED_OFF HIGH
#else
#define LED_ON HIGH
#define LED_OFF LOW
#endif

#define redLed 7    // Set Led Pins
#define greenLed 6

#define relay 4     // Set Relay Pin
#define wipeB 3     // Button pin for WipeMode

boolean match = false;          // initialize card match to false
boolean programMode = false;  // initialize programming mode to false
boolean replaceMaster = false;

int successRead;    // Variable integer to keep if we have Successful Read from Reader

byte storedCard[4];   // Stores an ID read from EEPROM
byte readCard[4];   // Stores scanned ID read from RFID Module
byte masterCard[4];   // Stores master card's ID read from EEPROM
int count;

/*
  We need to define MFRC522's pins and create instance
  Pin layout should be as follows (on Arduino Uno):
  MOSI: Pin 11 / ICSP-4
  MISO: Pin 12 / ICSP-1
  SCK : Pin 13 / ICSP-3
  SS : Pin 10 (Configurable)
  RST : Pin 9 (Configurable)
  look MFRC522 Library for
  other Arduinos' pin configuration
*/

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
U8GLIB_SSD1306_128X32 mujOled(U8G_I2C_OPT_NONE);

// vytvoření proměnných údávajících
// počet řádků a sloupců klávesnice
const byte radky = 4;
const byte sloupce = 3;
// vytvoření pole s rozmístěním kláves
char keys[radky][sloupce] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
// nastavení čísel pinů pro spojení s klávesnicí
byte pinyRadku[radky] = {2, 5, A3, A1};
byte pinySloupcu[sloupce] = {A0, 8, A2};
// vytvoření instance klavesnice z knihovny Keypad
Keypad klavesnice = Keypad( makeKeymap(keys), pinyRadku, pinySloupcu, radky, sloupce); 
const String password = "1234"; // change your password here
String input_password;


///////////////////////////////////////// Main napisy display ///////////////////////////////////
void vstup_do_setup(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 15); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode");
  mujOled.setPrintPos(50, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(": zaznamu");  
  mujOled.setPrintPos(5, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(count);  
}
void vstup_do_setup2(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode"); 
}
void pridano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP pridan");
}
void smazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP smazan");
}
void povoleno(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP POVOLEN");
}
void zakazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP ZAKAZAN");
}
void bez_master(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("vytvor master"); 
}
void master_vytvoren(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("master vytvoren"); 
}
void restart(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Restartuj"); 
}

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
  //Arduino Pin Configuration
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(wipeB, INPUT_PULLUP);   // Enable pin's pull up resistor
  pinMode(relay, OUTPUT);
  pinMode(A0, OUTPUT); 
  pinMode(A1, OUTPUT); 
  pinMode(A2, OUTPUT); 
  pinMode(A3, OUTPUT); 
  //Be careful how relay circuit behave on while resetting or power-cycling your Arduino
  digitalWrite(relay, HIGH);    // Make sure door is locked
  digitalWrite(redLed, LED_OFF);  // Make sure led is off
  digitalWrite(greenLed, LED_OFF);  // Make sure led is off

  //Protocol Configuration
  Serial.begin(9600);  // Initialize serial communications with PC
  SPI.begin();           // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init();    // Initialize MFRC522 Hardware

  //If you set Antenna Gain to Max it will increase reading distance
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

  Serial.println(F("Access Control v3.4"));   // For debugging purposes
  ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details

  //Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM
  if (digitalRead(wipeB) == LOW) {  // when button pressed pin should get low, button connected to ground
    digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
    Serial.println(F("Wipe Button Pressed"));
    Serial.println(F("You have 15 seconds to Cancel"));
    Serial.println(F("This will be remove all records and cannot be undone"));
    delay(15000);                        // Give user enough time to cancel operation
    if (digitalRead(wipeB) == LOW) {    // If button still be pressed, wipe EEPROM
      Serial.println(F("Starting Wiping EEPROM"));
      for (int x = 0; x < EEPROM.length(); x = x + 1) {    //Loop end of EEPROM address
        if (EEPROM.read(x) == 0) {              //If EEPROM address 0
          // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
        }
        else {
          EEPROM.write(x, 0);       // if not write 0 to clear, it takes 3.3mS
        }
      }
      Serial.println(F("EEPROM Successfully Wiped"));
      digitalWrite(redLed, LED_OFF);  // visualize successful wipe
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
    }
    else {
      Serial.println(F("Wiping Cancelled"));
      digitalWrite(redLed, LED_OFF);
    }
  }
  // Check if master card defined, if not let user choose a master card
  // This also useful to just redefine Master Card
  // You can keep other EEPROM records just write other than 143 to EEPROM address 1
  // EEPROM address 1 should hold magical number which is '143'
  if (EEPROM.read(1) != 143) {
    Serial.println(F("No Master Card Defined"));
    Serial.println(F("Scan A PICC to Define as Master Card"));
          mujOled.firstPage();  
          do {
            bez_master();
          } while( mujOled.nextPage() );
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0

    }
    while (!successRead);                  // Program will not go further while you not get a successful read
    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
      EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
    Serial.println(F("Master Card Defined"));
          mujOled.firstPage();  
          do {
            master_vytvoren();
          } while( mujOled.nextPage() );
  }
  Serial.println(F("-------------------"));
  Serial.println(F("Master Card's UID"));
  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
    Serial.print(masterCard[i], HEX);
  }
  Serial.println("");
  Serial.println(F("-------------------"));
  Serial.println(F("Everything Ready"));
  Serial.println(F("Waiting PICCs to be scanned"));
  cycleLeds();    // Everything ready lets give user some feedback by cycling leds
    mujOled.firstPage();
do {
} while( mujOled.nextPage() );
}


int klavesnice_rulez = 0; // 0 = čtečka postaru, cokoli jineho klavesnice rulez, čtečku ignorujeme
char key; // naplníme ho až na to bude vhodná chvíle

///////////////////////////////////////// Main Loop ///////////////////////////////////

void loop () {
// sem přijde nastavení klavesnice_rulez, čili následující kod_A
// kod_A
// kod_A je tento kus
  key = klavesnice.getKey(); // pokud nic není stisknuto, je to nula, jinak je to načtený znak
  if (key) klavesnice_rulez=1; // po stisku první klávesy si to zprivatizujeme my a pustíme to až se nám zachce
    // za povšimnutí stojí, že klavesnice_rulez je mimo loop a jakmile ji tu jednou nastavíme, zůstává nastavená pořád, dokud ji jinde nenastavíme jinak

  if (klavesnice_rulez) {
   // tady bude náš kód
   // kod_B
      // kod_B je tento kus
  if (key){
    Serial.println(key);

    if(key == '*') {
      input_password = ""; // clear input password
    } else if(key == '#') {
      if(password == input_password) {
        Serial.println("Vstup je povolen");
        // DO YOUR WORK HERE
        
      } else {
        Serial.println("Vstup neni povolen");
      }

      input_password = ""; // clear input password
      klavesnice_rulez = 0; // a vzdáme se výlučného držení klávesnice !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    } else {
      input_password += key; // append new character to input password string
    }
  }

   // a protože jsme udělali vše, co se v tomto průchodu udělat dalo, tak vzhůru do dalšího provádění loop()  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   return;
 };
// dál to bude pokračovat postaru
  do {
    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
    if (digitalRead(wipeB) == LOW) {
      digitalWrite(redLed, LED_ON);  // Make sure led is off
      digitalWrite(greenLed, LED_OFF);  // Make sure led is off
      Serial.println(F("Wipe Button Pressed"));
      Serial.println(F("Master Card will be Erased! in 10 seconds"));
      delay(10000);
      if (digitalRead(wipeB) == LOW) {
        EEPROM.write(1, 0);                  // Reset Magic Number.
        Serial.println(F("Restart device to re-program Master Card"));
          mujOled.firstPage();  
          do {
            restart();
          } while( mujOled.nextPage() );
        while (1);
      }
    }
    if (programMode) {
      cycleLeds();              // Program Mode cycles through RGB waiting to read a new card
    }
    else {
      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
    }
        if (!successRead) return;  // když se čtečka nenačetla, hybaj dělat znova loop()
  }
  while (!successRead);   //the program will not go further while you not get a successful read ( ale read byl úspěšný, jinak by to odchytil už ten return )
  if (programMode) {
    if ( isMaster(readCard) ) { //If master card scanned again exit program mode
      Serial.println(F("Master Card Scanned"));
      Serial.println(F("Exiting Program Mode"));
        mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      Serial.println(F("-----------------------------"));
      programMode = false;
      return;
    }
    else {
      if ( findID(readCard) ) { // If scanned card is known delete it
        Serial.println(F("I know this PICC, removing..."));
        deleteID(readCard);
        Serial.println("-----------------------------");
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
      else {                    // If scanned card is not known add it
        Serial.println(F("I do not know this PICC, adding..."));
        writeID(readCard);
        Serial.println(F("-----------------------------"));
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
    }
  }
  else {
    if ( isMaster(readCard)) {    // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println(F("Hello Master - Entered Program Mode"));
      count = EEPROM.read(0);   // Read the first Byte of EEPROM that
      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(F(" record(s) on EEPROM"));
      Serial.println("");
      Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      Serial.println(F("Scan Master Card again to Exit Program Mode"));
      Serial.println(F("-----------------------------"));
      mujOled.firstPage();  
          do {
            vstup_do_setup();
          } while( mujOled.nextPage() );
    }
    else {
      if ( findID(readCard) ) { // If not, see if the card is in the EEPROM
        Serial.println(F("Welcome, You shall pass"));
           mujOled.firstPage();  
          do {
            povoleno();
          } while( mujOled.nextPage() );
        granted(5000);         // Open the door lock for 300 ms
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
      else {      // If not, show that the ID was not valid
        Serial.println(F("You shall not pass"));
           mujOled.firstPage();  
          do {
            zakazano();
          } while( mujOled.nextPage() );
        denied();
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
    }
  }
}

/////////////////////////////////////////  Access Granted    ///////////////////////////////////
void granted (int setDelay) {
  digitalWrite(redLed, LED_OFF);  // Turn off red LED
  digitalWrite(greenLed, LED_ON);   // Turn on green LED
  digitalWrite(relay, LOW);     // Unlock door!
  delay(setDelay);          // Hold door lock open for given seconds
  digitalWrite(relay, HIGH);    // Relock door
  delay(1000);            // Hold green LED on for a second
}

///////////////////////////////////////// Access Denied  ///////////////////////////////////
void denied() {
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  digitalWrite(redLed, LED_ON);   // Turn on red LED
  delay(1000);
}


///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
int 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;
  }
  // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
  // I think we should assume every PICC as they have 4 byte UID
  // Until we support 7 byte PICCs
  Serial.println(F("Scanned PICC's UID:"));
  for (int i = 0; i < 4; i++) {  //
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
  }
  Serial.println("");
  mfrc522.PICC_HaltA(); // Stop reading
  return 1;
}

void ShowReaderDetails() {
  // Get the MFRC522 software version
  byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
  Serial.print(F("MFRC522 Software Version: 0x"));
  Serial.print(v, HEX);
  if (v == 0x91)
    Serial.print(F(" = v1.0"));
  else if (v == 0x92)
    Serial.print(F(" = v2.0"));
  else
    Serial.print(F(" (unknown),probably a chinese clone?"));
  Serial.println("");
  // When 0x00 or 0xFF is returned, communication probably failed
  if ((v == 0x00) || (v == 0xFF)) {
    Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
    Serial.println(F("SYSTEM HALTED: Check connections."));
    while (true); // do not go further
  }
}

///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
void cycleLeds() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
}

//////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
void normalModeOn () {
  digitalWrite(redLed, LED_OFF);  // Make sure Red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure Green LED is off
  digitalWrite(relay, HIGH);    // Make sure Door is Locked
}

//////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
void readID( int number ) {
  int start = (number * 4 ) + 2;    // Figure out starting position
  for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
    storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
  }
}

///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
void writeID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
    int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
    int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
    num++;                // Increment the counter by one
    EEPROM.write( 0, num );     // Write the new count to the counter
    for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
      EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
    }
    successWrite();
    Serial.println(F("Succesfully added ID record to EEPROM"));
            mujOled.firstPage();  
          do {
            pridano();
          } while( mujOled.nextPage() );
           delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
  else {
    failedWrite();
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
}

///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
void deleteID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
    failedWrite();      // If not
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
  else {
    int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
    int slot;       // Figure out the slot number of the card
    int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
    int looping;    // The number of times the loop repeats
    int j;
    int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
    slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
    start = (slot * 4) + 2;
    looping = ((num - slot) * 4);
    num--;      // Decrement the counter by one
    EEPROM.write( 0, num );   // Write the new count to the counter
    for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
      EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
    }
    for ( int k = 0; k < 4; k++ ) {         // Shifting loop
      EEPROM.write( start + j + k, 0);
    }
    successDelete();
    Serial.println(F("Succesfully removed ID record from EEPROM"));
          mujOled.firstPage();  
          do {
            smazano();
          } while( mujOled.nextPage() );
          delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
}

///////////////////////////////////////// Check Bytes   ///////////////////////////////////
boolean checkTwo ( byte a[], byte b[] ) {
  if ( a[0] != NULL )       // Make sure there is something in the array first
    match = true;       // Assume they match at first
  for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
    if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
      match = false;
  }
  if ( match ) {      // Check to see if if match is still true
    return true;      // Return true
  }
  else  {
    return false;       // Return false
  }
}

///////////////////////////////////////// Find Slot   ///////////////////////////////////
int findIDSLOT( byte find[] ) {
  int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      // is the same as the find[] ID card passed
      return i;         // The slot number of the card
      break;          // Stop looking we found it
    }
  }
}

///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
boolean findID( byte find[] ) {
  int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      return true;
      break;  // Stop looking we found it
    }
    else {    // If not, return false
    }
  }
  return false;
}

///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
// Flashes the green LED 3 times to indicate a successful write to EEPROM
void successWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
}

///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
// Flashes the red LED 3 times to indicate a failed write to EEPROM
void failedWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
}

///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
// Flashes the blue LED 3 times to indicate a success delete to EEPROM
void successDelete() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);

}

////////////////////// Check readCard IF is masterCard   ///////////////////////////////////
// Check to see if the ID passed is the master programing card
boolean isMaster( byte test[] ) {
  if ( checkTwo( test, masterCard ) )
    return true;
  else
    return false;
}



Kony
Příspěvky: 382
Registrován: 09 dub 2020, 11:43
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od Kony » 19 lis 2021, 15:39

Tak toto funguje dobre :

Kód: Vybrat vše


/*
  Arduino RFID Access Control

  Security !

  To keep it simple we are going to use Tag's Unique IDs

  as only method of Authenticity. It's simple and not hacker proof.
  If you need security, don't use it unless you modify the code

  Copyright (C) 2015 Omer Siar Baysal

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices
#include "U8glib.h"   // Library for display
#include <Keypad.h>

/*
  Instead of a Relay maybe you want to use a servo
  Servos can lock and unlock door locks too
  There are examples out there.
*/

// #include <Servo.h>

/*
  For visualizing whats going on hardware
  we need some leds and
  to control door lock a relay and a wipe button
  (or some other hardware)
  Used common anode led,digitalWriting HIGH turns OFF led
  Mind that if you are going to use common cathode led or
  just seperate leds, simply comment out #define COMMON_ANODE,
*/

#define COMMON_ANODE

#ifdef COMMON_ANODE
#define LED_ON LOW
#define LED_OFF HIGH
#else
#define LED_ON HIGH
#define LED_OFF LOW
#endif

#define redLed 7    // Set Led Pins
#define greenLed 6

#define relay 4     // Set Relay Pin
#define wipeB 3     // Button pin for WipeMode

boolean match = false;          // initialize card match to false
boolean programMode = false;  // initialize programming mode to false
boolean replaceMaster = false;

int successRead;    // Variable integer to keep if we have Successful Read from Reader

byte storedCard[4];   // Stores an ID read from EEPROM
byte readCard[4];   // Stores scanned ID read from RFID Module
byte masterCard[4];   // Stores master card's ID read from EEPROM
int count;

/*
  We need to define MFRC522's pins and create instance
  Pin layout should be as follows (on Arduino Uno):
  MOSI: Pin 11 / ICSP-4
  MISO: Pin 12 / ICSP-1
  SCK : Pin 13 / ICSP-3
  SS : Pin 10 (Configurable)
  RST : Pin 9 (Configurable)
  look MFRC522 Library for
  other Arduinos' pin configuration
*/

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
U8GLIB_SSD1306_128X32 mujOled(U8G_I2C_OPT_NONE);

// vytvoření proměnných údávajících
// počet řádků a sloupců klávesnice
const byte radky = 4;
const byte sloupce = 3;
// vytvoření pole s rozmístěním kláves
char keys[radky][sloupce] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
// nastavení čísel pinů pro spojení s klávesnicí
byte pinyRadku[radky] = {2, 5, A3, A1};
byte pinySloupcu[sloupce] = {A0, 8, A2};
// vytvoření instance klavesnice z knihovny Keypad
Keypad klavesnice = Keypad( makeKeymap(keys), pinyRadku, pinySloupcu, radky, sloupce); 
const String password = "1234"; // change your password here
String input_password;


///////////////////////////////////////// Main napisy display ///////////////////////////////////
void vstup_do_setup(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 15); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode");
  mujOled.setPrintPos(50, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(": zaznamu");  
  mujOled.setPrintPos(5, 32); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print(count);  
}
void vstup_do_setup2(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Program mode"); 
}
void pridano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP pridan");
}
void smazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("CHIP smazan");
}
void povoleno(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP POVOLEN");
}
void zakazano(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(0, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("VSTUP ZAKAZAN");
}
void bez_master(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr12);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("vytvor master"); 
}
void master_vytvoren(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("master vytvoren"); 
}
void restart(void) {
  // graphic commands to redraw the complete screen should be placed here  
  mujOled.setFont(u8g_font_gdr11);
  mujOled.setPrintPos(10, 25); 
  // call procedure from base class, http://arduino.cc/en/Serial/Print
  mujOled.print("Restartuj"); 
}

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
  //Arduino Pin Configuration
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(wipeB, INPUT_PULLUP);   // Enable pin's pull up resistor
  pinMode(relay, OUTPUT);
  pinMode(A0, OUTPUT); 
  pinMode(A1, OUTPUT); 
  pinMode(A2, OUTPUT); 
  pinMode(A3, OUTPUT); 
  //Be careful how relay circuit behave on while resetting or power-cycling your Arduino
  digitalWrite(relay, HIGH);    // Make sure door is locked
  digitalWrite(redLed, LED_OFF);  // Make sure led is off
  digitalWrite(greenLed, LED_OFF);  // Make sure led is off

  //Protocol Configuration
  Serial.begin(9600);  // Initialize serial communications with PC
  SPI.begin();           // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init();    // Initialize MFRC522 Hardware

  //If you set Antenna Gain to Max it will increase reading distance
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

  Serial.println(F("Access Control v3.4"));   // For debugging purposes
  ShowReaderDetails();  // Show details of PCD - MFRC522 Card Reader details

  //Wipe Code if Button Pressed while setup run (powered on) it wipes EEPROM
  if (digitalRead(wipeB) == LOW) {  // when button pressed pin should get low, button connected to ground
    digitalWrite(redLed, LED_ON); // Red Led stays on to inform user we are going to wipe
    Serial.println(F("Wipe Button Pressed"));
    Serial.println(F("You have 15 seconds to Cancel"));
    Serial.println(F("This will be remove all records and cannot be undone"));
    delay(15000);                        // Give user enough time to cancel operation
    if (digitalRead(wipeB) == LOW) {    // If button still be pressed, wipe EEPROM
      Serial.println(F("Starting Wiping EEPROM"));
      for (int x = 0; x < EEPROM.length(); x = x + 1) {    //Loop end of EEPROM address
        if (EEPROM.read(x) == 0) {              //If EEPROM address 0
          // do nothing, already clear, go to the next address in order to save time and reduce writes to EEPROM
        }
        else {
          EEPROM.write(x, 0);       // if not write 0 to clear, it takes 3.3mS
        }
      }
      Serial.println(F("EEPROM Successfully Wiped"));
      digitalWrite(redLed, LED_OFF);  // visualize successful wipe
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
      delay(200);
      digitalWrite(redLed, LED_ON);
      delay(200);
      digitalWrite(redLed, LED_OFF);
    }
    else {
      Serial.println(F("Wiping Cancelled"));
      digitalWrite(redLed, LED_OFF);
    }
  }
  // Check if master card defined, if not let user choose a master card
  // This also useful to just redefine Master Card
  // You can keep other EEPROM records just write other than 143 to EEPROM address 1
  // EEPROM address 1 should hold magical number which is '143'
  if (EEPROM.read(1) != 143) {
    Serial.println(F("No Master Card Defined"));
    Serial.println(F("Scan A PICC to Define as Master Card"));
          mujOled.firstPage();  
          do {
            bez_master();
          } while( mujOled.nextPage() );
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0

    }
    while (!successRead);                  // Program will not go further while you not get a successful read
    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
      EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
    Serial.println(F("Master Card Defined"));
          mujOled.firstPage();  
          do {
            master_vytvoren();
          } while( mujOled.nextPage() );
  }
  Serial.println(F("-------------------"));
  Serial.println(F("Master Card's UID"));
  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
    Serial.print(masterCard[i], HEX);
  }
  Serial.println("");
  Serial.println(F("-------------------"));
  Serial.println(F("Everything Ready"));
  Serial.println(F("Waiting PICCs to be scanned"));
  cycleLeds();    // Everything ready lets give user some feedback by cycling leds
    mujOled.firstPage();
do {
} while( mujOled.nextPage() );
}


int klavesnice_rulez = 0; // 0 = čtečka postaru, cokoli jineho klavesnice rulez, čtečku ignorujeme
char key; // naplníme ho až na to bude vhodná chvíle

///////////////////////////////////////// Main Loop ///////////////////////////////////

void loop () {
// sem přijde nastavení klavesnice_rulez, čili následující kod_A
// kod_A
// kod_A je tento kus
  key = klavesnice.getKey(); // pokud nic není stisknuto, je to nula, jinak je to načtený znak
  if (key) klavesnice_rulez=1; // po stisku první klávesy si to zprivatizujeme my a pustíme to až se nám zachce
    // za povšimnutí stojí, že klavesnice_rulez je mimo loop a jakmile ji tu jednou nastavíme, zůstává nastavená pořád, dokud ji jinde nenastavíme jinak

  if (klavesnice_rulez) {
   // tady bude náš kód
   // kod_B
      // kod_B je tento kus
  if (key){
    Serial.println(key);
             mujOled.firstPage();  
          do {
              mujOled.setFont(u8g_font_gdr11);
              mujOled.setPrintPos(0, 25); 
              mujOled.print(key);
          } while( mujOled.nextPage() );

    if(key == '*') {
      input_password = ""; // clear input password
    } else if(key == '#') {
      if(password == input_password) {
        Serial.println("Vstup je povolen");
           mujOled.firstPage();  
          do {
            povoleno();
          } while( mujOled.nextPage() );
        granted(5000);
              mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );  
      } else {
        Serial.println("Vstup neni povolen");
           mujOled.firstPage();  
          do {
            povoleno();
          } while( mujOled.nextPage() );
        denied();
                mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }

      input_password = ""; // clear input password
      klavesnice_rulez = 0; // a vzdáme se výlučného držení klávesnice !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    } else {
      input_password += key; // append new character to input password string
    }
  }

   // a protože jsme udělali vše, co se v tomto průchodu udělat dalo, tak vzhůru do dalšího provádění loop()  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
   return;
 };
// dál to bude pokračovat postaru
  do {
    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
    if (digitalRead(wipeB) == LOW) {
      digitalWrite(redLed, LED_ON);  // Make sure led is off
      digitalWrite(greenLed, LED_OFF);  // Make sure led is off
      Serial.println(F("Wipe Button Pressed"));
      Serial.println(F("Master Card will be Erased! in 10 seconds"));
      delay(10000);
      if (digitalRead(wipeB) == LOW) {
        EEPROM.write(1, 0);                  // Reset Magic Number.
        Serial.println(F("Restart device to re-program Master Card"));
          mujOled.firstPage();  
          do {
            restart();
          } while( mujOled.nextPage() );
        while (1);
      }
    }
    if (programMode) {
      cycleLeds();              // Program Mode cycles through RGB waiting to read a new card
    }
    else {
      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
    }
        if (!successRead) return;  // když se čtečka nenačetla, hybaj dělat znova loop()
  }
  while (!successRead);   //the program will not go further while you not get a successful read ( ale read byl úspěšný, jinak by to odchytil už ten return )
  if (programMode) {
    if ( isMaster(readCard) ) { //If master card scanned again exit program mode
      Serial.println(F("Master Card Scanned"));
      Serial.println(F("Exiting Program Mode"));
        mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      Serial.println(F("-----------------------------"));
      programMode = false;
      return;
    }
    else {
      if ( findID(readCard) ) { // If scanned card is known delete it
        Serial.println(F("I know this PICC, removing..."));
        deleteID(readCard);
        Serial.println("-----------------------------");
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
      else {                    // If scanned card is not known add it
        Serial.println(F("I do not know this PICC, adding..."));
        writeID(readCard);
        Serial.println(F("-----------------------------"));
        Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      }
    }
  }
  else {
    if ( isMaster(readCard)) {    // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println(F("Hello Master - Entered Program Mode"));
      count = EEPROM.read(0);   // Read the first Byte of EEPROM that
      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(F(" record(s) on EEPROM"));
      Serial.println("");
      Serial.println(F("Scan a PICC to ADD or REMOVE to EEPROM"));
      Serial.println(F("Scan Master Card again to Exit Program Mode"));
      Serial.println(F("-----------------------------"));
      mujOled.firstPage();  
          do {
            vstup_do_setup();
          } while( mujOled.nextPage() );
    }
    else {
      if ( findID(readCard) ) { // If not, see if the card is in the EEPROM
        Serial.println(F("Welcome, You shall pass"));
           mujOled.firstPage();  
          do {
            povoleno();
          } while( mujOled.nextPage() );
        granted(5000);         // Open the door lock for 300 ms
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
      else {      // If not, show that the ID was not valid
        Serial.println(F("You shall not pass"));
           mujOled.firstPage();  
          do {
            zakazano();
          } while( mujOled.nextPage() );
        denied();
         mujOled.firstPage();
        do {
        } while( mujOled.nextPage() );
      }
    }
  }
}

/////////////////////////////////////////  Access Granted    ///////////////////////////////////
void granted (int setDelay) {
  digitalWrite(redLed, LED_OFF);  // Turn off red LED
  digitalWrite(greenLed, LED_ON);   // Turn on green LED
  digitalWrite(relay, LOW);     // Unlock door!
  delay(setDelay);          // Hold door lock open for given seconds
  digitalWrite(relay, HIGH);    // Relock door
  delay(1000);            // Hold green LED on for a second
}

///////////////////////////////////////// Access Denied  ///////////////////////////////////
void denied() {
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  digitalWrite(redLed, LED_ON);   // Turn on red LED
  delay(1000);
}


///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
int 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;
  }
  // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
  // I think we should assume every PICC as they have 4 byte UID
  // Until we support 7 byte PICCs
  Serial.println(F("Scanned PICC's UID:"));
  for (int i = 0; i < 4; i++) {  //
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
  }
  Serial.println("");
  mfrc522.PICC_HaltA(); // Stop reading
  return 1;
}

void ShowReaderDetails() {
  // Get the MFRC522 software version
  byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
  Serial.print(F("MFRC522 Software Version: 0x"));
  Serial.print(v, HEX);
  if (v == 0x91)
    Serial.print(F(" = v1.0"));
  else if (v == 0x92)
    Serial.print(F(" = v2.0"));
  else
    Serial.print(F(" (unknown),probably a chinese clone?"));
  Serial.println("");
  // When 0x00 or 0xFF is returned, communication probably failed
  if ((v == 0x00) || (v == 0xFF)) {
    Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
    Serial.println(F("SYSTEM HALTED: Check connections."));
    while (true); // do not go further
  }
}

///////////////////////////////////////// Cycle Leds (Program Mode) ///////////////////////////////////
void cycleLeds() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
}

//////////////////////////////////////// Normal Mode Led  ///////////////////////////////////
void normalModeOn () {
  digitalWrite(redLed, LED_OFF);  // Make sure Red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure Green LED is off
  digitalWrite(relay, HIGH);    // Make sure Door is Locked
}

//////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
void readID( int number ) {
  int start = (number * 4 ) + 2;    // Figure out starting position
  for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
    storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
  }
}

///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
void writeID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
    int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
    int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
    num++;                // Increment the counter by one
    EEPROM.write( 0, num );     // Write the new count to the counter
    for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
      EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
    }
    successWrite();
    Serial.println(F("Succesfully added ID record to EEPROM"));
            mujOled.firstPage();  
          do {
            pridano();
          } while( mujOled.nextPage() );
           delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
  else {
    failedWrite();
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
}

///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
void deleteID( byte a[] ) {
  if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
    failedWrite();      // If not
    Serial.println(F("Failed! There is something wrong with ID or bad EEPROM"));
  }
  else {
    int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
    int slot;       // Figure out the slot number of the card
    int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
    int looping;    // The number of times the loop repeats
    int j;
    int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
    slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
    start = (slot * 4) + 2;
    looping = ((num - slot) * 4);
    num--;      // Decrement the counter by one
    EEPROM.write( 0, num );   // Write the new count to the counter
    for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
      EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
    }
    for ( int k = 0; k < 4; k++ ) {         // Shifting loop
      EEPROM.write( start + j + k, 0);
    }
    successDelete();
    Serial.println(F("Succesfully removed ID record from EEPROM"));
          mujOled.firstPage();  
          do {
            smazano();
          } while( mujOled.nextPage() );
          delay(1000);
           mujOled.firstPage();  
          do {
            vstup_do_setup2();
          } while( mujOled.nextPage() );
  }
}

///////////////////////////////////////// Check Bytes   ///////////////////////////////////
boolean checkTwo ( byte a[], byte b[] ) {
  if ( a[0] != NULL )       // Make sure there is something in the array first
    match = true;       // Assume they match at first
  for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
    if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
      match = false;
  }
  if ( match ) {      // Check to see if if match is still true
    return true;      // Return true
  }
  else  {
    return false;       // Return false
  }
}

///////////////////////////////////////// Find Slot   ///////////////////////////////////
int findIDSLOT( byte find[] ) {
  int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      // is the same as the find[] ID card passed
      return i;         // The slot number of the card
      break;          // Stop looking we found it
    }
  }
}

///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
boolean findID( byte find[] ) {
  int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
  for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
    readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
    if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
      return true;
      break;  // Stop looking we found it
    }
    else {    // If not, return false
    }
  }
  return false;
}

///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
// Flashes the green LED 3 times to indicate a successful write to EEPROM
void successWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(greenLed, LED_ON);   // Make sure green LED is on
  delay(200);
}

///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
// Flashes the red LED 3 times to indicate a failed write to EEPROM
void failedWrite() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  delay(200);
  digitalWrite(redLed, LED_ON);   // Make sure red LED is on
  delay(200);
}

///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
// Flashes the blue LED 3 times to indicate a success delete to EEPROM
void successDelete() {
  digitalWrite(redLed, LED_OFF);  // Make sure red LED is off
  digitalWrite(greenLed, LED_OFF);  // Make sure green LED is off
  delay(200);

}

////////////////////// Check readCard IF is masterCard   ///////////////////////////////////
// Check to see if the ID passed is the master programing card
boolean isMaster( byte test[] ) {
  if ( checkTwo( test, masterCard ) )
    return true;
  else
    return false;
}




Jeste bych chtel aby se pri psani na klavesnici zobrazovali znaky dle zmacknuti na OLED....

A jeste jedna otazka... nebude lepsi nahrat do Nano WatchDogs ??? kdyby se seknulo to Nano tak aby se restartovalo ??? ale potom tam nesmi byt delay ne ?

Kony
Příspěvky: 382
Registrován: 09 dub 2020, 11:43
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od Kony » 19 lis 2021, 17:23

By mozna stacilo aby se to vzdy 1x za 24 hodin restartovalo

Uživatelský avatar
kiRRow
Příspěvky: 1152
Registrován: 07 kvě 2019, 07:03
Reputation: 0
Bydliště: Opava

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od kiRRow » 19 lis 2021, 18:24

watchdog + delay = dát do pračky psa s kočkou a doufat, že se nebudou prát ...

Kony
Příspěvky: 382
Registrován: 09 dub 2020, 11:43
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od Kony » 19 lis 2021, 18:28

Proto jsem napsal, ze by asi i stacilo aby se to jednou za 24 hodin restartovalo samo

Kony
Příspěvky: 382
Registrován: 09 dub 2020, 11:43
Reputation: 0

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od Kony » 19 lis 2021, 18:28

kiRRow píše:
19 lis 2021, 18:24
watchdog + delay = dát do pračky psa s kočkou a doufat, že se nebudou prát ...
Tak pokud se pracka bude tocit rychle, tak nebudou mit cas se poprat hihi

Uživatelský avatar
kiRRow
Příspěvky: 1152
Registrován: 07 kvě 2019, 07:03
Reputation: 0
Bydliště: Opava

Re: Otevirani dveri pomoci RFID + klavesnice

Příspěvek od kiRRow » 19 lis 2021, 19:42

Kony píše:
19 lis 2021, 18:28
kiRRow píše:
19 lis 2021, 18:24
watchdog + delay = dát do pračky psa s kočkou a doufat, že se nebudou prát ...
Tak pokud se pracka bude tocit rychle, tak nebudou mit cas se poprat hihi
Pokud se pračka točí rychle, tak je v režimu ždímání. Ten většinou nastává po režimu praní.

Odpovědět

Kdo je online

Uživatelé prohlížející si toto fórum: kiRRow a 10 hostů