This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm whether you accept or reject these cookies being set.

A cookie will be stored in your browser regardless of choice to prevent you being asked this question again. You will be able to change your cookie settings at any time using the link in the footer.

  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Proyecto cofre abertura mediante RFID
#1
Buenas a tod@s:

Quiero hacer un proyecto que implemente un lector de tarjetas RFID.

Ayer me llegó el lector RFID con un llavero y una tarjeta. Durante esta mañana he probado un ejemplo:


Código:
/**
* ----------------------------------------------------------------------------
* This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
* for further details and other examples.
*
* NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
*
* Released into the public domain.
* ----------------------------------------------------------------------------
* This sample shows how to read and write data blocks on a MIFARE Classic PICC
* (= card/tag).
*
* BEWARE: Data will be written to the PICC, in sector #1 (blocks #4 to #7).
*
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
*             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
*             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
* Signal      Pin          Pin           Pin       Pin        Pin              Pin
* -----------------------------------------------------------------------------------------
* RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
* SPI SS      SDA(SS)      10            53        D10        10               10
* SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
* SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
* SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

MFRC522::MIFARE_Key key;

/**
* Initialize.
*/
void setup() {
    Serial.begin(9600); // Initialize serial communications with the PC
    while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card

    // Prepare the key (used both as key A and as key B)
    // using FFFFFFFFFFFFh which is the default at chip delivery from the factory
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }

    Serial.println(F("Scan a MIFARE Classic PICC to demonstrate read and write."));
    Serial.print(F("Using key (for A and B):"));
    dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
    Serial.println();
    
    Serial.println(F("BEWARE: Data will be written to the PICC, in sector #1"));
}

