Advertisement
Guest User

Untitled

a guest
Sep 21st, 2016
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. * MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
  3. * NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information.
  4. * Released into the public domain.
  5. */
  6.  
  7. #include <Arduino.h>
  8. #include <MFRC522.h>
  9.  
  10. /////////////////////////////////////////////////////////////////////////////////////
  11. // Functions for setting up the Arduino
  12. /////////////////////////////////////////////////////////////////////////////////////
  13. /**
  14.  * Constructor.
  15.  */
  16. MFRC522::MFRC522() {
  17. } // End constructor
  18.  
  19. /**
  20.  * Constructor.
  21.  * Prepares the output pins.
  22.  */
  23. MFRC522::MFRC522(   byte chipSelectPin,     ///< Arduino pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low)
  24.                     byte resetPowerDownPin  ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low)
  25.                 ) {
  26.     _chipSelectPin = chipSelectPin;
  27.     _resetPowerDownPin = resetPowerDownPin;
  28. } // End constructor
  29.  
  30. /////////////////////////////////////////////////////////////////////////////////////
  31. // Basic interface functions for communicating with the MFRC522
  32. /////////////////////////////////////////////////////////////////////////////////////
  33.  
  34. /**
  35.  * Writes a byte to the specified register in the MFRC522 chip.
  36.  * The interface is described in the datasheet section 8.1.2.
  37.  */
  38. void MFRC522::PCD_WriteRegister(    byte reg,       ///< The register to write to. One of the PCD_Register enums.
  39.                                     byte value      ///< The value to write.
  40.                                 ) {
  41.     SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
  42.     digitalWrite(_chipSelectPin, LOW);      // Select slave
  43.     SPI.transfer(reg & 0x7E);               // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
  44.     SPI.transfer(value);
  45.     digitalWrite(_chipSelectPin, HIGH);     // Release slave again
  46.     SPI.endTransaction(); // Stop using the SPI bus
  47. } // End PCD_WriteRegister()
  48.  
  49. /**
  50.  * Writes a number of bytes to the specified register in the MFRC522 chip.
  51.  * The interface is described in the datasheet section 8.1.2.
  52.  */
  53. void MFRC522::PCD_WriteRegister(    byte reg,       ///< The register to write to. One of the PCD_Register enums.
  54.                                     byte count,     ///< The number of bytes to write to the register
  55.                                     byte *values    ///< The values to write. Byte array.
  56.                                 ) {
  57.     SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
  58.     digitalWrite(_chipSelectPin, LOW);      // Select slave
  59.     SPI.transfer(reg & 0x7E);               // MSB == 0 is for writing. LSB is not used in address. Datasheet section 8.1.2.3.
  60.     for (byte index = 0; index < count; index++) {
  61.         SPI.transfer(values[index]);
  62.     }
  63.     digitalWrite(_chipSelectPin, HIGH);     // Release slave again
  64.     SPI.endTransaction(); // Stop using the SPI bus
  65. } // End PCD_WriteRegister()
  66.  
  67. /**
  68.  * Reads a byte from the specified register in the MFRC522 chip.
  69.  * The interface is described in the datasheet section 8.1.2.
  70.  */
  71. byte MFRC522::PCD_ReadRegister( byte reg    ///< The register to read from. One of the PCD_Register enums.
  72.                                 ) {
  73.     byte value;
  74.     SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
  75.     digitalWrite(_chipSelectPin, LOW);          // Select slave
  76.     SPI.transfer(0x80 | (reg & 0x7E));          // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
  77.     value = SPI.transfer(0);                    // Read the value back. Send 0 to stop reading.
  78.     digitalWrite(_chipSelectPin, HIGH);         // Release slave again
  79.     SPI.endTransaction(); // Stop using the SPI bus
  80.     return value;
  81. } // End PCD_ReadRegister()
  82.  
  83. /**
  84.  * Reads a number of bytes from the specified register in the MFRC522 chip.
  85.  * The interface is described in the datasheet section 8.1.2.
  86.  */
  87. void MFRC522::PCD_ReadRegister( byte reg,       ///< The register to read from. One of the PCD_Register enums.
  88.                                 byte count,     ///< The number of bytes to read
  89.                                 byte *values,   ///< Byte array to store the values in.
  90.                                 byte rxAlign    ///< Only bit positions rxAlign..7 in values[0] are updated.
  91.                                 ) {
  92.     if (count == 0) {
  93.         return;
  94.     }
  95.     //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
  96.     byte address = 0x80 | (reg & 0x7E);     // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
  97.     byte index = 0;                         // Index in values array.
  98.     SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
  99.     digitalWrite(_chipSelectPin, LOW);      // Select slave
  100.     count--;                                // One read is performed outside of the loop
  101.     SPI.transfer(address);                  // Tell MFRC522 which address we want to read
  102.     while (index < count) {
  103.         if (index == 0 && rxAlign) {        // Only update bit positions rxAlign..7 in values[0]
  104.             // Create bit mask for bit positions rxAlign..7
  105.             byte mask = 0;
  106.             for (byte i = rxAlign; i <= 7; i++) {
  107.                 mask |= (1 << i);
  108.             }
  109.             // Read value and tell that we want to read the same address again.
  110.             byte value = SPI.transfer(address);
  111.             // Apply mask to both current value of values[0] and the new data in value.
  112.             values[0] = (values[index] & ~mask) | (value & mask);
  113.         }
  114.         else { // Normal case
  115.             values[index] = SPI.transfer(address)// Read value and tell that we want to read the same address again.
  116.         }
  117.         index++;
  118.     }
  119.     values[index] = SPI.transfer(0);            // Read the final byte. Send 0 to stop reading.
  120.     digitalWrite(_chipSelectPin, HIGH);         // Release slave again
  121.     SPI.endTransaction(); // Stop using the SPI bus
  122. } // End PCD_ReadRegister()
  123.  
  124. /**
  125.  * Sets the bits given in mask in register reg.
  126.  */
  127. void MFRC522::PCD_SetRegisterBitMask(   byte reg,   ///< The register to update. One of the PCD_Register enums.
  128.                                         byte mask   ///< The bits to set.
  129.                                     ) {
  130.     byte tmp;
  131.     tmp = PCD_ReadRegister(reg);
  132.     PCD_WriteRegister(reg, tmp | mask);         // set bit mask
  133. } // End PCD_SetRegisterBitMask()
  134.  
  135. /**
  136.  * Clears the bits given in mask from register reg.
  137.  */
  138. void MFRC522::PCD_ClearRegisterBitMask( byte reg,   ///< The register to update. One of the PCD_Register enums.
  139.                                         byte mask   ///< The bits to clear.
  140.                                       ) {
  141.     byte tmp;
  142.     tmp = PCD_ReadRegister(reg);
  143.     PCD_WriteRegister(reg, tmp & (~mask));      // clear bit mask
  144. } // End PCD_ClearRegisterBitMask()
  145.  
  146.  
  147. /**
  148.  * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
  149.  *
  150.  * @return STATUS_OK on success, STATUS_??? otherwise.
  151.  */
  152. MFRC522::StatusCode MFRC522::PCD_CalculateCRC(  byte *data,     ///< In: Pointer to the data to transfer to the FIFO for CRC calculation.
  153.                                                 byte length,    ///< In: The number of bytes to transfer.
  154.                                                 byte *result    ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first.
  155.                      ) {
  156.     PCD_WriteRegister(CommandReg, PCD_Idle);        // Stop any active command.
  157.     PCD_WriteRegister(DivIrqReg, 0x04);             // Clear the CRCIRq interrupt request bit
  158.     PCD_SetRegisterBitMask(FIFOLevelReg, 0x80);     // FlushBuffer = 1, FIFO initialization
  159.     PCD_WriteRegister(FIFODataReg, length, data);   // Write data to the FIFO
  160.     PCD_WriteRegister(CommandReg, PCD_CalcCRC);     // Start the calculation
  161.    
  162.     // Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73�s.
  163.     word i = 5000;
  164.     byte n;
  165.     while (1) {
  166.         n = PCD_ReadRegister(DivIrqReg);    // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
  167.         if (n & 0x04) {                     // CRCIRq bit set - calculation done
  168.             break;
  169.         }
  170.         if (--i == 0) {                     // The emergency break. We will eventually terminate on this one after 89ms. Communication with the MFRC522 might be down.
  171.             return STATUS_TIMEOUT;
  172.         }
  173.     }
  174.     PCD_WriteRegister(CommandReg, PCD_Idle);        // Stop calculating CRC for new content in the FIFO.
  175.    
  176.     // Transfer the result from the registers to the result buffer
  177.     result[0] = PCD_ReadRegister(CRCResultRegL);
  178.     result[1] = PCD_ReadRegister(CRCResultRegH);
  179.     return STATUS_OK;
  180. } // End PCD_CalculateCRC()
  181.  
  182.  
  183. /////////////////////////////////////////////////////////////////////////////////////
  184. // Functions for manipulating the MFRC522
  185. /////////////////////////////////////////////////////////////////////////////////////
  186.  
  187. /**
  188.  * Initializes the MFRC522 chip.
  189.  */
  190. void MFRC522::PCD_Init() {
  191.     // Set the chipSelectPin as digital output, do not select the slave yet
  192.     pinMode(_chipSelectPin, OUTPUT);
  193.     digitalWrite(_chipSelectPin, HIGH);
  194.    
  195.     // Set the resetPowerDownPin as digital output, do not reset or power down.
  196.     pinMode(_resetPowerDownPin, OUTPUT);
  197.    
  198.     if (digitalRead(_resetPowerDownPin) == LOW) {   //The MFRC522 chip is in power down mode.
  199.         digitalWrite(_resetPowerDownPin, HIGH);     // Exit power down mode. This triggers a hard reset.
  200.         // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms.
  201.         delay(38);
  202.     }
  203.     else { // Perform a soft reset
  204.         PCD_Reset();
  205.     }
  206.    
  207.     // When communicating with a PICC we need a timeout if something goes wrong.
  208.     // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo].
  209.     // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg.
  210.     PCD_WriteRegister(TModeReg, 0x80);          // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds
  211.     PCD_WriteRegister(TPrescalerReg, 0xA9);     // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25�s.
  212.     PCD_WriteRegister(TReloadRegH, 0x03);       // Reload timer with 0x3E8 = 1000, ie 25ms before timeout.
  213.     PCD_WriteRegister(TReloadRegL, 0xE8);
  214.    
  215.     PCD_WriteRegister(TxASKReg, 0x40);      // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting
  216.     PCD_WriteRegister(ModeReg, 0x3D);       // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4)
  217.     PCD_AntennaOn();                        // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset)
  218. } // End PCD_Init()
  219.  
  220. /**
  221.  * Initializes the MFRC522 chip.
  222.  */
  223. void MFRC522::PCD_Init( byte chipSelectPin,     ///< Arduino pin connected to MFRC522's SPI slave select input (Pin 24, NSS, active low)
  224.                         byte resetPowerDownPin  ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low)
  225.                     ) {
  226.     _chipSelectPin = chipSelectPin;
  227.     _resetPowerDownPin = resetPowerDownPin;
  228.     // Set the chipSelectPin as digital output, do not select the slave yet
  229.     PCD_Init();
  230. } // End PCD_Init()
  231.  
  232. /**
  233.  * Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
  234.  */
  235. void MFRC522::PCD_Reset() {
  236.     PCD_WriteRegister(CommandReg, PCD_SoftReset);   // Issue the SoftReset command.
  237.     // The datasheet does not mention how long the SoftRest command takes to complete.
  238.     // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg)
  239.     // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms.
  240.     delay(38);
  241.     // Wait for the PowerDown bit in CommandReg to be cleared
  242.     while (PCD_ReadRegister(CommandReg) & (1<<4)) {
  243.         // PCD still restarting - unlikely after waiting 50ms, but better safe than sorry.
  244.     }
  245. } // End PCD_Reset()
  246.  
  247. /**
  248.  * Turns the antenna on by enabling pins TX1 and TX2.
  249.  * After a reset these pins are disabled.
  250.  */
  251. void MFRC522::PCD_AntennaOn() {
  252.     byte value = PCD_ReadRegister(TxControlReg);
  253.     if ((value & 0x03) != 0x03) {
  254.         PCD_WriteRegister(TxControlReg, value | 0x03);
  255.     }
  256. } // End PCD_AntennaOn()
  257.  
  258. /**
  259.  * Turns the antenna off by disabling pins TX1 and TX2.
  260.  */
  261. void MFRC522::PCD_AntennaOff() {
  262.     PCD_ClearRegisterBitMask(TxControlReg, 0x03);
  263. } // End PCD_AntennaOff()
  264.  
  265. /**
  266.  * Get the current MFRC522 Receiver Gain (RxGain[2:0]) value.
  267.  * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
  268.  * NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
  269.  *
  270.  * @return Value of the RxGain, scrubbed to the 3 bits used.
  271.  */
  272. byte MFRC522::PCD_GetAntennaGain() {
  273.     return PCD_ReadRegister(RFCfgReg) & (0x07<<4);
  274. } // End PCD_GetAntennaGain()
  275.  
  276. /**
  277.  * Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask.
  278.  * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
  279.  * NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits.
  280.  */
  281. void MFRC522::PCD_SetAntennaGain(byte mask) {
  282.     if (PCD_GetAntennaGain() != mask) {                     // only bother if there is a change
  283.         PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4));      // clear needed to allow 000 pattern
  284.         PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits
  285.     }
  286. } // End PCD_SetAntennaGain()
  287.  
  288. /**
  289.  * Performs a self-test of the MFRC522
  290.  * See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf
  291.  *
  292.  * @return Whether or not the test passed. Or false if no firmware reference is available.
  293.  */
  294. bool MFRC522::PCD_PerformSelfTest() {
  295.     // This follows directly the steps outlined in 16.1.1
  296.     // 1. Perform a soft reset.
  297.     PCD_Reset();
  298.    
  299.     // 2. Clear the internal buffer by writing 25 bytes of 00h
  300.     byte ZEROES[25] = {0x00};
  301.     PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // flush the FIFO buffer
  302.     PCD_WriteRegister(FIFODataReg, 25, ZEROES); // write 25 bytes of 00h to FIFO
  303.     PCD_WriteRegister(CommandReg, PCD_Mem);     // transfer to internal buffer
  304.    
  305.     // 3. Enable self-test
  306.     PCD_WriteRegister(AutoTestReg, 0x09);
  307.    
  308.     // 4. Write 00h to FIFO buffer
  309.     PCD_WriteRegister(FIFODataReg, 0x00);
  310.    
  311.     // 5. Start self-test by issuing the CalcCRC command
  312.     PCD_WriteRegister(CommandReg, PCD_CalcCRC);
  313.    
  314.     // 6. Wait for self-test to complete
  315.     word i;
  316.     byte n;
  317.     for (i = 0; i < 0xFF; i++) {
  318.         n = PCD_ReadRegister(DivIrqReg);    // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved
  319.         if (n & 0x04) {                     // CRCIRq bit set - calculation done
  320.             break;
  321.         }
  322.     }
  323.     PCD_WriteRegister(CommandReg, PCD_Idle);        // Stop calculating CRC for new content in the FIFO.
  324.    
  325.     // 7. Read out resulting 64 bytes from the FIFO buffer.
  326.     byte result[64];
  327.     PCD_ReadRegister(FIFODataReg, 64, result, 0);
  328.    
  329.     // Auto self-test done
  330.     // Reset AutoTestReg register to be 0 again. Required for normal operation.
  331.     PCD_WriteRegister(AutoTestReg, 0x00);
  332.    
  333.     // Determine firmware version (see section 9.3.4.8 in spec)
  334.     byte version = PCD_ReadRegister(VersionReg);
  335.    
  336.     // Pick the appropriate reference values
  337.     const byte *reference;
  338.     switch (version) {
  339.         case 0x88:  // Fudan Semiconductor FM17522 clone
  340.             reference = FM17522_firmware_reference;
  341.             break;
  342.         case 0x90:  // Version 0.0
  343.             reference = MFRC522_firmware_referenceV0_0;
  344.             break;
  345.         case 0x91:  // Version 1.0
  346.             reference = MFRC522_firmware_referenceV1_0;
  347.             break;
  348.         case 0x92:  // Version 2.0
  349.             reference = MFRC522_firmware_referenceV2_0;
  350.             break;
  351.         default:    // Unknown version
  352.             return false; // abort test
  353.     }
  354.    
  355.     // Verify that the results match up to our expectations
  356.     for (i = 0; i < 64; i++) {
  357.         if (result[i] != pgm_read_byte(&(reference[i]))) {
  358.             return false;
  359.         }
  360.     }
  361.    
  362.     // Test passed; all is good.
  363.     return true;
  364. } // End PCD_PerformSelfTest()
  365.  
  366. /////////////////////////////////////////////////////////////////////////////////////
  367. // Functions for communicating with PICCs
  368. /////////////////////////////////////////////////////////////////////////////////////
  369.  
  370. /**
  371.  * Executes the Transceive command.
  372.  * CRC validation can only be done if backData and backLen are specified.
  373.  *
  374.  * @return STATUS_OK on success, STATUS_??? otherwise.
  375.  */
  376. MFRC522::StatusCode MFRC522::PCD_TransceiveData(    byte *sendData,     ///< Pointer to the data to transfer to the FIFO.
  377.                                                     byte sendLen,       ///< Number of bytes to transfer to the FIFO.
  378.                                                     byte *backData,     ///< NULL or pointer to buffer if data should be read back after executing the command.
  379.                                                     byte *backLen,      ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
  380.                                                     byte *validBits,    ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL.
  381.                                                     byte rxAlign,       ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
  382.                                                     bool checkCRC       ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
  383.                                  ) {
  384.     byte waitIRq = 0x30;        // RxIRq and IdleIRq
  385.     return PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC);
  386. } // End PCD_TransceiveData()
  387.  
  388. /**
  389.  * Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO.
  390.  * CRC validation can only be done if backData and backLen are specified.
  391.  *
  392.  * @return STATUS_OK on success, STATUS_??? otherwise.
  393.  */
  394. MFRC522::StatusCode MFRC522::PCD_CommunicateWithPICC(   byte command,       ///< The command to execute. One of the PCD_Command enums.
  395.                                                         byte waitIRq,       ///< The bits in the ComIrqReg register that signals successful completion of the command.
  396.                                                         byte *sendData,     ///< Pointer to the data to transfer to the FIFO.
  397.                                                         byte sendLen,       ///< Number of bytes to transfer to the FIFO.
  398.                                                         byte *backData,     ///< NULL or pointer to buffer if data should be read back after executing the command.
  399.                                                         byte *backLen,      ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned.
  400.                                                         byte *validBits,    ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits.
  401.                                                         byte rxAlign,       ///< In: Defines the bit position in backData[0] for the first bit received. Default 0.
  402.                                                         bool checkCRC       ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
  403.                                      ) {
  404.     byte n, _validBits;
  405.     unsigned int i;
  406.    
  407.     // Prepare values for BitFramingReg
  408.     byte txLastBits = validBits ? *validBits : 0;
  409.     byte bitFraming = (rxAlign << 4) + txLastBits;      // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
  410.    
  411.     PCD_WriteRegister(CommandReg, PCD_Idle);            // Stop any active command.
  412.     PCD_WriteRegister(ComIrqReg, 0x7F);                 // Clear all seven interrupt request bits
  413.     PCD_SetRegisterBitMask(FIFOLevelReg, 0x80);         // FlushBuffer = 1, FIFO initialization
  414.     PCD_WriteRegister(FIFODataReg, sendLen, sendData)// Write sendData to the FIFO
  415.     PCD_WriteRegister(BitFramingReg, bitFraming);       // Bit adjustments
  416.     PCD_WriteRegister(CommandReg, command);             // Execute the command
  417.     if (command == PCD_Transceive) {
  418.         PCD_SetRegisterBitMask(BitFramingReg, 0x80);    // StartSend=1, transmission of data starts
  419.     }
  420.    
  421.     // Wait for the command to complete.
  422.     // In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting.
  423.     // Each iteration of the do-while-loop takes 17.86�s.
  424.     i = 2000;
  425.     while (1) {
  426.         n = PCD_ReadRegister(ComIrqReg);    // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq
  427.         if (n & waitIRq) {                  // One of the interrupts that signal success has been set.
  428.             break;
  429.         }
  430.         if (n & 0x01) {                     // Timer interrupt - nothing received in 25ms
  431.             return STATUS_TIMEOUT;
  432.         }
  433.         if (--i == 0) {                     // The emergency break. If all other conditions fail we will eventually terminate on this one after 35.7ms. Communication with the MFRC522 might be down.
  434.             return STATUS_TIMEOUT;
  435.         }
  436.     }
  437.    
  438.     // Stop now if any errors except collisions were detected.
  439.     byte errorRegValue = PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr
  440.     if (errorRegValue & 0x13) {  // BufferOvfl ParityErr ProtocolErr
  441.         return STATUS_ERROR;
  442.     }  
  443.  
  444.     // If the caller wants data back, get it from the MFRC522.
  445.     if (backData && backLen) {
  446.         n = PCD_ReadRegister(FIFOLevelReg);         // Number of bytes in the FIFO
  447.         if (n > *backLen) {
  448.             return STATUS_NO_ROOM;
  449.         }
  450.         *backLen = n;                                           // Number of bytes returned
  451.         PCD_ReadRegister(FIFODataReg, n, backData, rxAlign);    // Get received data from FIFO
  452.         _validBits = PCD_ReadRegister(ControlReg) & 0x07;       // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid.
  453.         if (validBits) {
  454.             *validBits = _validBits;
  455.         }
  456.     }
  457.    
  458.     // Tell about collisions
  459.     if (errorRegValue & 0x08) {     // CollErr
  460.         return STATUS_COLLISION;
  461.     }
  462.    
  463.     // Perform CRC_A validation if requested.
  464.     if (backData && backLen && checkCRC) {
  465.         // In this case a MIFARE Classic NAK is not OK.
  466.         if (*backLen == 1 && _validBits == 4) {
  467.             return STATUS_MIFARE_NACK;
  468.         }
  469.         // We need at least the CRC_A value and all 8 bits of the last byte must be received.
  470.         if (*backLen < 2 || _validBits != 0) {
  471.             return STATUS_CRC_WRONG;
  472.         }
  473.         // Verify CRC_A - do our own calculation and store the control in controlBuffer.
  474.         byte controlBuffer[2];
  475.         MFRC522::StatusCode status = PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]);
  476.         if (status != STATUS_OK) {
  477.             return status;
  478.         }
  479.         if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) {
  480.             return STATUS_CRC_WRONG;
  481.         }
  482.     }
  483.    
  484.     return STATUS_OK;
  485. } // End PCD_CommunicateWithPICC()
  486.  
  487. /**
  488.  * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
  489.  * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
  490.  *
  491.  * @return STATUS_OK on success, STATUS_??? otherwise.
  492.  */
  493. MFRC522::StatusCode MFRC522::PICC_RequestA( byte *bufferATQA,   ///< The buffer to store the ATQA (Answer to request) in
  494.                                             byte *bufferSize    ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
  495.                                         ) {
  496.     return PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize);
  497. } // End PICC_RequestA()
  498.  
  499. /**
  500.  * Transmits a Wake-UP command, Type A. Invites PICCs in state IDLE and HALT to go to READY(*) and prepare for anticollision or selection. 7 bit frame.
  501.  * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
  502.  *
  503.  * @return STATUS_OK on success, STATUS_??? otherwise.
  504.  */
  505. MFRC522::StatusCode MFRC522::PICC_WakeupA(  byte *bufferATQA,   ///< The buffer to store the ATQA (Answer to request) in
  506.                                             byte *bufferSize    ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
  507.                                         ) {
  508.     return PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize);
  509. } // End PICC_WakeupA()
  510.  
  511. /**
  512.  * Transmits REQA or WUPA commands.
  513.  * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
  514.  *
  515.  * @return STATUS_OK on success, STATUS_??? otherwise.
  516.  */
  517. MFRC522::StatusCode MFRC522::PICC_REQA_or_WUPA( byte command,       ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA
  518.                                                 byte *bufferATQA,   ///< The buffer to store the ATQA (Answer to request) in
  519.                                                 byte *bufferSize    ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
  520.                                             ) {
  521.     byte validBits;
  522.     MFRC522::StatusCode status;
  523.    
  524.     if (bufferATQA == NULL || *bufferSize < 2) {    // The ATQA response is 2 bytes long.
  525.         return STATUS_NO_ROOM;
  526.     }
  527.     PCD_ClearRegisterBitMask(CollReg, 0x80);        // ValuesAfterColl=1 => Bits received after collision are cleared.
  528.     validBits = 7;                                  // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0]
  529.     status = PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits);
  530.     if (status != STATUS_OK) {
  531.         return status;
  532.     }
  533.     if (*bufferSize != 2 || validBits != 0) {       // ATQA must be exactly 16 bits.
  534.         return STATUS_ERROR;
  535.     }
  536.     return STATUS_OK;
  537. } // End PICC_REQA_or_WUPA()
  538.  
  539. /**
  540.  * Transmits SELECT/ANTICOLLISION commands to select a single PICC.
  541.  * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA().
  542.  * On success:
  543.  *      - The chosen PICC is in state ACTIVE(*) and all other PICCs have returned to state IDLE/HALT. (Figure 7 of the ISO/IEC 14443-3 draft.)
  544.  *      - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
  545.  *
  546.  * A PICC UID consists of 4, 7 or 10 bytes.
  547.  * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
  548.  *      UID size    Number of UID bytes     Cascade levels      Example of PICC
  549.  *      ========    ===================     ==============      ===============
  550.  *      single               4                      1               MIFARE Classic
  551.  *      double               7                      2               MIFARE Ultralight
  552.  *      triple              10                      3               Not currently in use?
  553.  *
  554.  * @return STATUS_OK on success, STATUS_??? otherwise.
  555.  */
  556. MFRC522::StatusCode MFRC522::PICC_Select(   Uid *uid,           ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
  557.                                             byte validBits      ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
  558.                                          ) {
  559.     bool uidComplete;
  560.     bool selectDone;
  561.     bool useCascadeTag;
  562.     byte cascadeLevel = 1;
  563.     MFRC522::StatusCode result;
  564.     byte count;
  565.     byte index;
  566.     byte uidIndex;                  // The first index in uid->uidByte[] that is used in the current Cascade Level.
  567.     int8_t currentLevelKnownBits;       // The number of known UID bits in the current Cascade Level.
  568.     byte buffer[9];                 // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A
  569.     byte bufferUsed;                // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO.
  570.     byte rxAlign;                   // Used in BitFramingReg. Defines the bit position for the first bit received.
  571.     byte txLastBits;                // Used in BitFramingReg. The number of valid bits in the last transmitted byte.
  572.     byte *responseBuffer;
  573.     byte responseLength;
  574.    
  575.     // Description of buffer structure:
  576.     //      Byte 0: SEL                 Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3
  577.     //      Byte 1: NVB                 Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits.
  578.     //      Byte 2: UID-data or CT      See explanation below. CT means Cascade Tag.
  579.     //      Byte 3: UID-data
  580.     //      Byte 4: UID-data
  581.     //      Byte 5: UID-data
  582.     //      Byte 6: BCC                 Block Check Character - XOR of bytes 2-5
  583.     //      Byte 7: CRC_A
  584.     //      Byte 8: CRC_A
  585.     // The BCC and CRC_A are only transmitted if we know all the UID bits of the current Cascade Level.
  586.     //
  587.     // Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels)
  588.     //      UID size    Cascade level   Byte2   Byte3   Byte4   Byte5
  589.     //      ========    =============   =====   =====   =====   =====
  590.     //       4 bytes        1           uid0    uid1    uid2    uid3
  591.     //       7 bytes        1           CT      uid0    uid1    uid2
  592.     //                      2           uid3    uid4    uid5    uid6
  593.     //      10 bytes        1           CT      uid0    uid1    uid2
  594.     //                      2           CT      uid3    uid4    uid5
  595.     //                      3           uid6    uid7    uid8    uid9
  596.    
  597.     // Sanity checks
  598.     if (validBits > 80) {
  599.         return STATUS_INVALID;
  600.     }
  601.    
  602.     // Prepare MFRC522
  603.     PCD_ClearRegisterBitMask(CollReg, 0x80);        // ValuesAfterColl=1 => Bits received after collision are cleared.
  604.    
  605.     // Repeat Cascade Level loop until we have a complete UID.
  606.     uidComplete = false;
  607.     while (!uidComplete) {
  608.         // Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2.
  609.         switch (cascadeLevel) {
  610.             case 1:
  611.                 buffer[0] = PICC_CMD_SEL_CL1;
  612.                 uidIndex = 0;
  613.                 useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes
  614.                 break;
  615.            
  616.             case 2:
  617.                 buffer[0] = PICC_CMD_SEL_CL2;
  618.                 uidIndex = 3;
  619.                 useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes
  620.                 break;
  621.            
  622.             case 3:
  623.                 buffer[0] = PICC_CMD_SEL_CL3;
  624.                 uidIndex = 6;
  625.                 useCascadeTag = false;                      // Never used in CL3.
  626.                 break;
  627.            
  628.             default:
  629.                 return STATUS_INTERNAL_ERROR;
  630.                 break;
  631.         }
  632.        
  633.         // How many UID bits are known in this Cascade Level?
  634.         currentLevelKnownBits = validBits - (8 * uidIndex);
  635.         if (currentLevelKnownBits < 0) {
  636.             currentLevelKnownBits = 0;
  637.         }
  638.         // Copy the known bits from uid->uidByte[] to buffer[]
  639.         index = 2; // destination index in buffer[]
  640.         if (useCascadeTag) {
  641.             buffer[index++] = PICC_CMD_CT;
  642.         }
  643.         byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level.
  644.         if (bytesToCopy) {
  645.             byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag
  646.             if (bytesToCopy > maxBytes) {
  647.                 bytesToCopy = maxBytes;
  648.             }
  649.             for (count = 0; count < bytesToCopy; count++) {
  650.                 buffer[index++] = uid->uidByte[uidIndex + count];
  651.             }
  652.         }
  653.         // Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits
  654.         if (useCascadeTag) {
  655.             currentLevelKnownBits += 8;
  656.         }
  657.        
  658.         // Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations.
  659.         selectDone = false;
  660.         while (!selectDone) {
  661.             // Find out how many bits and bytes to send and receive.
  662.             if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT.
  663.                 //Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
  664.                 buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes
  665.                 // Calculate BCC - Block Check Character
  666.                 buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5];
  667.                 // Calculate CRC_A
  668.                 result = PCD_CalculateCRC(buffer, 7, &buffer[7]);
  669.                 if (result != STATUS_OK) {
  670.                     return result;
  671.                 }
  672.                 txLastBits      = 0; // 0 => All 8 bits are valid.
  673.                 bufferUsed      = 9;
  674.                 // Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx)
  675.                 responseBuffer  = &buffer[6];
  676.                 responseLength  = 3;
  677.             }
  678.             else { // This is an ANTICOLLISION.
  679.                 //Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC);
  680.                 txLastBits      = currentLevelKnownBits % 8;
  681.                 count           = currentLevelKnownBits / 8;    // Number of whole bytes in the UID part.
  682.                 index           = 2 + count;                    // Number of whole bytes: SEL + NVB + UIDs
  683.                 buffer[1]       = (index << 4) + txLastBits;    // NVB - Number of Valid Bits
  684.                 bufferUsed      = index + (txLastBits ? 1 : 0);
  685.                 // Store response in the unused part of buffer
  686.                 responseBuffer  = &buffer[index];
  687.                 responseLength  = sizeof(buffer) - index;
  688.             }
  689.            
  690.             // Set bit adjustments
  691.             rxAlign = txLastBits;                                           // Having a separate variable is overkill. But it makes the next line easier to read.
  692.             PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits)// RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0]
  693.            
  694.             // Transmit the buffer and receive the response.
  695.             result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign);
  696.             if (result == STATUS_COLLISION) { // More than one PICC in the field => collision.
  697.                 byte valueOfCollReg = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0]
  698.                 if (valueOfCollReg & 0x20) { // CollPosNotValid
  699.                     return STATUS_COLLISION; // Without a valid collision position we cannot continue
  700.                 }
  701.                 byte collisionPos = valueOfCollReg & 0x1F; // Values 0-31, 0 means bit 32.
  702.                 if (collisionPos == 0) {
  703.                     collisionPos = 32;
  704.                 }
  705.                 if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen
  706.                     return STATUS_INTERNAL_ERROR;
  707.                 }
  708.                 // Choose the PICC with the bit set.
  709.                 currentLevelKnownBits = collisionPos;
  710.                 count           = (currentLevelKnownBits - 1) % 8; // The bit to modify
  711.                 index           = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0.
  712.                 buffer[index]   |= (1 << count);
  713.             }
  714.             else if (result != STATUS_OK) {
  715.                 return result;
  716.             }
  717.             else { // STATUS_OK
  718.                 if (currentLevelKnownBits >= 32) { // This was a SELECT.
  719.                     selectDone = true; // No more anticollision
  720.                     // We continue below outside the while.
  721.                 }
  722.                 else { // This was an ANTICOLLISION.
  723.                     // We now have all 32 bits of the UID in this Cascade Level
  724.                     currentLevelKnownBits = 32;
  725.                     // Run loop again to do the SELECT.
  726.                 }
  727.             }
  728.         } // End of while (!selectDone)
  729.        
  730.         // We do not check the CBB - it was constructed by us above.
  731.        
  732.         // Copy the found UID bytes from buffer[] to uid->uidByte[]
  733.         index           = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[]
  734.         bytesToCopy     = (buffer[2] == PICC_CMD_CT) ? 3 : 4;
  735.         for (count = 0; count < bytesToCopy; count++) {
  736.             uid->uidByte[uidIndex + count] = buffer[index++];
  737.         }
  738.        
  739.         // Check response SAK (Select Acknowledge)
  740.         if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A).
  741.             return STATUS_ERROR;
  742.         }
  743.         // Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore.
  744.         result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]);
  745.         if (result != STATUS_OK) {
  746.             return result;
  747.         }
  748.         if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) {
  749.             return STATUS_CRC_WRONG;
  750.         }
  751.         if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes
  752.             cascadeLevel++;
  753.         }
  754.         else {
  755.             uidComplete = true;
  756.             uid->sak = responseBuffer[0];
  757.         }
  758.     } // End of while (!uidComplete)
  759.    
  760.     // Set correct uid->size
  761.     uid->size = 3 * cascadeLevel + 1;
  762.    
  763.     return STATUS_OK;
  764. } // End PICC_Select()
  765.  
  766. /**
  767.  * Instructs a PICC in state ACTIVE(*) to go to state HALT.
  768.  *
  769.  * @return STATUS_OK on success, STATUS_??? otherwise.
  770.  */
  771. MFRC522::StatusCode MFRC522::PICC_HaltA() {
  772.     MFRC522::StatusCode result;
  773.     byte buffer[4];
  774.    
  775.     // Build command buffer
  776.     buffer[0] = PICC_CMD_HLTA;
  777.     buffer[1] = 0;
  778.     // Calculate CRC_A
  779.     result = PCD_CalculateCRC(buffer, 2, &buffer[2]);
  780.     if (result != STATUS_OK) {
  781.         return result;
  782.     }
  783.    
  784.     // Send the command.
  785.     // The standard says:
  786.     //      If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the
  787.     //      HLTA command, this response shall be interpreted as 'not acknowledge'.
  788.     // We interpret that this way: Only STATUS_TIMEOUT is a success.
  789.     result = PCD_TransceiveData(buffer, sizeof(buffer), NULL, 0);
  790.     if (result == STATUS_TIMEOUT) {
  791.         return STATUS_OK;
  792.     }
  793.     if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-)
  794.         return STATUS_ERROR;
  795.     }
  796.     return result;
  797. } // End PICC_HaltA()
  798.  
  799.  
  800. /////////////////////////////////////////////////////////////////////////////////////
  801. // Functions for communicating with MIFARE PICCs
  802. /////////////////////////////////////////////////////////////////////////////////////
  803.  
  804. /**
  805.  * Executes the MFRC522 MFAuthent command.
  806.  * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card.
  807.  * The authentication is described in the MFRC522 datasheet section 10.3.1.9 and http://www.nxp.com/documents/data_sheet/MF1S503x.pdf section 10.1.
  808.  * For use with MIFARE Classic PICCs.
  809.  * The PICC must be selected - ie in state ACTIVE(*) - before calling this function.
  810.  * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start.
  811.  *
  812.  * All keys are set to FFFFFFFFFFFFh at chip delivery.
  813.  *
  814.  * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key.
  815.  */
  816. MFRC522::StatusCode MFRC522::PCD_Authenticate(byte command,     ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B
  817.                                             byte blockAddr,     ///< The block number. See numbering in the comments in the .h file.
  818.                                             MIFARE_Key *key,    ///< Pointer to the Crypteo1 key to use (6 bytes)
  819.                                             Uid *uid            ///< Pointer to Uid struct. The first 4 bytes of the UID is used.
  820.                                             ) {
  821.     byte waitIRq = 0x10;        // IdleIRq
  822.    
  823.     // Build command buffer
  824.     byte sendData[12];
  825.     sendData[0] = command;
  826.     sendData[1] = blockAddr;
  827.     for (byte i = 0; i < MF_KEY_SIZE; i++) {    // 6 key bytes
  828.         sendData[2+i] = key->keyByte[i];
  829.     }
  830.     for (byte i = 0; i < 4; i++) {              // The first 4 bytes of the UID
  831.         sendData[8+i] = uid->uidByte[i];
  832.     }
  833.    
  834.     // Start the authentication.
  835.     return PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData));
  836. } // End PCD_Authenticate()
  837.  
  838. /**
  839.  * Used to exit the PCD from its authenticated state.
  840.  * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start.
  841.  */
  842. void MFRC522::PCD_StopCrypto1() {
  843.     // Clear MFCrypto1On bit
  844.     PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0]
  845. } // End PCD_StopCrypto1()
  846.  
  847. /**
  848.  * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC.
  849.  *
  850.  * For MIFARE Classic the sector containing the block must be authenticated before calling this function.
  851.  *
  852.  * For MIFARE Ultralight only addresses 00h to 0Fh are decoded.
  853.  * The MF0ICU1 returns a NAK for higher addresses.
  854.  * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument.
  855.  * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned.
  856.  * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned.
  857.  *
  858.  * The buffer must be at least 18 bytes because a CRC_A is also returned.
  859.  * Checks the CRC_A before returning STATUS_OK.
  860.  *
  861.  * @return STATUS_OK on success, STATUS_??? otherwise.
  862.  */
  863. MFRC522::StatusCode MFRC522::MIFARE_Read(   byte blockAddr,     ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from.
  864.                                             byte *buffer,       ///< The buffer to store the data in
  865.                                             byte *bufferSize    ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK.
  866.                                         ) {
  867.     MFRC522::StatusCode result;
  868.    
  869.     // Sanity check
  870.     if (buffer == NULL || *bufferSize < 18) {
  871.         return STATUS_NO_ROOM;
  872.     }
  873.    
  874.     // Build command buffer
  875.     buffer[0] = PICC_CMD_MF_READ;
  876.     buffer[1] = blockAddr;
  877.     // Calculate CRC_A
  878.     result = PCD_CalculateCRC(buffer, 2, &buffer[2]);
  879.     if (result != STATUS_OK) {
  880.         return result;
  881.     }
  882.    
  883.     // Transmit the buffer and receive the response, validate CRC_A.
  884.     return PCD_TransceiveData(buffer, 4, buffer, bufferSize, NULL, 0, true);
  885. } // End MIFARE_Read()
  886.  
  887. /**
  888.  * Writes 16 bytes to the active PICC.
  889.  *
  890.  * For MIFARE Classic the sector containing the block must be authenticated before calling this function.
  891.  *
  892.  * For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE".
  893.  * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3)
  894.  * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0.
  895.  * *
  896.  * @return STATUS_OK on success, STATUS_??? otherwise.
  897.  */
  898. MFRC522::StatusCode MFRC522::MIFARE_Write(  byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to.
  899.                                             byte *buffer,   ///< The 16 bytes to write to the PICC
  900.                                             byte bufferSize ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written.
  901.                                         ) {
  902.     MFRC522::StatusCode result;
  903.    
  904.     // Sanity check
  905.     if (buffer == NULL || bufferSize < 16) {
  906.         return STATUS_INVALID;
  907.     }
  908.    
  909.     // Mifare Classic protocol requires two communications to perform a write.
  910.     // Step 1: Tell the PICC we want to write to block blockAddr.
  911.     byte cmdBuffer[2];
  912.     cmdBuffer[0] = PICC_CMD_MF_WRITE;
  913.     cmdBuffer[1] = blockAddr;
  914.     result = PCD_MIFARE_Transceive(cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
  915.     if (result != STATUS_OK) {
  916.         return result;
  917.     }
  918.    
  919.     // Step 2: Transfer the data
  920.     result = PCD_MIFARE_Transceive(buffer, bufferSize); // Adds CRC_A and checks that the response is MF_ACK.
  921.     if (result != STATUS_OK) {
  922.         return result;
  923.     }
  924.    
  925.     return STATUS_OK;
  926. } // End MIFARE_Write()
  927.  
  928. /**
  929.  * Writes a 4 byte page to the active MIFARE Ultralight PICC.
  930.  *
  931.  * @return STATUS_OK on success, STATUS_??? otherwise.
  932.  */
  933. MFRC522::StatusCode MFRC522::MIFARE_Ultralight_Write(   byte page,      ///< The page (2-15) to write to.
  934.                                                         byte *buffer,   ///< The 4 bytes to write to the PICC
  935.                                                         byte bufferSize ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written.
  936.                                                     ) {
  937.     MFRC522::StatusCode result;
  938.    
  939.     // Sanity check
  940.     if (buffer == NULL || bufferSize < 4) {
  941.         return STATUS_INVALID;
  942.     }
  943.    
  944.     // Build commmand buffer
  945.     byte cmdBuffer[6];
  946.     cmdBuffer[0] = PICC_CMD_UL_WRITE;
  947.     cmdBuffer[1] = page;
  948.     memcpy(&cmdBuffer[2], buffer, 4);
  949.    
  950.     // Perform the write
  951.     result = PCD_MIFARE_Transceive(cmdBuffer, 6); // Adds CRC_A and checks that the response is MF_ACK.
  952.     if (result != STATUS_OK) {
  953.         return result;
  954.     }
  955.     return STATUS_OK;
  956. } // End MIFARE_Ultralight_Write()
  957.  
  958. /**
  959.  * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory.
  960.  * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
  961.  * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
  962.  * Use MIFARE_Transfer() to store the result in a block.
  963.  *
  964.  * @return STATUS_OK on success, STATUS_??? otherwise.
  965.  */
  966. MFRC522::StatusCode MFRC522::MIFARE_Decrement(  byte blockAddr, ///< The block (0-0xff) number.
  967.                                                 long delta      ///< This number is subtracted from the value of block blockAddr.
  968.                                             ) {
  969.     return MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta);
  970. } // End MIFARE_Decrement()
  971.  
  972. /**
  973.  * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory.
  974.  * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
  975.  * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
  976.  * Use MIFARE_Transfer() to store the result in a block.
  977.  *
  978.  * @return STATUS_OK on success, STATUS_??? otherwise.
  979.  */
  980. MFRC522::StatusCode MFRC522::MIFARE_Increment(  byte blockAddr, ///< The block (0-0xff) number.
  981.                                                 long delta      ///< This number is added to the value of block blockAddr.
  982.                                             ) {
  983.     return MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta);
  984. } // End MIFARE_Increment()
  985.  
  986. /**
  987.  * MIFARE Restore copies the value of the addressed block into a volatile memory.
  988.  * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
  989.  * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
  990.  * Use MIFARE_Transfer() to store the result in a block.
  991.  *
  992.  * @return STATUS_OK on success, STATUS_??? otherwise.
  993.  */
  994. MFRC522::StatusCode MFRC522::MIFARE_Restore(    byte blockAddr ///< The block (0-0xff) number.
  995.                                             ) {
  996.     // The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2.
  997.     // Doing only a single step does not work, so I chose to transfer 0L in step two.
  998.     return MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L);
  999. } // End MIFARE_Restore()
  1000.  
  1001. /**
  1002.  * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore.
  1003.  *
  1004.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1005.  */
  1006. MFRC522::StatusCode MFRC522::MIFARE_TwoStepHelper(  byte command,   ///< The command to use
  1007.                                                     byte blockAddr, ///< The block (0-0xff) number.
  1008.                                                     long data       ///< The data to transfer in step 2
  1009.                                                     ) {
  1010.     MFRC522::StatusCode result;
  1011.     byte cmdBuffer[2]; // We only need room for 2 bytes.
  1012.    
  1013.     // Step 1: Tell the PICC the command and block address
  1014.     cmdBuffer[0] = command;
  1015.     cmdBuffer[1] = blockAddr;
  1016.     result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
  1017.     if (result != STATUS_OK) {
  1018.         return result;
  1019.     }
  1020.    
  1021.     // Step 2: Transfer the data
  1022.     result = PCD_MIFARE_Transceive( (byte *)&data, 4, true); // Adds CRC_A and accept timeout as success.
  1023.     if (result != STATUS_OK) {
  1024.         return result;
  1025.     }
  1026.    
  1027.     return STATUS_OK;
  1028. } // End MIFARE_TwoStepHelper()
  1029.  
  1030. /**
  1031.  * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block.
  1032.  * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
  1033.  * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
  1034.  *
  1035.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1036.  */
  1037. MFRC522::StatusCode MFRC522::MIFARE_Transfer(   byte blockAddr ///< The block (0-0xff) number.
  1038.                                             ) {
  1039.     MFRC522::StatusCode result;
  1040.     byte cmdBuffer[2]; // We only need room for 2 bytes.
  1041.    
  1042.     // Tell the PICC we want to transfer the result into block blockAddr.
  1043.     cmdBuffer[0] = PICC_CMD_MF_TRANSFER;
  1044.     cmdBuffer[1] = blockAddr;
  1045.     result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK.
  1046.     if (result != STATUS_OK) {
  1047.         return result;
  1048.     }
  1049.     return STATUS_OK;
  1050. } // End MIFARE_Transfer()
  1051.  
  1052. /**
  1053.  * Helper routine to read the current value from a Value Block.
  1054.  *
  1055.  * Only for MIFARE Classic and only for blocks in "value block" mode, that
  1056.  * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
  1057.  * the block must be authenticated before calling this function.
  1058.  *
  1059.  * @param[in]   blockAddr   The block (0x00-0xff) number.
  1060.  * @param[out]  value       Current value of the Value Block.
  1061.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1062.   */
  1063. MFRC522::StatusCode MFRC522::MIFARE_GetValue(byte blockAddr, long *value) {
  1064.     MFRC522::StatusCode status;
  1065.     byte buffer[18];
  1066.     byte size = sizeof(buffer);
  1067.    
  1068.     // Read the block
  1069.     status = MIFARE_Read(blockAddr, buffer, &size);
  1070.     if (status == STATUS_OK) {
  1071.         // Extract the value
  1072.         *value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]);
  1073.     }
  1074.     return status;
  1075. } // End MIFARE_GetValue()
  1076.  
  1077. /**
  1078.  * Helper routine to write a specific value into a Value Block.
  1079.  *
  1080.  * Only for MIFARE Classic and only for blocks in "value block" mode, that
  1081.  * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing
  1082.  * the block must be authenticated before calling this function.
  1083.  *
  1084.  * @param[in]   blockAddr   The block (0x00-0xff) number.
  1085.  * @param[in]   value       New value of the Value Block.
  1086.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1087.  */
  1088. MFRC522::StatusCode MFRC522::MIFARE_SetValue(byte blockAddr, long value) {
  1089.     byte buffer[18];
  1090.    
  1091.     // Translate the long into 4 bytes; repeated 2x in value block
  1092.     buffer[0] = buffer[ 8] = (value & 0xFF);
  1093.     buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8;
  1094.     buffer[2] = buffer[10] = (value & 0xFF0000) >> 16;
  1095.     buffer[3] = buffer[11] = (value & 0xFF000000) >> 24;
  1096.     // Inverse 4 bytes also found in value block
  1097.     buffer[4] = ~buffer[0];
  1098.     buffer[5] = ~buffer[1];
  1099.     buffer[6] = ~buffer[2];
  1100.     buffer[7] = ~buffer[3];
  1101.     // Address 2x with inverse address 2x
  1102.     buffer[12] = buffer[14] = blockAddr;
  1103.     buffer[13] = buffer[15] = ~blockAddr;
  1104.    
  1105.     // Write the whole data block
  1106.     return MIFARE_Write(blockAddr, buffer, 16);
  1107. } // End MIFARE_SetValue()
  1108.  
  1109. /**
  1110.  * Authenticate with a NTAG216.
  1111.  *
  1112.  * Only for NTAG216. First implemented by Gargantuanman.
  1113.  *
  1114.  * @param[in]   passWord   password.
  1115.  * @param[in]   pACK       result success???.
  1116.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1117.  */
  1118. MFRC522::StatusCode MFRC522::PCD_NTAG216_AUTH(byte* passWord, byte pACK[]) //Authenticate with 32bit password
  1119. {
  1120.     MFRC522::StatusCode result;
  1121.     byte                cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
  1122.    
  1123.     cmdBuffer[0] = 0x1B; //Comando de autentificacion
  1124.    
  1125.     for (byte i = 0; i<4; i++)
  1126.         cmdBuffer[i+1] = passWord[i];
  1127.    
  1128.     result = PCD_CalculateCRC(cmdBuffer, 5, &cmdBuffer[5]);
  1129.    
  1130.     if (result!=STATUS_OK) {
  1131.         return result;
  1132.     }
  1133.    
  1134.     // Transceive the data, store the reply in cmdBuffer[]
  1135.     byte waitIRq        = 0x30; // RxIRq and IdleIRq
  1136.     byte cmdBufferSize  = sizeof(cmdBuffer);
  1137.     byte validBits      = 0;
  1138.     byte rxlength       = 5;
  1139.     result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, 7, cmdBuffer, &rxlength, &validBits);
  1140.    
  1141.     pACK[0] = cmdBuffer[0];
  1142.     pACK[1] = cmdBuffer[1];
  1143.    
  1144.     if (result!=STATUS_OK) {
  1145.         return result;
  1146.     }
  1147.    
  1148.     return STATUS_OK;
  1149. } // End PCD_NTAG216_AUTH()
  1150.  
  1151.  
  1152. /////////////////////////////////////////////////////////////////////////////////////
  1153. // Support functions
  1154. /////////////////////////////////////////////////////////////////////////////////////
  1155.  
  1156. /**
  1157.  * Wrapper for MIFARE protocol communication.
  1158.  * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout.
  1159.  *
  1160.  * @return STATUS_OK on success, STATUS_??? otherwise.
  1161.  */
  1162. MFRC522::StatusCode MFRC522::PCD_MIFARE_Transceive( byte *sendData,     ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A.
  1163.                                                     byte sendLen,       ///< Number of bytes in sendData.
  1164.                                                     bool acceptTimeout  ///< True => A timeout is also success
  1165.                                                 ) {
  1166.     MFRC522::StatusCode result;
  1167.     byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A.
  1168.    
  1169.     // Sanity check
  1170.     if (sendData == NULL || sendLen > 16) {
  1171.         return STATUS_INVALID;
  1172.     }
  1173.    
  1174.     // Copy sendData[] to cmdBuffer[] and add CRC_A
  1175.     memcpy(cmdBuffer, sendData, sendLen);
  1176.     result = PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]);
  1177.     if (result != STATUS_OK) {
  1178.         return result;
  1179.     }
  1180.     sendLen += 2;
  1181.    
  1182.     // Transceive the data, store the reply in cmdBuffer[]
  1183.     byte waitIRq = 0x30;        // RxIRq and IdleIRq
  1184.     byte cmdBufferSize = sizeof(cmdBuffer);
  1185.     byte validBits = 0;
  1186.     result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits);
  1187.     if (acceptTimeout && result == STATUS_TIMEOUT) {
  1188.         return STATUS_OK;
  1189.     }
  1190.     if (result != STATUS_OK) {
  1191.         return result;
  1192.     }
  1193.     // The PICC must reply with a 4 bit ACK
  1194.     if (cmdBufferSize != 1 || validBits != 4) {
  1195.         return STATUS_ERROR;
  1196.     }
  1197.     if (cmdBuffer[0] != MF_ACK) {
  1198.         return STATUS_MIFARE_NACK;
  1199.     }
  1200.     return STATUS_OK;
  1201. } // End PCD_MIFARE_Transceive()
  1202.  
  1203. /**
  1204.  * Returns a __FlashStringHelper pointer to a status code name.
  1205.  *
  1206.  * @return const __FlashStringHelper *
  1207.  */
  1208. const __FlashStringHelper *MFRC522::GetStatusCodeName(MFRC522::StatusCode code  ///< One of the StatusCode enums.
  1209.                                         ) {
  1210.     switch (code) {
  1211.         case STATUS_OK:             return F("Success.");
  1212.         case STATUS_ERROR:          return F("Error in communication.");
  1213.         case STATUS_COLLISION:      return F("Collission detected.");
  1214.         case STATUS_TIMEOUT:        return F("Timeout in communication.");
  1215.         case STATUS_NO_ROOM:        return F("A buffer is not big enough.");
  1216.         case STATUS_INTERNAL_ERROR: return F("Internal error in the code. Should not happen.");
  1217.         case STATUS_INVALID:        return F("Invalid argument.");
  1218.         case STATUS_CRC_WRONG:      return F("The CRC_A does not match.");
  1219.         case STATUS_MIFARE_NACK:    return F("A MIFARE PICC responded with NAK.");
  1220.         default:                    return F("Unknown error");
  1221.     }
  1222. } // End GetStatusCodeName()
  1223.  
  1224. /**
  1225.  * Translates the SAK (Select Acknowledge) to a PICC type.
  1226.  *
  1227.  * @return PICC_Type
  1228.  */
  1229. MFRC522::PICC_Type MFRC522::PICC_GetType(byte sak       ///< The SAK byte returned from PICC_Select().
  1230.                                         ) {
  1231.     // http://www.nxp.com/documents/application_note/AN10833.pdf
  1232.     // 3.2 Coding of Select Acknowledge (SAK)
  1233.     // ignore 8-bit (iso14443 starts with LSBit = bit 1)
  1234.     // fixes wrong type for manufacturer Infineon (http://nfc-tools.org/index.php?title=ISO14443A)
  1235.     sak &= 0x7F;
  1236.     switch (sak) {
  1237.         case 0x04:  return PICC_TYPE_NOT_COMPLETE;  // UID not complete
  1238.         case 0x09:  return PICC_TYPE_MIFARE_MINI;
  1239.         case 0x08:  return PICC_TYPE_MIFARE_1K;
  1240.         case 0x18:  return PICC_TYPE_MIFARE_4K;
  1241.         case 0x00:  return PICC_TYPE_MIFARE_UL;
  1242.         case 0x10:
  1243.         case 0x11:  return PICC_TYPE_MIFARE_PLUS;
  1244.         case 0x01:  return PICC_TYPE_TNP3XXX;
  1245.         case 0x20:  return PICC_TYPE_ISO_14443_4;
  1246.         case 0x40:  return PICC_TYPE_ISO_18092;
  1247.         default:    return PICC_TYPE_UNKNOWN;
  1248.     }
  1249. } // End PICC_GetType()
  1250.  
  1251. /**
  1252.  * Returns a __FlashStringHelper pointer to the PICC type name.
  1253.  *
  1254.  * @return const __FlashStringHelper *
  1255.  */
  1256. const __FlashStringHelper *MFRC522::PICC_GetTypeName(PICC_Type piccType ///< One of the PICC_Type enums.
  1257.                                                     ) {
  1258.     switch (piccType) {
  1259.         case PICC_TYPE_ISO_14443_4:     return F("PICC compliant with ISO/IEC 14443-4");
  1260.         case PICC_TYPE_ISO_18092:       return F("PICC compliant with ISO/IEC 18092 (NFC)");
  1261.         case PICC_TYPE_MIFARE_MINI:     return F("MIFARE Mini, 320 bytes");
  1262.         case PICC_TYPE_MIFARE_1K:       return F("MIFARE 1KB");
  1263.         case PICC_TYPE_MIFARE_4K:       return F("MIFARE 4KB");
  1264.         case PICC_TYPE_MIFARE_UL:       return F("MIFARE Ultralight or Ultralight C");
  1265.         case PICC_TYPE_MIFARE_PLUS:     return F("MIFARE Plus");
  1266.         case PICC_TYPE_TNP3XXX:         return F("MIFARE TNP3XXX");
  1267.         case PICC_TYPE_NOT_COMPLETE:    return F("SAK indicates UID is not complete.");
  1268.         case PICC_TYPE_UNKNOWN:
  1269.         default:                        return F("Unknown type");
  1270.     }
  1271. } // End PICC_GetTypeName()
  1272.  
  1273. /**
  1274.  * Dumps debug info about the connected PCD to Serial.
  1275.  * Shows all known firmware versions
  1276.  */
  1277. void MFRC522::PCD_DumpVersionToSerial() {
  1278.     // Get the MFRC522 firmware version
  1279.     byte v = PCD_ReadRegister(VersionReg);
  1280.     Serial.print(F("Firmware Version: 0x"));
  1281.     Serial.print(v, HEX);
  1282.     // Lookup which version
  1283.     switch(v) {
  1284.         case 0x88: Serial.println(F(" = (clone)"));  break;
  1285.         case 0x90: Serial.println(F(" = v0.0"));     break;
  1286.         case 0x91: Serial.println(F(" = v1.0"));     break;
  1287.         case 0x92: Serial.println(F(" = v2.0"));     break;
  1288.         default:   Serial.println(F(" = (unknown)"));
  1289.     }
  1290.     // When 0x00 or 0xFF is returned, communication probably failed
  1291.     if ((v == 0x00) || (v == 0xFF))
  1292.         Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
  1293. } // End PCD_DumpVersionToSerial()
  1294.  
  1295. /**
  1296.  * Dumps debug info about the selected PICC to Serial.
  1297.  * On success the PICC is halted after dumping the data.
  1298.  * For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried.
  1299.  */
  1300. void MFRC522::PICC_DumpToSerial(Uid *uid    ///< Pointer to Uid struct returned from a successful PICC_Select().
  1301.                                 ) {
  1302.     MIFARE_Key key;
  1303.    
  1304.     // Dump UID, SAK and Type
  1305.     PICC_DumpDetailsToSerial(uid);
  1306.    
  1307.     // Dump contents
  1308.     PICC_Type piccType = PICC_GetType(uid->sak);
  1309.     switch (piccType) {
  1310.         case PICC_TYPE_MIFARE_MINI:
  1311.         case PICC_TYPE_MIFARE_1K:
  1312.         case PICC_TYPE_MIFARE_4K:
  1313.             // All keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  1314.             for (byte i = 0; i < 6; i++) {
  1315.                 key.keyByte[i] = 0xFF;
  1316.             }
  1317.             PICC_DumpMifareClassicToSerial(uid, piccType, &key);
  1318.             break;
  1319.            
  1320.         case PICC_TYPE_MIFARE_UL:
  1321.             PICC_DumpMifareUltralightToSerial();
  1322.             break;
  1323.            
  1324.         case PICC_TYPE_ISO_14443_4:
  1325.         case PICC_TYPE_ISO_18092:
  1326.         case PICC_TYPE_MIFARE_PLUS:
  1327.         case PICC_TYPE_TNP3XXX:
  1328.             Serial.println(F("Dumping memory contents not implemented for that PICC type."));
  1329.             break;
  1330.            
  1331.         case PICC_TYPE_UNKNOWN:
  1332.         case PICC_TYPE_NOT_COMPLETE:
  1333.         default:
  1334.             break; // No memory dump here
  1335.     }
  1336.    
  1337.     Serial.println();
  1338.     PICC_HaltA(); // Already done if it was a MIFARE Classic PICC.
  1339. } // End PICC_DumpToSerial()
  1340.  
  1341. /**
  1342.  * Dumps card info (UID,SAK,Type) about the selected PICC to Serial.
  1343.  */
  1344. void MFRC522::PICC_DumpDetailsToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select().
  1345.                                     ) {
  1346.     // UID
  1347.     Serial.print(F("Card UID:"));
  1348.     for (byte i = 0; i < uid->size; i++) {
  1349.         if(uid->uidByte[i] < 0x10)
  1350.             Serial.print(F(" 0"));
  1351.         else
  1352.             Serial.print(F(" "));
  1353.         Serial.print(uid->uidByte[i], HEX);
  1354.     }
  1355.     Serial.println();
  1356.    
  1357.     // SAK
  1358.     Serial.print(F("Card SAK: "));
  1359.     if(uid->sak < 0x10)
  1360.         Serial.print(F("0"));
  1361.     Serial.println(uid->sak, HEX);
  1362.    
  1363.     // (suggested) PICC type
  1364.     PICC_Type piccType = PICC_GetType(uid->sak);
  1365.     Serial.print(F("PICC type: "));
  1366.     Serial.println(PICC_GetTypeName(piccType));
  1367. } // End PICC_DumpDetailsToSerial()
  1368.  
  1369. /**
  1370.  * Dumps memory contents of a MIFARE Classic PICC.
  1371.  * On success the PICC is halted after dumping the data.
  1372.  */
  1373. void MFRC522::PICC_DumpMifareClassicToSerial(   Uid *uid,           ///< Pointer to Uid struct returned from a successful PICC_Select().
  1374.                                                 PICC_Type piccType, ///< One of the PICC_Type enums.
  1375.                                                 MIFARE_Key *key     ///< Key A used for all sectors.
  1376.                                             ) {
  1377.     byte no_of_sectors = 0;
  1378.     switch (piccType) {
  1379.         case PICC_TYPE_MIFARE_MINI:
  1380.             // Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes.
  1381.             no_of_sectors = 5;
  1382.             break;
  1383.            
  1384.         case PICC_TYPE_MIFARE_1K:
  1385.             // Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes.
  1386.             no_of_sectors = 16;
  1387.             break;
  1388.            
  1389.         case PICC_TYPE_MIFARE_4K:
  1390.             // Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes.
  1391.             no_of_sectors = 40;
  1392.             break;
  1393.            
  1394.         default: // Should not happen. Ignore.
  1395.             break;
  1396.     }
  1397.    
  1398.     // Dump sectors, highest address first.
  1399.     if (no_of_sectors) {
  1400.         Serial.println(F("Sector Block   0  1  2  3   4  5  6  7   8  9 10 11  12 13 14 15  AccessBits"));
  1401.         for (int8_t i = no_of_sectors - 1; i >= 0; i--) {
  1402.             PICC_DumpMifareClassicSectorToSerial(uid, key, i);
  1403.         }
  1404.     }
  1405.     PICC_HaltA(); // Halt the PICC before stopping the encrypted session.
  1406.     PCD_StopCrypto1();
  1407. } // End PICC_DumpMifareClassicToSerial()
  1408.  
  1409. /**
  1410.  * Dumps memory contents of a sector of a MIFARE Classic PICC.
  1411.  * Uses PCD_Authenticate(), MIFARE_Read() and PCD_StopCrypto1.
  1412.  * Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits.
  1413.  */
  1414. void MFRC522::PICC_DumpMifareClassicSectorToSerial(Uid *uid,            ///< Pointer to Uid struct returned from a successful PICC_Select().
  1415.                                                     MIFARE_Key *key,    ///< Key A for the sector.
  1416.                                                     byte sector         ///< The sector to dump, 0..39.
  1417.                                                     ) {
  1418.     MFRC522::StatusCode status;
  1419.     byte firstBlock;        // Address of lowest address to dump actually last block dumped)
  1420.     byte no_of_blocks;      // Number of blocks in sector
  1421.     bool isSectorTrailer;   // Set to true while handling the "last" (ie highest address) in the sector.
  1422.    
  1423.     // The access bits are stored in a peculiar fashion.
  1424.     // There are four groups:
  1425.     //      g[3]    Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
  1426.     //      g[2]    Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
  1427.     //      g[1]    Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
  1428.     //      g[0]    Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
  1429.     // Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB.
  1430.     // The four CX bits are stored together in a nible cx and an inverted nible cx_.
  1431.     byte c1, c2, c3;        // Nibbles
  1432.     byte c1_, c2_, c3_;     // Inverted nibbles
  1433.     bool invertedError;     // True if one of the inverted nibbles did not match
  1434.     byte g[4];              // Access bits for each of the four groups.
  1435.     byte group;             // 0-3 - active group for access bits
  1436.     bool firstInGroup;      // True for the first block dumped in the group
  1437.    
  1438.     // Determine position and size of sector.
  1439.     if (sector < 32) { // Sectors 0..31 has 4 blocks each
  1440.         no_of_blocks = 4;
  1441.         firstBlock = sector * no_of_blocks;
  1442.     }
  1443.     else if (sector < 40) { // Sectors 32-39 has 16 blocks each
  1444.         no_of_blocks = 16;
  1445.         firstBlock = 128 + (sector - 32) * no_of_blocks;
  1446.     }
  1447.     else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors.
  1448.         return;
  1449.     }
  1450.        
  1451.     // Dump blocks, highest address first.
  1452.     byte byteCount;
  1453.     byte buffer[18];
  1454.     byte blockAddr;
  1455.     isSectorTrailer = true;
  1456.     for (int8_t blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) {
  1457.         blockAddr = firstBlock + blockOffset;
  1458.         // Sector number - only on first line
  1459.         if (isSectorTrailer) {
  1460.             if(sector < 10)
  1461.                 Serial.print(F("   ")); // Pad with spaces
  1462.             else
  1463.                 Serial.print(F("  ")); // Pad with spaces
  1464.             Serial.print(sector);
  1465.             Serial.print(F("   "));
  1466.         }
  1467.         else {
  1468.             Serial.print(F("       "));
  1469.         }
  1470.         // Block number
  1471.         if(blockAddr < 10)
  1472.             Serial.print(F("   ")); // Pad with spaces
  1473.         else {
  1474.             if(blockAddr < 100)
  1475.                 Serial.print(F("  ")); // Pad with spaces
  1476.             else
  1477.                 Serial.print(F(" ")); // Pad with spaces
  1478.         }
  1479.         Serial.print(blockAddr);
  1480.         Serial.print(F("  "));
  1481.         // Establish encrypted communications before reading the first block
  1482.         if (isSectorTrailer) {
  1483.             status = PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid);
  1484.             if (status != STATUS_OK) {
  1485.                 Serial.print(F("PCD_Authenticate() failed: "));
  1486.                 Serial.println(GetStatusCodeName(status));
  1487.                 return;
  1488.             }
  1489.         }
  1490.         // Read block
  1491.         byteCount = sizeof(buffer);
  1492.         status = MIFARE_Read(blockAddr, buffer, &byteCount);
  1493.         if (status != STATUS_OK) {
  1494.             Serial.print(F("MIFARE_Read() failed: "));
  1495.             Serial.println(GetStatusCodeName(status));
  1496.             continue;
  1497.         }
  1498.         // Dump data
  1499.         for (byte index = 0; index < 16; index++) {
  1500.             if(buffer[index] < 0x10)
  1501.                 Serial.print(F(" 0"));
  1502.             else
  1503.                 Serial.print(F(" "));
  1504.             Serial.print(buffer[index], HEX);
  1505.             if ((index % 4) == 3) {
  1506.                 Serial.print(F(" "));
  1507.             }
  1508.         }
  1509.         // Parse sector trailer data
  1510.         if (isSectorTrailer) {
  1511.             c1  = buffer[7] >> 4;
  1512.             c2  = buffer[8] & 0xF;
  1513.             c3  = buffer[8] >> 4;
  1514.             c1_ = buffer[6] & 0xF;
  1515.             c2_ = buffer[6] >> 4;
  1516.             c3_ = buffer[7] & 0xF;
  1517.             invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF));
  1518.             g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0);
  1519.             g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1);
  1520.             g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2);
  1521.             g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3);
  1522.             isSectorTrailer = false;
  1523.         }
  1524.        
  1525.         // Which access group is this block in?
  1526.         if (no_of_blocks == 4) {
  1527.             group = blockOffset;
  1528.             firstInGroup = true;
  1529.         }
  1530.         else {
  1531.             group = blockOffset / 5;
  1532.             firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5);
  1533.         }
  1534.        
  1535.         if (firstInGroup) {
  1536.             // Print access bits
  1537.             Serial.print(F(" [ "));
  1538.             Serial.print((g[group] >> 2) & 1, DEC); Serial.print(F(" "));
  1539.             Serial.print((g[group] >> 1) & 1, DEC); Serial.print(F(" "));
  1540.             Serial.print((g[group] >> 0) & 1, DEC);
  1541.             Serial.print(F(" ] "));
  1542.             if (invertedError) {
  1543.                 Serial.print(F(" Inverted access bits did not match! "));
  1544.             }
  1545.         }
  1546.        
  1547.         if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block
  1548.             long value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]);
  1549.             Serial.print(F(" Value=0x")); Serial.print(value, HEX);
  1550.             Serial.print(F(" Adr=0x")); Serial.print(buffer[12], HEX);
  1551.         }
  1552.         Serial.println();
  1553.     }
  1554.    
  1555.     return;
  1556. } // End PICC_DumpMifareClassicSectorToSerial()
  1557.  
  1558. /**
  1559.  * Dumps memory contents of a MIFARE Ultralight PICC.
  1560.  */
  1561. void MFRC522::PICC_DumpMifareUltralightToSerial() {
  1562.     MFRC522::StatusCode status;
  1563.     byte byteCount;
  1564.     byte buffer[18];
  1565.     byte i;
  1566.    
  1567.     Serial.println(F("Page  0  1  2  3"));
  1568.     // Try the mpages of the original Ultralight. Ultralight C has more pages.
  1569.     for (byte page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time.
  1570.         // Read pages
  1571.         byteCount = sizeof(buffer);
  1572.         status = MIFARE_Read(page, buffer, &byteCount);
  1573.         if (status != STATUS_OK) {
  1574.             Serial.print(F("MIFARE_Read() failed: "));
  1575.             Serial.println(GetStatusCodeName(status));
  1576.             break;
  1577.         }
  1578.         // Dump data
  1579.         for (byte offset = 0; offset < 4; offset++) {
  1580.             i = page + offset;
  1581.             if(i < 10)
  1582.                 Serial.print(F("  ")); // Pad with spaces
  1583.             else
  1584.                 Serial.print(F(" ")); // Pad with spaces
  1585.             Serial.print(i);
  1586.             Serial.print(F("  "));
  1587.             for (byte index = 0; index < 4; index++) {
  1588.                 i = 4 * offset + index;
  1589.                 if(buffer[i] < 0x10)
  1590.                     Serial.print(F(" 0"));
  1591.                 else
  1592.                     Serial.print(F(" "));
  1593.                 Serial.print(buffer[i], HEX);
  1594.             }
  1595.             Serial.println();
  1596.         }
  1597.     }
  1598. } // End PICC_DumpMifareUltralightToSerial()
  1599.  
  1600. /**
  1601.  * Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tuples C1 is MSB (=4) and C3 is LSB (=1).
  1602.  */
  1603. void MFRC522::MIFARE_SetAccessBits( byte *accessBitBuffer,  ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set.
  1604.                                     byte g0,                ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
  1605.                                     byte g1,                ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
  1606.                                     byte g2,                ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
  1607.                                     byte g3                 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
  1608.                                 ) {
  1609.     byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2);
  1610.     byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1);
  1611.     byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0);
  1612.    
  1613.     accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF);
  1614.     accessBitBuffer[1] =          c1 << 4 | (~c3 & 0xF);
  1615.     accessBitBuffer[2] =          c3 << 4 | c2;
  1616. } // End MIFARE_SetAccessBits()
  1617.  
  1618.  
  1619. /**
  1620.  * Performs the "magic sequence" needed to get Chinese UID changeable
  1621.  * Mifare cards to allow writing to sector 0, where the card UID is stored.
  1622.  *
  1623.  * Note that you do not need to have selected the card through REQA or WUPA,
  1624.  * this sequence works immediately when the card is in the reader vicinity.
  1625.  * This means you can use this method even on "bricked" cards that your reader does
  1626.  * not recognise anymore (see MFRC522::MIFARE_UnbrickUidSector).
  1627.  *
  1628.  * Of course with non-bricked devices, you're free to select them before calling this function.
  1629.  */
  1630. bool MFRC522::MIFARE_OpenUidBackdoor(bool logErrors) {
  1631.     // Magic sequence:
  1632.     // > 50 00 57 CD (HALT + CRC)
  1633.     // > 40 (7 bits only)
  1634.     // < A (4 bits only)
  1635.     // > 43
  1636.     // < A (4 bits only)
  1637.     // Then you can write to sector 0 without authenticating
  1638.    
  1639.     PICC_HaltA(); // 50 00 57 CD
  1640.    
  1641.     byte cmd = 0x40;
  1642.     byte validBits = 7; /* Our command is only 7 bits. After receiving card response,
  1643.                           this will contain amount of valid response bits. */
  1644.     byte response[32]; // Card's response is written here
  1645.     byte received;
  1646.     MFRC522::StatusCode status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 40
  1647.     if(status != STATUS_OK) {
  1648.         if(logErrors) {
  1649.             Serial.println(F("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?"));
  1650.             Serial.print(F("Error name: "));
  1651.             Serial.println(GetStatusCodeName(status));
  1652.         }
  1653.         return false;
  1654.     }
  1655.     if (received != 1 || response[0] != 0x0A) {
  1656.         if (logErrors) {
  1657.             Serial.print(F("Got bad response on backdoor 0x40 command: "));
  1658.             Serial.print(response[0], HEX);
  1659.             Serial.print(F(" ("));
  1660.             Serial.print(validBits);
  1661.             Serial.print(F(" valid bits)\r\n"));
  1662.         }
  1663.         return false;
  1664.     }
  1665.    
  1666.     cmd = 0x43;
  1667.     validBits = 8;
  1668.     status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 43
  1669.     if(status != STATUS_OK) {
  1670.         if(logErrors) {
  1671.             Serial.println(F("Error in communication at command 0x43, after successfully executing 0x40"));
  1672.             Serial.print(F("Error name: "));
  1673.             Serial.println(GetStatusCodeName(status));
  1674.         }
  1675.         return false;
  1676.     }
  1677.     if (received != 1 || response[0] != 0x0A) {
  1678.         if (logErrors) {
  1679.             Serial.print(F("Got bad response on backdoor 0x43 command: "));
  1680.             Serial.print(response[0], HEX);
  1681.             Serial.print(F(" ("));
  1682.             Serial.print(validBits);
  1683.             Serial.print(F(" valid bits)\r\n"));
  1684.         }
  1685.         return false;
  1686.     }
  1687.    
  1688.     // You can now write to sector 0 without authenticating!
  1689.     return true;
  1690. } // End MIFARE_OpenUidBackdoor()
  1691.  
  1692. /**
  1693.  * Reads entire block 0, including all manufacturer data, and overwrites
  1694.  * that block with the new UID, a freshly calculated BCC, and the original
  1695.  * manufacturer data.
  1696.  *
  1697.  * It assumes a default KEY A of 0xFFFFFFFFFFFF.
  1698.  * Make sure to have selected the card before this function is called.
  1699.  */
  1700. bool MFRC522::MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors) {
  1701.    
  1702.     // UID + BCC byte can not be larger than 16 together
  1703.     if (!newUid || !uidSize || uidSize > 15) {
  1704.         if (logErrors) {
  1705.             Serial.println(F("New UID buffer empty, size 0, or size > 15 given"));
  1706.         }
  1707.         return false;
  1708.     }
  1709.    
  1710.     // Authenticate for reading
  1711.     MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
  1712.     MFRC522::StatusCode status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid);
  1713.     if (status != STATUS_OK) {
  1714.        
  1715.         if (status == STATUS_TIMEOUT) {
  1716.             // We get a read timeout if no card is selected yet, so let's select one
  1717.            
  1718.             // Wake the card up again if sleeping
  1719. //            byte atqa_answer[2];
  1720. //            byte atqa_size = 2;
  1721. //            PICC_WakeupA(atqa_answer, &atqa_size);
  1722.            
  1723.             if (!PICC_IsNewCardPresent() || !PICC_ReadCardSerial()) {
  1724.                 Serial.println(F("No card was previously selected, and none are available. Failed to set UID."));
  1725.                 return false;
  1726.             }
  1727.            
  1728.             status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid);
  1729.             if (status != STATUS_OK) {
  1730.                 // We tried, time to give up
  1731.                 if (logErrors) {
  1732.                     Serial.println(F("Failed to authenticate to card for reading, could not set UID: "));
  1733.                     Serial.println(GetStatusCodeName(status));
  1734.                 }
  1735.                 return false;
  1736.             }
  1737.         }
  1738.         else {
  1739.             if (logErrors) {
  1740.                 Serial.print(F("PCD_Authenticate() failed: "));
  1741.                 Serial.println(GetStatusCodeName(status));
  1742.             }
  1743.             return false;
  1744.         }
  1745.     }
  1746.    
  1747.     // Read block 0
  1748.     byte block0_buffer[18];
  1749.     byte byteCount = sizeof(block0_buffer);
  1750.     status = MIFARE_Read((byte)0, block0_buffer, &byteCount);
  1751.     if (status != STATUS_OK) {
  1752.         if (logErrors) {
  1753.             Serial.print(F("MIFARE_Read() failed: "));
  1754.             Serial.println(GetStatusCodeName(status));
  1755.             Serial.println(F("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?"));
  1756.         }
  1757.         return false;
  1758.     }
  1759.    
  1760.     // Write new UID to the data we just read, and calculate BCC byte
  1761.     byte bcc = 0;
  1762.     for (int i = 0; i < uidSize; i++) {
  1763.         block0_buffer[i] = newUid[i];
  1764.         bcc ^= newUid[i];
  1765.     }
  1766.    
  1767.     // Write BCC byte to buffer
  1768.     block0_buffer[uidSize] = bcc;
  1769.    
  1770.     // Stop encrypted traffic so we can send raw bytes
  1771.     PCD_StopCrypto1();
  1772.    
  1773.     // Activate UID backdoor
  1774.     if (!MIFARE_OpenUidBackdoor(logErrors)) {
  1775.         if (logErrors) {
  1776.             Serial.println(F("Activating the UID backdoor failed."));
  1777.         }
  1778.         return false;
  1779.     }
  1780.    
  1781.     // Write modified block 0 back to card
  1782.     status = MIFARE_Write((byte)0, block0_buffer, (byte)16);
  1783.     if (status != STATUS_OK) {
  1784.         if (logErrors) {
  1785.             Serial.print(F("MIFARE_Write() failed: "));
  1786.             Serial.println(GetStatusCodeName(status));
  1787.         }
  1788.         return false;
  1789.     }
  1790.    
  1791.     // Wake the card up again
  1792.     byte atqa_answer[2];
  1793.     byte atqa_size = 2;
  1794.     PICC_WakeupA(atqa_answer, &atqa_size);
  1795.    
  1796.     return true;
  1797. }
  1798.  
  1799. /**
  1800.  * Resets entire sector 0 to zeroes, so the card can be read again by readers.
  1801.  */
  1802. bool MFRC522::MIFARE_UnbrickUidSector(bool logErrors) {
  1803.     MIFARE_OpenUidBackdoor(logErrors);
  1804.    
  1805.     byte block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  1806.    
  1807.     // Write modified block 0 back to card
  1808.     MFRC522::StatusCode status = MIFARE_Write((byte)0, block0_buffer, (byte)16);
  1809.     if (status != STATUS_OK) {
  1810.         if (logErrors) {
  1811.             Serial.print(F("MIFARE_Write() failed: "));
  1812.             Serial.println(GetStatusCodeName(status));
  1813.         }
  1814.         return false;
  1815.     }
  1816.     return true;
  1817. }
  1818.  
  1819. /////////////////////////////////////////////////////////////////////////////////////
  1820. // Convenience functions - does not add extra functionality
  1821. /////////////////////////////////////////////////////////////////////////////////////
  1822.  
  1823. /**
  1824.  * Returns true if a PICC responds to PICC_CMD_REQA.
  1825.  * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored.
  1826.  *
  1827.  * @return bool
  1828.  */
  1829. bool MFRC522::PICC_IsNewCardPresent() {
  1830.     byte bufferATQA[2];
  1831.     byte bufferSize = sizeof(bufferATQA);
  1832.     MFRC522::StatusCode result = PICC_RequestA(bufferATQA, &bufferSize);
  1833.     return (result == STATUS_OK || result == STATUS_COLLISION);
  1834. } // End PICC_IsNewCardPresent()
  1835.  
  1836. /**
  1837.  * Simple wrapper around PICC_Select.
  1838.  * Returns true if a UID could be read.
  1839.  * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first.
  1840.  * The read UID is available in the class variable uid.
  1841.  *
  1842.  * @return bool
  1843.  */
  1844. bool MFRC522::PICC_ReadCardSerial() {
  1845.     MFRC522::StatusCode result = PICC_Select(&uid);
  1846.     return (result == STATUS_OK);
  1847. } // End
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement