PROTOTIPO - CONTROL DE ACCESO CON RFID + TECLADO CON ALMACENAMIENTO EN MICRO SD

 














CODIGO PARA PLACA ARDUINO NANO

#include <SPI.h>      // incluye libreria bus SPI
#include <MFRC522.h>      // incluye libreria especifica para MFRC522
#include <SD.h> // for the SD card
#include <RTClib.h> // for the RTC
#include <LiquidCrystal_I2C.h>  //Downlaod the library: http://www.electronoobs.com/eng_arduino_liq_crystal.php
LiquidCrystal_I2C lcd(0x27,16,2);  
#define RST_PIN  9      // constante para referenciar pin de reset
#define SS_PIN  10      // constante para referenciar pin de slave select
MFRC522 mfrc522(SS_PIN, RST_PIN); // crea objeto mfrc522 enviando pines de slave select y reset
#define CS_SD 4
#define buzzer 3
#define ledrojo A0
#define ledverde A2
#define ledazul A3
#define rele 5
#define boton 6
File myFile;
RTC_DS3231 rtc;     // crea objeto del tipo RTC_DS3231
const PROGMEM byte Usuario[30][4]  ={
   {0xCD, 0x7A, 0xD8, 0x01},
   {0x06, 0x3B, 0xEE, 0xF9},
   {0x79, 0xAB, 0xFC, 0x5C},
   {0x2B, 0x1D, 0x31, 0x09},
   {0x66, 0xD8, 0xDD, 0xF9},
   {0x96, 0x0A, 0xBB, 0xEF}, //Prof. Jesus Tomases
   {0xE8, 0xCC, 0x58, 0x0D},
   {0xC3, 0x5E, 0xEF, 0xB6},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00},
   {0x00, 0x00, 0x00, 0x00}
};
bool acierto=false;
byte LecturaUID[4];         // crea array para almacenar el UID leido

String Docente;
const char docente_1[] PROGMEM = "Jorge Royero";
const char docente_2[] PROGMEM = "Albey Mejia";
const char docente_3[] PROGMEM = "Selfy De Los Reyes";
const char docente_4[] PROGMEM = "Giovany Peña";
const char docente_5[] PROGMEM = "Paola Guevara";
const char docente_6[] PROGMEM = "Jesus Tomases";
const char docente_7[] PROGMEM = "Fredy Charris";
const char docente_8[] PROGMEM = "Alberto Malagon";
const char docente_9[] PROGMEM = "Guillermina Garcia";
const char docente_10[] PROGMEM = "Jose Contreras";
const char docente_11[] PROGMEM = "Kely Tovar";
const char docente_12[] PROGMEM = "Alexandra Salazar";
const char docente_13[] PROGMEM = "Prof. ";
const char docente_14[] PROGMEM = "Prof. ";
const char docente_15[] PROGMEM = "Prof. ";
const char docente_16[] PROGMEM = "Prof. ";
const char docente_17[] PROGMEM = "Prof. ";
const char docente_18[] PROGMEM = "Prof. ";
const char docente_19[] PROGMEM = "Prof. ";
const char docente_20[] PROGMEM = "Prof. ";
const char docente_21[] PROGMEM = "Prof. ";
const char docente_22[] PROGMEM = "Prof. ";
const char docente_23[] PROGMEM = "Prof. ";
const char docente_24[] PROGMEM = "Prof. ";
const char docente_25[] PROGMEM = "Prof. ";
const char docente_26[] PROGMEM = "Prof. ";
const char docente_27[] PROGMEM = "Prof. ";
const char docente_28[] PROGMEM = "Prof. ";
const char docente_29[] PROGMEM = "Prof. ";
const char docente_30[] PROGMEM = "Prof. ";
const char* const names[] PROGMEM = {
  docente_1, docente_2, docente_3, docente_4, docente_5, docente_6,
  docente_7, docente_8, docente_9, docente_10, docente_11, docente_12,
  docente_13, docente_14, docente_15, docente_16, docente_17, docente_18,
  docente_19, docente_20, docente_21, docente_22, docente_23, docente_24,
  docente_25, docente_26, docente_27, docente_28, docente_29, docente_30
};