/**
* Main loop.
*/
void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
        return;

    // Show some details of the PICC (that is: the tag/card)
    Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
    Serial.println();
    Serial.print(F("PICC type: "));
    byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Check for compatibility
    if (    piccType != MFRC522::PICC_TYPE_MIFARE_MINI
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_1K
        &&  piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Serial.println(F("This sample only works with MIFARE Classic cards."));
        return;
    }

    // In this sample we use the second sector,
    // that is: sector #1, covering block #4 up to and including block #7
    byte sector         = 1;
    byte blockAddr      = 4;
    byte dataBlock[]    = {
        0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
        0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
        0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
        0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
    };
    byte trailerBlock   = 7;
    byte status;
    byte buffer[18];
    byte size = sizeof(buffer);

    // Authenticate using key A
    Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Show the whole sector as it currently is
    Serial.println(F("Current data in sector:"));
    mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
    Serial.println();

    // Read data from the block
    Serial.print(F("Reading data from block ")); Serial.print(blockAddr);
    Serial.println(F(" ..."));
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Read() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.print(F("Data in block ")); Serial.print(blockAddr); Serial.println(F(":"));
    dump_byte_array(buffer, 16); Serial.println();
    Serial.println();

    // Authenticate using key B
    Serial.println(F("Authenticating again using key B..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("PCD_Authenticate() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

    // Write data to the block
    Serial.print(F("Writing data into block ")); Serial.print(blockAddr);
    Serial.println(F(" ..."));
    dump_byte_array(dataBlock, 16); Serial.println();
    status = mfrc522.MIFARE_Write(blockAddr, dataBlock, 16);
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Write() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.println();

    // Read data from the block (again, should now be what we have written)
    Serial.print(F("Reading data from block ")); Serial.print(blockAddr);
    Serial.println(F(" ..."));
    status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
    if (status != MFRC522::STATUS_OK) {
        Serial.print(F("MIFARE_Read() failed: "));
        Serial.println(mfrc522.GetStatusCodeName(status));
    }
    Serial.print(F("Data in block ")); Serial.print(blockAddr); Serial.println(F(":"));
    dump_byte_array(buffer, 16); Serial.println();
        
    // Check that data in block is what we have written
    // by counting the number of bytes that are equal
    Serial.println(F("Checking result..."));
    byte count = 0;
    for (byte i = 0; i < 16; i++) {
        // Compare buffer (= what we've read) with dataBlock (= what we've written)
        if (buffer[i] == dataBlock[i])
            count++;
    }
    Serial.print(F("Number of bytes that match = ")); Serial.println(count);
    if (count == 16) {
        Serial.println(F("Success :-)"));
    } else {
        Serial.println(F("Failure, no match :-("));
        Serial.println(F("  perhaps the write didn't work properly..."));
    }
    Serial.println();
        
    // Dump the sector data
    Serial.println(F("Current data in sector:"));
    mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
    Serial.println();

    // Halt PICC
    mfrc522.PICC_HaltA();
    // Stop encryption on PCD
    mfrc522.PCD_StopCrypto1();
}

/**
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

El caso es que quiero modificar ese código para que tan solo me lea la ID de cada dispositivo. Y actue un sero en función de las ID leídas. El caso es que necesito que una variable guarde la ID leída y no sé que tipo de varaiable tendría que escojer para recojer este tipo de datos (ya que mezcla numeros y letras).

Muchas gracias de antemano.
  Responder
#2
Buenas a tod@s:

He estado peleando esta tarde con el código para descubrir como tengo que relacionar una variable con los ID de las tarjetas. Miro de guardar la ID en variables tipo char pero me dice que no está declarado el propio ID de la tarjeta.

Como puedo guardar la constante ID para posteriormente compararlo con la ID leída y que actue consecuentemente???

Muchas gracias.
  Responder
#3
puedes empezar revisando este proyecto. Lo tengo desde hace tiempo en favoritos.... Guiño

http://forum.arduino.cc/index.php?topic=256260

https://github.com/omersiar/RFID522-Door...ock208.ino

Tiene bastante chicha ya que es un proyecto con lectura, grabación, llave maestra etc... pero está muy bien comentado Mola
  Responder
#4
Buenas a tod@s:

Gracias biketrial981 Mola

Ahora le hecho una ojeada :aplauso:
  Responder
#5
Buenas a tod@s:

Al final he declarado las ID como variables tipo char y agrupando el ID entre comillas 'XXXXXXXX'.

Ahora quiero hacer algo del estilo:

if (ID1== 1234ABCD){
Serial.println("ID1");
}
if (ID1!=1234ABCD){
Serial.println("ID2");
}

Pero no me permite hacer dicha comparación :S
  Responder
#6
Me apunto al hilo
  Responder
#7
Buenas a tod@s:

Esta semana he estado trabajando en el proyecto y he conseguido leer las ID de los llaveros y que se encienda un led o mueva un servo.

Aquí os dejo el codigo:

Código:
/**
* ----------------------------------------------------------------------------
* This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
* for further details and other examples.
*
* NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
*
* Released into the public domain.
* ----------------------------------------------------------------------------
* This sample shows how to read and write data blocks on a MIFARE Classic PICC
* (= card/tag).
*
* BEWARE: Data will be written to the PICC, in sector #1 (blocks #4 to #7).
*
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
*             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
*             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
* Signal      Pin          Pin           Pin       Pin        Pin              Pin
* -----------------------------------------------------------------------------------------
* RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
* SPI SS      SDA(SS)      10            53        D10        10               10
* SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
* SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
* SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*
*/

#include <SPI.h>
#include <MFRC522.h>
#include <Servo.h>
#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

byte  targeta[]={0x05,0x9E,0x02,0xB1};
int  codigo = 0;
int val;
int ang;
Servo servo;
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

MFRC522::MIFARE_Key key;

/**
* Initialize.
*/
void setup() {
  servo.attach(5);
  servo.write(0);
  //ang =map(ang, 0, 0, 0, 180); //Posem el màxim i el mínim pel servo
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card

  // Prepare the key (used both as key A and as key B)
  // using FFFFFFFFFFFFh which is the default at chip delivery from the factory
  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("Scan a MIFARE Classic PICC to demonstrate read and write."));
  Serial.print(F("Using key (for A and B):"));
  dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
  Serial.println();

  Serial.println(F("BEWARE: Data will be written to the PICC, in sector #1"));
}

/**
* Main loop.
*/
void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
    return;

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
    return;

  // Show some details of the PICC (that is: the tag/card)
  Serial.print(F("Card UID:"));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  dump_byte_array(targeta, mfrc522.uid.size);

  for(int i= 0; i<mfrc522.uid.size; i++){
    if(targeta[i] == mfrc522.uid.uidByte[i] ) {
      codigo++;
    }

  }

  if(codigo == 4) {
    Serial.println();
    Serial.print("Yuhuuu");    
    codigo = 0;
    ang=ang+2;
    servo.write(ang);
    delay(5);
  }
  else {
    Serial.println();
    Serial.print("Nooooo!!!");      
    codigo = 0;
    servo.write(0);
    delay(5);
  }


return;







  Serial.println();
  Serial.print(F("PICC type: "));
  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  // Check for compatibility
  if (    piccType != MFRC522::PICC_TYPE_MIFARE_MINI
    &&  piccType != MFRC522::PICC_TYPE_MIFARE_1K
    &&  piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("This sample only works with MIFARE Classic cards."));
    return;
  }

  // In this sample we use the second sector,
  // that is: sector #1, covering block #4 up to and including block #7
  byte sector         = 1;
  byte blockAddr      = 4;
  byte dataBlock[]    = {
    0x01, 0x02, 0x03, 0x04, //  1,  2,   3,  4,
    0x05, 0x06, 0x07, 0x08, //  5,  6,   7,  8,
    0x08, 0x09, 0xff, 0x0b, //  9, 10, 255, 12,
    0x0c, 0x0d, 0x0e, 0x0f  // 13, 14,  15, 16
  };
  byte trailerBlock   = 7;
  byte status;
  byte buffer[18];
  byte size = sizeof(buffer);

  // Authenticate using key A
  Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Show the whole sector as it currently is
  Serial.println(F("Current data in sector:"));
  mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
  Serial.println();

  // Read data from the block
  Serial.print(F("Reading data from block "));
  Serial.print(blockAddr);
  Serial.println(F(" ..."));
  status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
  }
  Serial.print(F("Data in block "));
  Serial.print(blockAddr);
  Serial.println(F(":"));
  dump_byte_array(buffer, 16);
  Serial.println();
  Serial.println();

  // Authenticate using key B
  Serial.println(F("Authenticating again using key B..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write data to the block
  Serial.print(F("Writing data into block "));
  Serial.print(blockAddr);
  Serial.println(F(" ..."));
  dump_byte_array(dataBlock, 16);
  Serial.println();
  status = mfrc522.MIFARE_Write(blockAddr, dataBlock, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
  }
  Serial.println();

  // Read data from the block (again, should now be what we have written)
  Serial.print(F("Reading data from block "));
  Serial.print(blockAddr);
  Serial.println(F(" ..."));
  status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
  }
  Serial.print(F("Data in block "));
  Serial.print(blockAddr);
  Serial.println(F(":"));
  dump_byte_array(buffer, 16);
  Serial.println();

  // Check that data in block is what we have written
  // by counting the number of bytes that are equal
  Serial.println(F("Checking result..."));
  byte count = 0;
  for (byte i = 0; i < 16; i++) {
    // Compare buffer (= what we've read) with dataBlock (= what we've written)
    if (buffer[i] == dataBlock[i])
      count++;
  }
  Serial.print(F("Number of bytes that match = "));
  Serial.println(count);
  if (count == 16) {
    Serial.println(F("Success :-)"));
  }
  else {
    Serial.println(F("Failure, no match :-("));
    Serial.println(F("  perhaps the write didn't work properly..."));
  }
  Serial.println();

  // Dump the sector data
  Serial.println(F("Current data in sector:"));
  mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
  Serial.println();

  // Halt PICC
  mfrc522.PICC_HaltA();
  // Stop encryption on PCD
  mfrc522.PCD_StopCrypto1();
}