#include <Keypad_I2C.h>
#include <Keypad.h>        // GDY120705
#include <Wire.h>
#define I2CADDR 0x20
const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char hexaKeys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
//byte rowPins[ROWS] = {0, 1, 2, 3}; //PARA KEYPAD 4X3 PLANO P0=F1, P1=F2, P2=F3, P3=F4
//byte colPins[COLS] = {4, 5, 6}; //PARA KEYPAD 4X3 PLANO P4=C1, P5=C2, P6=C3
byte rowPins[ROWS] = {1, 6, 5, 3}; //PARA KEYPAD 4X3 VOLUMETRICO P1=F1, P6=F2, P5=F3, P3=F4
byte colPins[COLS] = {2, 0, 4}; //PARA KEYPAD 4X3 VOLUMETRICO P2=C1, P0=C2, P4=C3

//initialize an instance of class NewKeypad
Keypad_I2C customKeypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS, I2CADDR);

char TECLA;       // almacena la tecla presionada
char CLAVE[5];        // almacena en un array 4 digitos ingresados

const char* const USUARIO[] PROGMEM ={
   "1231", "1232", "1233", "1234", "1235", "1236", "1237", "1238", "1239", "1240",
   "1241", "1242", "1243", "1244", "1245", "1246", "1247", "1248", "1249", "1250"
   "1251", "1252", "1253", "1254", "1255", "1256", "1257", "1258", "1259", "1260"
};

byte INDICE = 0;      // indice del array

 const int*const hora[] PROGMEM = {
   6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12};

 const int*const minuto[] PROGMEM = {
   0, 30, 0, 30, 0, 30, 0, 30, 0, 30, 0, 30, 0, 30};
 int segundosTimbre = 5;
 int estado_boton = HIGH;
 

void setup() {
  //Serial.begin(9600);     // inicializa comunicacion por monitor serie a 9600 bps
  Wire.begin( );                // GDY200622
  customKeypad.begin( );        // GDY120705
  lcd.init();
  lcd.backlight();
  //lcd.setCursor(0,0);
  //lcd.print("Coloque Tarjeta..");
  pinMode(buzzer, OUTPUT);
  pinMode(ledrojo, OUTPUT);  
  pinMode(ledverde, OUTPUT);
  pinMode(ledazul, OUTPUT);
  pinMode(rele, OUTPUT);
  pinMode(boton, INPUT_PULLUP);
  digitalWrite (buzzer, LOW);
  digitalWrite (ledrojo, LOW);
  digitalWrite (ledverde, LOW);
  digitalWrite (ledazul, LOW);
  digitalWrite (rele, LOW);

  SPI.begin();        // inicializa bus SPI
  mfrc522.PCD_Init();     // inicializa modulo lector
  //Serial.println("Listo");    // Muestra texto Listo

  //Serial.print(F("Initializing SD card..."));
  if(!SD.begin(CS_SD)) {
    //Serial.println(F("initialization failed!"));
     return;
  }
  Serial.println("initialization done.");
  // Setup for the RTC  
  if(!rtc.begin()) {
    //Serial.println(F("Couldn't find RTC"));
     while(1);
  }
}