/**
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

Ahora trabajaré en el código que irá definitivamente en el proyecto. Que cuando lea ambos llaveros un servo se desplaze de 0º a 180º de forma lentamente y cuando deje de detectar uno de los 2, el servo rápidamente se mueva a 0º.

Lo que avance lentamente lo he hecho ya:


Código:
ang=ang+2;
servo.write(ang);
delay(5);

Pero ahora estoy mirando a ver como hago para que cuando deje de detectar uno de los llaveros se ponga a 0 el servo. He probado de ponerlo a 0 cada vez que inicie el loop, el problema es que después es incapaz de moverse a los 180º, con lo cual esa opción queda descartada.

Os iré informando y documentando de los progresos con fotos. Ahora... de momento está todo patas arriba, con lo cual... no es nada presentable para documentarlo. Pero una vez empieze a montarlo, ya os iré documentando el proyecto de forma adecuada con documentación fotográfica.
  Responder
#8
Hola.
Estaba leyendo porque quiero hacerme algo parecido.
Mirar este sitio:
http://duinos.net/show/?id=220
A mi me ha salvado la vida.
Código sencillo y muy fácil de entender y modificar
  Responder
#9
No entiendo muy bien lo que quieres hacer. Pretendes leer la Id de los dos llaveros a la vez...?

Creo que el modulo no es capaz de leer dos Id's a la vez.

Yo tengo hecho un proyecto de control de accesos que almacena las Id's en la memoria Eprom poniendo el arduino en modo grabacion con una tarjeta "master" y libera un rele en caso de que le acerques una tarjeta de las incluidas en la Eprom.
  Responder
#10
Carl0701 escribió:No entiendo muy bien lo que quieres hacer. Pretendes leer la Id de los dos llaveros a la vez...?

Creo que el modulo no es capaz de leer dos Id's a la vez.

Yo tengo hecho un proyecto de control de accesos que almacena las Id's en la memoria Eprom poniendo el arduino en modo grabacion con una tarjeta "master" y libera un rele en caso de que le acerques una tarjeta de las incluidas en la Eprom.


Es lo que quería hacer yo. La diferencia es que en el enlace que pongo hay que poner las tarjetas a mano al programar el arduino.
Creo que tu sistema es mejor, pero la cabeza no me da para mas y no se como hacerlo
  Responder
#11
Carl0701 escribió:No entiendo muy bien lo que quieres hacer. Pretendes leer la Id de los dos llaveros a la vez...?

Creo que el modulo no es capaz de leer dos Id's a la vez.

Yo tengo hecho un proyecto de control de accesos que almacena las Id's en la memoria Eprom poniendo el arduino en modo grabacion con una tarjeta "master" y libera un rele en caso de que le acerques una tarjeta de las incluidas en la Eprom.


Es lo que quería hacer yo. Un control de acceso sencillo.
La diferencia con el tuyo es que en el enlace que pongo, hay que añadir las tarjetas a mano al programar el arduino. Y cada vez que quieras añadir una tarjeta, hay que volver a programar.
Por lo que dices, es mejor tu proyecto, pero mi cabeza no da para tanto.
  Responder
#12
Es lo que quería hacer yo. Un control de acceso sencillo.
La diferencia con el tuyo es que en el enlace que pongo, hay que añadir las tarjetas a mano al programar el arduino. Y cada vez que quieras añadir una tarjeta, hay que volver a programar.
Por lo que dices, es mejor tu proyecto, pero mi cabeza no da para tanto.
  Responder
#13
Esta basado en el proyecto que te comenta mas arriba biketrial891. En cuando tenga un rato te busco la info...
  Responder
#14
Si te fijas en el proyecto del que te hablaba anteriormente http://forum.arduino.cc/index.php?topic=256260.

En https://github.com/omersiar/RFID522-Door-Unlock hay una version de codigo que trabaja con la memoria Eprom, utiliza varios leds de estado para informar sobre el funcionamiento, un boton para borrar completamente la memoria y una tarjeta "master" para dar de alta o de baja las tarjetas. Incluso ofrece un codigo aparte para borrar individualmente una tarjeta (extraviada, por ejemplo) sabiendo su Id.

1.- Primeramente, en el arranque comprueba si esta pulsado el boton que borra la memoria. En caso afirmativo la borra completamente y en caso contrario, continua...

Código:
//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 5 seconds to Cancel"));
    Serial.println(F("This will be remove all records and cannot be undone"));
    delay(5000);                        // 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);
    }
  }

2.- Seguidamente solicita, si no se hizo anteriormente, la creacion de la tarjeta "Master", necesaria para la gestion de altas y bajas de tarjetas:


Código:
if (EEPROM.read(1) != 143) {          
    Serial.println(F("No Master Card Defined"));
    Serial.println(F("Scan A PICC to Define as Master Card"));
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0
      digitalWrite(blueLed, LED_ON);    // Visualize Master Card need to be defined
      delay(200);
      digitalWrite(blueLed, LED_OFF);
      delay(200);
    }
    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"));
  }

Y a partir de ahi queda a la espera de que le acerques las tarjetas o llaveros. En caso de que le presentes la Master, el sistema pasara a modo "Programa" y las proximas tarjetas que acerques las dara de alta o baja segun su estado anterior hasta que vuelvas a presentar la Master.

Ese es el resumen del funcionamiento basico. Luego podrias añadir un LCD para presentar los mensajes o incluso un reloj y un modulo SD para registrar los accesos con fecha y hora en un archivo.

Si necesitas cualquier otra aclaración, avisa...
  Responder
#15
Ya había visto el enlace que dices y me había dado cuenta de que hay un apartado exclusivo de Eeprom.
La verdad es que no entendía el programa, pero con tus explicaciones, voy a intentarlo otra vez (comprenderlo), y aunque solo tengo una tarjeta y un llavero (lo que viene al comprar), intentaré hacerlo. Y si me sale bien, compraré mas llaveros o tarjetas, ya veremos.
Muchas gracias.
  Responder
#16
chemamata escribió:Ya había visto el enlace que dices y me había dado cuenta de que hay un apartado exclusivo de Eeprom.
La verdad es que no entendía el programa, pero con tus explicaciones, voy a intentarlo otra vez (comprenderlo), y aunque solo tengo una tarjeta y un llavero (lo que viene al comprar), intentaré hacerlo. Y si me sale bien, compraré mas llaveros o tarjetas, ya veremos.
Muchas gracias.

Ok. Lo dicho, si necesitas cualquier otra aclaracion, dimelo...
  Responder
#17
Voy a aprovecharme de tu amabilidad.
En la línea 98:

pinMode(wipeB, INPUT_PULLUP); // Enable pin's pull up resistor

es lo mismo que:

pinMode(wipeB, INPUT); digitalWrite(wipeB,HIGH);

Lo que quiere decir que pongo el pin en "alta" y al pulsar el botón lo que hago es conectarlo a negativo y al soltar el botón vuelve a "alta"
¿Estoy en lo cierto?
  Responder
#18
Todo OK.
Una maravilla. Muchas gracias.
Funciona de maravilla.
Es como tu habías dicho .
Primero detecta que no hay tarjeta maestra, la añade y luego da de alta y luego de baja (solo tengo un llavero), pasas otra vez la maestra y activa el relé (modificaré el tiempo) y si reseteas el Nano con el botón apretado, vacía la Eeprom y vuelta a empezar.
Voy a pillarme unos llaveros más
Muchas gracias
  Responder


Posibles temas similares…
Tema Autor Respuestas Vistas Último mensaje
  abertura en abanico jhon_bishop 0 974 17-10-2015, 09:47 PM
Último mensaje: jhon_bishop
  arduino, RFID y android.. pirro1216 5 2,215 01-05-2014, 07:36 PM
Último mensaje: pirro1216
  Primer proyecto propio: Display controlado mediante teclado Electromecánico 5 2,342 11-01-2014, 10:54 AM
Último mensaje: Lepes