void loop() {
 
  estado_boton = digitalRead(boton);
  if(estado_boton == LOW){
    digitalWrite(rele, HIGH);
  }
  if(estado_boton == HIGH){
    digitalWrite(rele, LOW);
  }
  LeerTeclado();
          DateTime fecha = rtc.now();       // funcion que devuelve fecha y horario en formato
          lcd.setCursor(4,0);
          lcd.print(fecha.day());       // funcion que obtiene el dia de la fecha completa
          lcd.print("/");         // caracter barra como separador
          lcd.print(fecha.month());       // funcion que obtiene el mes de la fecha completa
          lcd.print("/");         // caracter barra como separador
          lcd.print(fecha.year());        // funcion que obtiene el año de la fecha completa
          lcd.setCursor(4,1);
          lcd.print(fecha.hour());        // funcion que obtiene la hora de la fecha completa
          lcd.print(":");         // caracter dos puntos como separador
          lcd.print(fecha.minute());        // funcion que obtiene los minutos de la fecha completa
          lcd.print(":");         // caracter dos puntos como separador
          lcd.print(fecha.second());      // funcion que obtiene los segundos de la fecha completa
          if (fecha.minute() == 0 && fecha.second() == 0){  //
          lcd.clear();}
          for(int i = 0; i<14; i++){
          if (fecha.hour() == pgm_read_word(&(hora[i])) && fecha.minute() == pgm_read_word(&(minuto[i])) && fecha.second() <= segundosTimbre - 1){
            Timbre();
            }}

  if ( ! mfrc522.PICC_IsNewCardPresent())   // si no hay una tarjeta presente
    return;           // retorna al loop esperando por una tarjeta
 
  if ( ! mfrc522.PICC_ReadCardSerial())     // si no puede obtener datos de la tarjeta
    return;           // retorna al loop esperando por otra tarjeta
    //Serial.print(F("UID:"));        // muestra texto UID:
   
    for (byte i = 0; i < mfrc522.uid.size; i++) { // bucle recorre de a un byte por vez el UID
      if (mfrc522.uid.uidByte[i] < 0x10){   // si el byte leido es menor a 0x10
        //Serial.print(F(" 0"));        // imprime espacio en blanco y numero cero
        }
        else{           // sino
          //Serial.print(F(" "));       // imprime un espacio en blanco
          }
          //Serial.print(mfrc522.uid.uidByte[i], HEX);    // imprime el byte del UID leido en hexadecimal
          LecturaUID[i]=mfrc522.uid.uidByte[i];     // almacena en array el byte del UID leido      
           }
          //Serial.print(F("\t"));        // imprime un espacio de tabulacion  

         
          acierto=false;
          for(int i = 0; i<30; i++){//pgm_read_byte(&mi_cadena[0])
          const byte PROGMEM b0=pgm_read_dword(&(Usuario[i]))>>0;
          const byte PROGMEM b1=pgm_read_dword(&(Usuario[i]))>>8;
          const byte PROGMEM b2=pgm_read_dword(&(Usuario[i]))>>16;
          const byte PROGMEM b3=pgm_read_dword(&(Usuario[i]))>>24;

          const byte leido[4]={b0,b1,b2,b3};
           if(comparaUID(LecturaUID, leido)){   // llama a funcion comparaUID con Usuario1
            acierto=true;
            char arrayBuf[20];  // crea un búfer
            strcpy_P(arrayBuf, pgm_read_word(&(names[i])));
            Docente = arrayBuf;
            //Serial.print(F("Bienvenido ")); // si retorna verdadero muestra texto bienvenida
            //Serial.println(Docente);
            GrabarSdrfid();
            delay(30);
           }
            else            // si retorna falso
            //Serial.println(F("No te conozco"));     // muestra texto equivalente a acceso denegado          
           
            mfrc522.PICC_HaltA();     // detiene comunicacion con tarjeta
          }  
          if(!acierto)
          {
            //Serial.println(F("No te conozco"));     // muestra texto equivalente a acceso denegado          
          }                                      
  } //AQUI FINALIZA EL LOOP

boolean comparaUID(byte lectura[],byte usuario[]) // funcion comparaUID
{
  for (byte i=0; i < mfrc522.uid.size; i++){    // bucle recorre de a un byte por vez el UID
  if(lectura[i] != usuario[i])        // si byte de UID leido es distinto a usuario
    return(false);          // retorna falso
  }
  return(true);           // si los 4 bytes coinciden retorna verdadero
}


void GrabarSdrfid(){
  digitalWrite(CS_SD,LOW); // Enables SD card chip select pin
  myFile=SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    delay(300);
    //myFile.print(LecturaUID);
    //myFile.print(", ");  
    DateTime now = rtc.now();
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.print(now.minute(), DEC);
    myFile.print(':');
    myFile.print(now.second(), DEC);
    myFile.print(',');
    myFile.print(Docente); //Nomre del docente
    myFile.print(',');
    myFile.println("Acceso mediante chip RFID");
    Serial.println(F("sucessfully written on SD card"));
    delay(300);
    myFile.close();
    lcd.clear();
    lcd.backlight();
    lcd.setCursor(0,0);
    lcd.print(Docente);
    Buzzer();
  }
    else {
    //Serial.println(F("error opening data.txt"));  
    }
    digitalWrite(CS_SD,HIGH); // Disables SD card chip select pin    
     }



    void Buzzer(){
    digitalWrite(buzzer,HIGH);
    digitalWrite (ledrojo, LOW);
    digitalWrite (ledverde, HIGH);
    digitalWrite (ledazul, LOW);
    delay (100);
    digitalWrite(buzzer,LOW);
    delay (100);
    digitalWrite(buzzer,HIGH);  
    delay (100);
    digitalWrite(buzzer,LOW);
    digitalWrite (ledverde, LOW);
    delay(1000);
    lcd.clear();
  }

void BuzzerE(){
    digitalWrite(buzzer,HIGH);
    digitalWrite (ledrojo, HIGH);
    digitalWrite (ledverde, LOW);
    digitalWrite (ledazul, LOW);
    delay (1000);
    digitalWrite(buzzer,LOW);
    digitalWrite (ledrojo, LOW);
    lcd.clear();
}
  void LeerTeclado(){

  TECLA = customKeypad.getKey();   // obtiene tecla presionada y asigna a variable
  if (TECLA){        // comprueba que se haya presionado una tecla
    CLAVE[INDICE] = TECLA;    // almacena en array la tecla presionada
    INDICE++;       // incrementa indice en uno
    //Serial.print(TECLA);    // envia a monitor serial la tecla presionada
    lcd.clear();
    lcd.print(TECLA);
    /*
    lcd.print(CLAVE[0]);
    lcd.setCursor(1,0);
    lcd.print(CLAVE[1]);
    lcd.setCursor(2,0);
    lcd.print(CLAVE[2]);
    lcd.setCursor(3,0);
    lcd.print(CLAVE[3]);
    */
   }

  if(INDICE == 4)       // si ya se almacenaron los 4 digitos
  {
    lcd.clear();
    lcd.print("CODIGO:");
    lcd.setCursor(8,0);
    lcd.print(CLAVE);
    delay(500);
    acierto=false;
    for(int i = 0; i<30; i++){
        if(!strcmp(CLAVE, pgm_read_word(&(USUARIO[i])))){
          acierto=true;
          char arrayBuf[20];  // crea un búfer
          strcpy_P(arrayBuf, pgm_read_word(&(names[i])));
          Docente = arrayBuf;
          DateTime fecha = rtc.now();       // funcion que devuelve fecha y horario en formato
          //Serial.print(F("Hola "));
          //Serial.println(Docente);
          GrabarSdkeypad();//INICIA PROCESO DE ESCRITURA EN LA SD
          delay(30);
           }
          else            // si retorna falso
            //Serial.println(F("Contraseña Incorrecta"));     // muestra texto equivalente a acceso denegado
   
     INDICE = 0;        
   
    }
    if (!acierto)
    {
       //Serial.println(F("No te conozco"));    // muestra texto equivalente a acceso denegado
       lcd.clear();
       lcd.backlight();
       lcd.setCursor(0,0);
       lcd.print("No te conozco");  
       BuzzerE();
       delay(1000);
       lcd.clear();                    
    }
 
  }
  }


  void GrabarSdkeypad(){
  digitalWrite(CS_SD,LOW); // Enables SD card chip select pin
  myFile=SD.open("DATA.txt", FILE_WRITE);
  if (myFile) {
    delay(300);
    //myFile.print(CLAVE);
    //myFile.print(", ");  
    DateTime now = rtc.now();
    myFile.print(now.year(), DEC);
    myFile.print('/');
    myFile.print(now.month(), DEC);
    myFile.print('/');
    myFile.print(now.day(), DEC);
    myFile.print(',');
    myFile.print(now.hour(), DEC);
    myFile.print(':');
    myFile.print(now.minute(), DEC);
    myFile.print(':');
    myFile.print(now.second(), DEC);
    myFile.print(',');
    myFile.print(Docente); //Nomre del docente
    myFile.print(',');
    myFile.println("Acceso mediante teclado numerico");
    //Serial.println(F("sucessfully written on SD card"));
    delay(300);
    myFile.close();
    lcd.clear();
    lcd.backlight();
    lcd.setCursor(0,0);
    lcd.print(Docente);
    Buzzer();
  }
    else {
    //Serial.println(F("error opening data.txt"));
    lcd.clear();
    lcd.backlight();
    lcd.setCursor(0,0);
    lcd.print("error opening data.txt");
    BuzzerE();
    }
    digitalWrite(CS_SD,HIGH); // Disables SD card chip select pin    
     }
 
  void Timbre(){
    lcd.clear();
    lcd.print("TIMBRE ON");
    digitalWrite (rele, HIGH);
    delay(segundosTimbre*1000);
    digitalWrite (rele, LOW);
    lcd.clear();
      }






Comentarios

Entradas populares de este blog

CLASIFICADOR DE COLORES CON SENSOR TCS3472 (I2C) CON ARDUINO NANO

CONTROL DE ACCESO CON RFID YMODULO RTC DS3231