test ok

Dependents:   DR14_FRDM_MFRC522 RFID-RC522_LCD_16x2_A1602

Fork of MFRC522 by Martin Olejar

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers MFRC522.h Source File

MFRC522.h

00001 /**
00002  * @ version Forks dec 2014
00003  * @date 27/12/2014
00004  * @author F.BLANC
00005  * MFRC522.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
00006  * Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
00007  * Created by Miguel Balboa (circuitito.com), Jan, 2012.
00008  * Rewritten by Soren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.)
00009  * Ported to mbed by Martin Olejar, Dec, 2013
00010  *
00011  * Please read this file for an overview and then MFRC522.cpp for comments on the specific functions.
00012  * Search for "mf-rc522" on ebay.com to purchase the MF-RC522 board.
00013  *
00014  * There are three hardware components involved:
00015  * 1) The micro controller: An Arduino
00016  * 2) The PCD (short for Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
00017  * 3) The PICC (short for Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
00018  *
00019  * The microcontroller and card reader uses SPI for communication.
00020  * The protocol is described in the MFRC522 datasheet: http://www.nxp.com/documents/data_sheet/MFRC522.pdf
00021  *
00022  * The card reader and the tags communicate using a 13.56MHz electromagnetic field.
00023  * The protocol is defined in ISO/IEC 14443-3 Identification cards -- Contactless integrated circuit cards -- Proximity cards -- Part 3: Initialization and anticollision".
00024  * A free version of the final draft can be found at http://wg8.de/wg8n1496_17n3613_Ballot_FCD14443-3.pdf
00025  * Details are found in chapter 6, Type A: Initialization and anticollision.
00026  *
00027  * If only the PICC UID is wanted, the above documents has all the needed information.
00028  * To read and write from MIFARE PICCs, the MIFARE protocol is used after the PICC has been selected.
00029  * The MIFARE Classic chips and protocol is described in the datasheets:
00030  *    1K:   http://www.nxp.com/documents/data_sheet/MF1S503x.pdf
00031  *    4K:   http://www.nxp.com/documents/data_sheet/MF1S703x.pdf
00032  *    Mini: http://www.idcardmarket.com/download/mifare_S20_datasheet.pdf
00033  * The MIFARE Ultralight chip and protocol is described in the datasheets:
00034  *    Ultralight:   http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf
00035  *    Ultralight C: http://www.nxp.com/documents/short_data_sheet/MF0ICU2_SDS.pdf
00036  *
00037  * MIFARE Classic 1K (MF1S503x):
00038  *    Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes.
00039  *    The blocks are numbered 0-63.
00040  *    Block 3 in each sector is the Sector Trailer. See http://www.nxp.com/documents/data_sheet/MF1S503x.pdf sections 8.6 and 8.7:
00041  *        Bytes 0-5:   Key A
00042  *        Bytes 6-8:   Access Bits
00043  *        Bytes 9:     User data
00044  *        Bytes 10-15: Key B (or user data)
00045  *    Block 0 is read only manufacturer data.
00046  *    To access a block, an authentication using a key from the block's sector must be performed first.
00047  *    Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11).
00048  *    All keys are set to FFFFFFFFFFFFh at chip delivery.
00049  *    Warning: Please read section 8.7 "Memory Access". It includes this text: if the PICC detects a format violation the whole sector is irreversibly blocked.
00050  *    To use a block in "value block" mode (for Increment/Decrement operations) you need to change the sector trailer. Use PICC_SetAccessBits() to calculate the bit patterns.
00051  * MIFARE Classic 4K (MF1S703x):
00052  *    Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes.
00053  *    The blocks are numbered 0-255.
00054  *    The last block in each sector is the Sector Trailer like above.
00055  * MIFARE Classic Mini (MF1 IC S20):
00056  *    Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes.
00057  *    The blocks are numbered 0-19.
00058  *    The last block in each sector is the Sector Trailer like above.
00059  *
00060  * MIFARE Ultralight (MF0ICU1):
00061  *    Has 16 pages of 4 bytes = 64 bytes.
00062  *    Pages 0 + 1 is used for the 7-byte UID.
00063  *    Page 2 contains the last chech digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2)
00064  *    Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0.
00065  *    Pages 4-15 are read/write unless blocked by the lock bytes in page 2.
00066  * MIFARE Ultralight C (MF0ICU2):
00067  *    Has 48 pages of 4 bytes = 64 bytes.
00068  *    Pages 0 + 1 is used for the 7-byte UID.
00069  *    Page 2 contains the last chech digit for the UID, one byte manufacturer internal data, and the lock bytes (see http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf section 8.5.2)
00070  *    Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0.
00071  *    Pages 4-39 are read/write unless blocked by the lock bytes in page 2.
00072  *    Page 40 Lock bytes
00073  *    Page 41 16 bit one way counter
00074  *    Pages 42-43 Authentication configuration
00075  *    Pages 44-47 Authentication key
00076  */
00077 #ifndef MFRC522_h
00078 #define MFRC522_h
00079 
00080 #include "mbed.h"
00081 
00082 /**
00083 * MFRC522 example
00084 *
00085 * @code
00086 * #include "mbed.h"
00087 * #include "MFRC522.h"
00088 *
00089 * //KL25Z Pins for MFRC522 SPI interface
00090 * #define SPI_MOSI    PTC6
00091 * #define SPI_MISO    PTC7
00092 * #define SPI_SCLK    PTC5
00093 * #define SPI_CS      PTC4
00094 * // KL25Z Pin for MFRC522 reset
00095 * #define MF_RESET    PTC3
00096 * // KL25Z Pins for Debug UART port
00097 * #define UART_RX     PTA1
00098 * #define UART_TX     PTA2
00099 *
00100 * DigitalOut LedRed   (LED_RED);
00101 * DigitalOut LedGreen (LED_GREEN);
00102 *
00103 * Serial     DebugUART(UART_TX, UART_RX);
00104 * MFRC522    RfChip   (SPI_MOSI, SPI_MISO, SPI_SCLK, SPI_CS, MF_RESET);
00105 *
00106 * int main(void) {
00107 *   // Set debug UART speed
00108 *   DebugUART.baud(115200);
00109 *
00110 *   // Init. RC522 Chip
00111 *   RfChip.PCD_Init();
00112 *
00113 *   while (true) {
00114 *     LedRed   = 1;
00115 *     LedGreen = 1;
00116 *
00117 *     // Look for new cards
00118 *     if ( ! RfChip.PICC_IsNewCardPresent())
00119 *     {
00120 *       wait_ms(500);
00121 *       continue;
00122 *     }
00123 *
00124 *     LedRed   = 0;
00125 *
00126 *     // Select one of the cards
00127 *     if ( ! RfChip.PICC_ReadCardSerial())
00128 *     {
00129 *       wait_ms(500);
00130 *       continue;
00131 *     }
00132 *
00133 *     LedRed   = 1;
00134 *     LedGreen = 0;
00135 *
00136 *     // Print Card UID
00137 *     printf("Card UID: ");
00138 *     for (uint8_t i = 0; i < RfChip.uid.size; i++)
00139 *     {
00140 *       printf(" %X02", RfChip.uid.uidByte[i]);
00141 *     }
00142 *     printf("\n\r");
00143 *
00144 *     // Print Card type
00145 *     uint8_t piccType = RfChip.PICC_GetType(RfChip.uid.sak);
00146 *     printf("PICC Type: %s \n\r", RfChip.PICC_GetTypeName(piccType));
00147 *     wait_ms(1000);
00148 *   }
00149 * }
00150 * @endcode
00151 */
00152 
00153 class MFRC522 {
00154 public:
00155 
00156   /**
00157    * MFRC522 registers (described in chapter 9 of the datasheet).
00158    * When using SPI all addresses are shifted one bit left in the "SPI address byte" (section 8.1.2.3)
00159    */
00160   enum PCD_Register {
00161     // Page 0: Command and status
00162     //                0x00        // reserved for future use
00163     CommandReg      = 0x01 << 1,  // starts and stops command execution
00164     ComIEnReg       = 0x02 << 1,  // enable and disable interrupt request control bits
00165     DivIEnReg       = 0x03 << 1,  // enable and disable interrupt request control bits
00166     ComIrqReg       = 0x04 << 1,  // interrupt request bits
00167     DivIrqReg       = 0x05 << 1,  // interrupt request bits
00168     ErrorReg        = 0x06 << 1,  // error bits showing the error status of the last command executed
00169     Status1Reg      = 0x07 << 1,  // communication status bits
00170     Status2Reg      = 0x08 << 1,  // receiver and transmitter status bits
00171     FIFODataReg     = 0x09 << 1,  // input and output of 64 byte FIFO buffer
00172     FIFOLevelReg    = 0x0A << 1,  // number of bytes stored in the FIFO buffer
00173     WaterLevelReg   = 0x0B << 1,  // level for FIFO underflow and overflow warning
00174     ControlReg      = 0x0C << 1,  // miscellaneous control registers
00175     BitFramingReg   = 0x0D << 1,  // adjustments for bit-oriented frames
00176     CollReg         = 0x0E << 1,  // bit position of the first bit-collision detected on the RF interface
00177     //                0x0F        // reserved for future use
00178 
00179     // Page 1:Command
00180     //                0x10        // reserved for future use
00181     ModeReg         = 0x11 << 1,  // defines general modes for transmitting and receiving
00182     TxModeReg       = 0x12 << 1,  // defines transmission data rate and framing
00183     RxModeReg       = 0x13 << 1,  // defines reception data rate and framing
00184     TxControlReg    = 0x14 << 1,  // controls the logical behavior of the antenna driver pins TX1 and TX2
00185     TxASKReg        = 0x15 << 1,  // controls the setting of the transmission modulation
00186     TxSelReg        = 0x16 << 1,  // selects the internal sources for the antenna driver
00187     RxSelReg        = 0x17 << 1,  // selects internal receiver settings
00188     RxThresholdReg  = 0x18 << 1,  // selects thresholds for the bit decoder
00189     DemodReg        = 0x19 << 1,  // defines demodulator settings
00190     //                0x1A        // reserved for future use
00191     //                0x1B        // reserved for future use
00192     MfTxReg         = 0x1C << 1,  // controls some MIFARE communication transmit parameters
00193     MfRxReg         = 0x1D << 1,  // controls some MIFARE communication receive parameters
00194     //                0x1E        // reserved for future use
00195     SerialSpeedReg  = 0x1F << 1,  // selects the speed of the serial UART interface
00196 
00197     // Page 2: Configuration
00198     //                0x20        // reserved for future use
00199     CRCResultRegH   = 0x21 << 1,  // shows the MSB and LSB values of the CRC calculation
00200     CRCResultRegL   = 0x22 << 1,
00201     //                0x23        // reserved for future use
00202     ModWidthReg     = 0x24 << 1,  // controls the ModWidth setting?
00203     //                0x25        // reserved for future use
00204     RFCfgReg        = 0x26 << 1,  // configures the receiver gain
00205     GsNReg          = 0x27 << 1,  // selects the conductance of the antenna driver pins TX1 and TX2 for modulation
00206     CWGsPReg        = 0x28 << 1,  // defines the conductance of the p-driver output during periods of no modulation
00207     ModGsPReg       = 0x29 << 1,  // defines the conductance of the p-driver output during periods of modulation
00208     TModeReg        = 0x2A << 1,  // defines settings for the internal timer
00209     TPrescalerReg   = 0x2B << 1,  // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg.
00210     TReloadRegH     = 0x2C << 1,  // defines the 16-bit timer reload value
00211     TReloadRegL     = 0x2D << 1,
00212     TCntValueRegH   = 0x2E << 1,  // shows the 16-bit timer value
00213     TCntValueRegL   = 0x2F << 1,
00214 
00215     // Page 3:Test Registers
00216     //                0x30        // reserved for future use
00217     TestSel1Reg     = 0x31 << 1,  // general test signal configuration
00218     TestSel2Reg     = 0x32 << 1,  // general test signal configuration
00219     TestPinEnReg    = 0x33 << 1,  // enables pin output driver on pins D1 to D7
00220     TestPinValueReg = 0x34 << 1,  // defines the values for D1 to D7 when it is used as an I/O bus
00221     TestBusReg      = 0x35 << 1,  // shows the status of the internal test bus
00222     AutoTestReg     = 0x36 << 1,  // controls the digital self test
00223     VersionReg      = 0x37 << 1,  // shows the software version
00224     AnalogTestReg   = 0x38 << 1,  // controls the pins AUX1 and AUX2
00225     TestDAC1Reg     = 0x39 << 1,  // defines the test value for TestDAC1
00226     TestDAC2Reg     = 0x3A << 1,  // defines the test value for TestDAC2
00227     TestADCReg      = 0x3B << 1   // shows the value of ADC I and Q channels
00228     //                0x3C        // reserved for production tests
00229     //                0x3D        // reserved for production tests
00230     //                0x3E        // reserved for production tests
00231     //                0x3F        // reserved for production tests
00232   };
00233 
00234   // MFRC522 commands Described in chapter 10 of the datasheet.
00235   enum PCD_Command {
00236     PCD_Idle               = 0x00,   // no action, cancels current command execution
00237     PCD_Mem                = 0x01,   // stores 25 bytes into the internal buffer
00238     PCD_GenerateRandomID   = 0x02,   // generates a 10-byte random ID number
00239     PCD_CalcCRC            = 0x03,   // activates the CRC coprocessor or performs a self test
00240     PCD_Transmit           = 0x04,   // transmits data from the FIFO buffer
00241     PCD_NoCmdChange        = 0x07,   // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit
00242     PCD_Receive            = 0x08,   // activates the receiver circuits
00243     PCD_Transceive         = 0x0C,   // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission
00244     PCD_MFAuthent          = 0x0E,   // performs the MIFARE standard authentication as a reader
00245     PCD_SoftReset          = 0x0F    // resets the MFRC522
00246   };
00247 
00248   // Commands sent to the PICC.
00249   enum PICC_Command {
00250     // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4)
00251     PICC_CMD_REQA          = 0x26,   // REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
00252     PICC_CMD_WUPA          = 0x52,   // 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.
00253     PICC_CMD_CT            = 0x88,   // Cascade Tag. Not really a command, but used during anti collision.
00254     PICC_CMD_SEL_CL1       = 0x93,   // Anti collision/Select, Cascade Level 1
00255     PICC_CMD_SEL_CL2       = 0x95,   // Anti collision/Select, Cascade Level 1
00256     PICC_CMD_SEL_CL3       = 0x97,   // Anti collision/Select, Cascade Level 1
00257     PICC_CMD_HLTA          = 0x50,   // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT.
00258 
00259     // The commands used for MIFARE Classic (from http://www.nxp.com/documents/data_sheet/MF1S503x.pdf, Section 9)
00260     // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector.
00261     // The read/write commands can also be used for MIFARE Ultralight.
00262     PICC_CMD_MF_AUTH_KEY_A = 0x60,   // Perform authentication with Key A
00263     PICC_CMD_MF_AUTH_KEY_B = 0x61,   // Perform authentication with Key B
00264     PICC_CMD_MF_READ       = 0x30,   // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight.
00265     PICC_CMD_MF_WRITE      = 0xA0,   // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight.
00266     PICC_CMD_MF_DECREMENT  = 0xC0,   // Decrements the contents of a block and stores the result in the internal data register.
00267     PICC_CMD_MF_INCREMENT  = 0xC1,   // Increments the contents of a block and stores the result in the internal data register.
00268     PICC_CMD_MF_RESTORE    = 0xC2,   // Reads the contents of a block into the internal data register.
00269     PICC_CMD_MF_TRANSFER   = 0xB0,   // Writes the contents of the internal data register to a block.
00270 
00271     // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6)
00272     // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight.
00273     PICC_CMD_UL_WRITE      = 0xA2    // Writes one 4 byte page to the PICC.
00274   };
00275 
00276   // MIFARE constants that does not fit anywhere else
00277   enum MIFARE_Misc {
00278     MF_ACK                 = 0xA,    // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK.
00279     MF_KEY_SIZE            = 6       // A Mifare Crypto1 key is 6 bytes.
00280   };
00281 
00282   // PICC types we can detect. Remember to update PICC_GetTypeName() if you add more.
00283   enum PICC_Type {
00284     PICC_TYPE_UNKNOWN      = 0,
00285     PICC_TYPE_ISO_14443_4  = 1,  // PICC compliant with ISO/IEC 14443-4
00286     PICC_TYPE_ISO_18092    = 2,  // PICC compliant with ISO/IEC 18092 (NFC)
00287     PICC_TYPE_MIFARE_MINI  = 3,  // MIFARE Classic protocol, 320 bytes
00288     PICC_TYPE_MIFARE_1K    = 4,  // MIFARE Classic protocol, 1KB
00289     PICC_TYPE_MIFARE_4K    = 5,  // MIFARE Classic protocol, 4KB
00290     PICC_TYPE_MIFARE_UL    = 6,  // MIFARE Ultralight or Ultralight C
00291     PICC_TYPE_MIFARE_PLUS  = 7,  // MIFARE Plus
00292     PICC_TYPE_TNP3XXX      = 8,  // Only mentioned in NXP AN 10833 MIFARE Type Identification Procedure
00293     PICC_TYPE_NOT_COMPLETE = 255 // SAK indicates UID is not complete.
00294   };
00295 
00296   // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more.
00297   enum StatusCode {
00298     STATUS_OK              = 1,  // Success
00299     STATUS_ERROR           = 2,  // Error in communication
00300     STATUS_COLLISION       = 3,  // Collision detected
00301     STATUS_TIMEOUT         = 4,  // Timeout in communication.
00302     STATUS_NO_ROOM         = 5,  // A buffer is not big enough.
00303     STATUS_INTERNAL_ERROR  = 6,  // Internal error in the code. Should not happen ;-)
00304     STATUS_INVALID         = 7,  // Invalid argument.
00305     STATUS_CRC_WRONG       = 8,  // The CRC_A does not match
00306     STATUS_MIFARE_NACK     = 9   // A MIFARE PICC responded with NAK.
00307   };
00308 
00309   // A struct used for passing the UID of a PICC.
00310   typedef struct {
00311     uint8_t    size;     // Number of bytes in the UID. 4, 7 or 10.
00312     uint8_t    uidByte[10];
00313     uint8_t    sak;      // The SAK (Select acknowledge) byte returned from the PICC after successful selection.
00314   } Uid;
00315 
00316   // A struct used for passing a MIFARE Crypto1 key
00317   typedef struct {
00318     uint8_t    keyByte[MF_KEY_SIZE];
00319   } MIFARE_Key;
00320 
00321   // Member variables
00322   Uid uid;                // Used by PICC_ReadCardSerial().
00323 
00324   // Size of the MFRC522 FIFO
00325   static const uint8_t FIFO_SIZE = 64;   // The FIFO is 64 bytes.
00326 
00327   /**
00328   * MFRC522 constructor
00329   *
00330   * @param mosi  SPI MOSI pin
00331   * @param miso  SPI MISO pin
00332   * @param sclk  SPI SCLK pin
00333   * @param cs    SPI CS pin
00334   * @param reset Reset pin
00335   */
00336   MFRC522(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName reset);
00337 
00338   /**
00339   * MFRC522 destructor
00340   */
00341   ~MFRC522();
00342   
00343 
00344   // ************************************************************************************
00345   //! @name Functions for manipulating the MFRC522
00346   // ************************************************************************************
00347   //@{
00348 
00349   /**
00350   * Initializes the MFRC522 chip.
00351   */
00352   void    PCD_Init           (void);
00353 
00354   /**
00355   * Performs a soft reset on the MFRC522 chip and waits for it to be ready again.
00356   */
00357   void    PCD_Reset          (void);
00358 
00359   /**
00360   * Turns the antenna on by enabling pins TX1 and TX2.
00361   * After a reset these pins disabled.
00362   */
00363   void    PCD_AntennaOn      (void);
00364 
00365   /**
00366   * Writes a byte to the specified register in the MFRC522 chip.
00367   * The interface is described in the datasheet section 8.1.2.
00368   *
00369   * @param reg   The register to write to. One of the PCD_Register enums.
00370   * @param value The value to write.
00371   */
00372   void    PCD_WriteRegister  (uint8_t reg, uint8_t value);
00373 
00374   /**
00375   * Writes a number of bytes to the specified register in the MFRC522 chip.
00376   * The interface is described in the datasheet section 8.1.2.
00377   *
00378   * @param reg    The register to write to. One of the PCD_Register enums.
00379   * @param count  The number of bytes to write to the register
00380   * @param values The values to write. Byte array.
00381   */
00382   void    PCD_WriteRegister  (uint8_t reg, uint8_t count, uint8_t *values);
00383 
00384   /**
00385   * Reads a byte from the specified register in the MFRC522 chip.
00386   * The interface is described in the datasheet section 8.1.2.
00387   *
00388   * @param reg The register to read from. One of the PCD_Register enums.
00389   * @returns Register value
00390   */
00391   uint8_t PCD_ReadRegister   (uint8_t reg);
00392 
00393   /**
00394   * Reads a number of bytes from the specified register in the MFRC522 chip.
00395   * The interface is described in the datasheet section 8.1.2.
00396   *
00397   * @param reg     The register to read from. One of the PCD_Register enums.
00398   * @param count   The number of bytes to read.
00399   * @param values  Byte array to store the values in.
00400   * @param rxAlign Only bit positions rxAlign..7 in values[0] are updated.
00401   */
00402   void    PCD_ReadRegister   (uint8_t reg, uint8_t count, uint8_t *values, uint8_t rxAlign = 0);
00403 
00404   /**
00405   * Sets the bits given in mask in register reg.
00406   *
00407   * @param reg  The register to update. One of the PCD_Register enums.
00408   * @param mask The bits to set.
00409   */
00410   void    PCD_SetRegisterBits(uint8_t reg, uint8_t mask);
00411 
00412   /**
00413   * Clears the bits given in mask from register reg.
00414   *
00415   * @param reg  The register to update. One of the PCD_Register enums.
00416   * @param mask The bits to clear.
00417   */
00418   void    PCD_ClrRegisterBits(uint8_t reg, uint8_t mask);
00419 
00420   /**
00421   * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A.
00422   *
00423   * @param data   Pointer to the data to transfer to the FIFO for CRC calculation.
00424   * @param length The number of bytes to transfer.
00425   * @param result Pointer to result buffer. Result is written to result[0..1], low byte first.
00426   * @return STATUS_OK on success, STATUS_??? otherwise.
00427   */
00428   uint8_t PCD_CalculateCRC   (uint8_t *data, uint8_t length, uint8_t *result);
00429 
00430   /**
00431    * Executes the Transceive command.
00432    * CRC validation can only be done if backData and backLen are specified.
00433    *
00434    * @param sendData Pointer to the data to transfer to the FIFO.
00435    * @param sendLen  Number of bytes to transfer to the FIFO.
00436    * @param backData NULL or pointer to buffer if data should be read back after executing the command.
00437    * @param backLen  Max number of bytes to write to *backData. Out: The number of bytes returned.
00438    * @param validBits The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL.
00439    * @param rxAlign  Defines the bit position in backData[0] for the first bit received. Default 0.
00440    * @param checkCRC True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
00441    *
00442    * @return STATUS_OK on success, STATUS_??? otherwise.
00443    */
00444   uint8_t PCD_TransceiveData (uint8_t *sendData,
00445                               uint8_t sendLen,
00446                               uint8_t *backData,
00447                               uint8_t *backLen,
00448                               uint8_t *validBits = NULL,
00449                               uint8_t rxAlign    = 0,
00450                               bool    checkCRC   = false);
00451 
00452 
00453   /**
00454    * Transfers data to the MFRC522 FIFO, executes a commend, waits for completion and transfers data back from the FIFO.
00455    * CRC validation can only be done if backData and backLen are specified.
00456    *
00457    * @param command   The command to execute. One of the PCD_Command enums.
00458    * @param waitIRq   The bits in the ComIrqReg register that signals successful completion of the command.
00459    * @param sendData  Pointer to the data to transfer to the FIFO.
00460    * @param sendLen   Number of bytes to transfer to the FIFO.
00461    * @param backData  NULL or pointer to buffer if data should be read back after executing the command.
00462    * @param backLen   In: Max number of bytes to write to *backData. Out: The number of bytes returned.
00463    * @param validBits In/Out: The number of valid bits in the last byte. 0 for 8 valid bits.
00464    * @param rxAlign   In: Defines the bit position in backData[0] for the first bit received. Default 0.
00465    * @param checkCRC  In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated.
00466    *
00467    * @return STATUS_OK on success, STATUS_??? otherwise.
00468    */
00469   uint8_t PCD_CommunicateWithPICC(uint8_t command,
00470                                   uint8_t waitIRq,
00471                                   uint8_t *sendData,
00472                                   uint8_t sendLen,
00473                                   uint8_t *backData  = NULL,
00474                                   uint8_t *backLen   = NULL,
00475                                   uint8_t *validBits = NULL,
00476                                   uint8_t rxAlign    = 0,
00477                                   bool    checkCRC   = false);
00478 
00479   /**
00480    * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame.
00481    * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
00482    *
00483    * @param bufferATQA  The buffer to store the ATQA (Answer to request) in
00484    * @param bufferSize  Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
00485    * 
00486    * @return STATUS_OK on success, STATUS_??? otherwise.
00487    */
00488   uint8_t PICC_RequestA      (uint8_t *bufferATQA, uint8_t *bufferSize);
00489   
00490   /**
00491    * 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.
00492    * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
00493    *
00494    * @param bufferATQA  The buffer to store the ATQA (Answer to request) in
00495    * @param bufferSize  Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
00496    * 
00497    * @return STATUS_OK on success, STATUS_??? otherwise.
00498    */  
00499   uint8_t PICC_WakeupA       (uint8_t *bufferATQA, uint8_t *bufferSize);
00500   
00501   /**
00502    * Transmits REQA or WUPA commands.
00503    * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design.
00504    *
00505    * @param command     The command to send - PICC_CMD_REQA or PICC_CMD_WUPA
00506    * @param bufferATQA  The buffer to store the ATQA (Answer to request) in
00507    * @param bufferSize  Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK.
00508    * 
00509    * @return STATUS_OK on success, STATUS_??? otherwise.
00510    */  
00511   uint8_t PICC_REQA_or_WUPA  (uint8_t command, uint8_t *bufferATQA, uint8_t *bufferSize);
00512   
00513   /**
00514    * Transmits SELECT/ANTICOLLISION commands to select a single PICC.
00515    * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA().
00516    * On success:
00517    *   - 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.)
00518    *   - The UID size and value of the chosen PICC is returned in *uid along with the SAK.
00519    * 
00520    * A PICC UID consists of 4, 7 or 10 bytes.
00521    * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used:
00522    *
00523    *   UID size        Number of UID bytes                Cascade levels                Example of PICC
00524    *   ========        ===================                ==============                ===============
00525    *   single                   4                                1                      MIFARE Classic
00526    *   double                   7                                2                      MIFARE Ultralight
00527    *   triple                  10                                3                      Not currently in use?
00528    *
00529    *
00530    * @param uid        Pointer to Uid struct. Normally output, but can also be used to supply a known UID.
00531    * @param validBits  The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size.
00532    *   
00533    * @return STATUS_OK on success, STATUS_??? otherwise.
00534    */
00535   uint8_t PICC_Select        (Uid *uid, uint8_t validBits = 0);
00536   
00537   /**
00538    * Instructs a PICC in state ACTIVE(*) to go to state HALT.
00539    *
00540    * @return STATUS_OK on success, STATUS_??? otherwise.
00541    */  
00542   uint8_t PICC_HaltA         (void);
00543   
00544   // ************************************************************************************
00545   //@}
00546 
00547 
00548   // ************************************************************************************
00549   //! @name Functions for communicating with MIFARE PICCs
00550   // ************************************************************************************
00551   //@{
00552   
00553   /**
00554    * Executes the MFRC522 MFAuthent command.
00555    * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card.
00556    * 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.
00557    * For use with MIFARE Classic PICCs.
00558    * The PICC must be selected - ie in state ACTIVE(*) - before calling this function.
00559    * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start.
00560    * 
00561    * All keys are set to FFFFFFFFFFFFh at chip delivery.
00562    *
00563    * @param command    PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B
00564    * @param blockAddr  The block number. See numbering in the comments in the .h file.
00565    * @param key        Pointer to the Crypteo1 key to use (6 bytes)
00566    * @param uid        Pointer to Uid struct. The first 4 bytes of the UID is used.
00567    * 
00568    * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key.
00569    */
00570   uint8_t PCD_Authenticate   (uint8_t command, uint8_t blockAddr, MIFARE_Key *key, Uid *uid);
00571   
00572   /**
00573    * Used to exit the PCD from its authenticated state.
00574    * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start.
00575    */
00576   void    PCD_StopCrypto1    (void);
00577   
00578   /**
00579    * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC.
00580    * 
00581    * For MIFARE Classic the sector containing the block must be authenticated before calling this function.
00582    * 
00583    * For MIFARE Ultralight only addresses 00h to 0Fh are decoded.
00584    * The MF0ICU1 returns a NAK for higher addresses.
00585    * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument.
00586    * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned.
00587    * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned.
00588    * 
00589    * The buffer must be at least 18 bytes because a CRC_A is also returned.
00590    * Checks the CRC_A before returning STATUS_OK.
00591    *
00592    * @param blockAddr  MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from.
00593    * @param buffer     The buffer to store the data in
00594    * @param bufferSize Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK.
00595    *
00596    * @return STATUS_OK on success, STATUS_??? otherwise.
00597    */
00598   uint8_t MIFARE_Read        (uint8_t blockAddr, uint8_t *buffer, uint8_t *bufferSize);
00599   
00600   /**
00601    * Writes 16 bytes to the active PICC.
00602    * 
00603    * For MIFARE Classic the sector containing the block must be authenticated before calling this function.
00604    * 
00605    * For MIFARE Ultralight the opretaion is called "COMPATIBILITY WRITE".
00606    * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3)
00607    * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0.
00608    *
00609    * @param blockAddr  MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to.
00610    * @param buffer     The 16 bytes to write to the PICC
00611    * @param bufferSize Buffer size, must be at least 16 bytes. Exactly 16 bytes are written.
00612    *
00613    * @return STATUS_OK on success, STATUS_??? otherwise.
00614  */
00615   uint8_t MIFARE_Write       (uint8_t blockAddr, uint8_t *buffer, uint8_t bufferSize);
00616   
00617   /**
00618    * Writes a 4 byte page to the active MIFARE Ultralight PICC.
00619    * 
00620    * @param page       The page (2-15) to write to.
00621    * @param buffer     The 4 bytes to write to the PICC
00622    * @param bufferSize Buffer size, must be at least 4 bytes. Exactly 4 bytes are written.
00623    *
00624    * @return STATUS_OK on success, STATUS_??? otherwise.
00625    */
00626   uint8_t MIFARE_UltralightWrite(uint8_t page, uint8_t *buffer, uint8_t bufferSize);
00627    
00628   /**
00629    * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory.
00630    * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
00631    * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
00632    * Use MIFARE_Transfer() to store the result in a block.
00633    *
00634    * @param blockAddr The block (0-0xff) number.
00635    * @param delta     This number is subtracted from the value of block blockAddr.
00636    *
00637    * @return STATUS_OK on success, STATUS_??? otherwise.
00638    */
00639   uint8_t MIFARE_Decrement   (uint8_t blockAddr, uint32_t delta);
00640   
00641   /**
00642    * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory.
00643    * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
00644    * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
00645    * Use MIFARE_Transfer() to store the result in a block.
00646    * 
00647    * @param blockAddr The block (0-0xff) number.
00648    * @param delta     This number is added to the value of block blockAddr.
00649    *
00650    * @return STATUS_OK on success, STATUS_??? otherwise.
00651    */
00652   uint8_t MIFARE_Increment   (uint8_t blockAddr, uint32_t delta);
00653   
00654   /**
00655    * MIFARE Restore copies the value of the addressed block into a volatile memory.
00656    * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
00657    * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
00658    * Use MIFARE_Transfer() to store the result in a block.
00659    * 
00660    * @param blockAddr The block (0-0xff) number.
00661    *
00662    * @return STATUS_OK on success, STATUS_??? otherwise.
00663    */
00664   uint8_t MIFARE_Restore     (uint8_t blockAddr);
00665   
00666   /**
00667    * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block.
00668    * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function.
00669    * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001].
00670    * 
00671    * @param blockAddr The block (0-0xff) number.
00672    *
00673    * @return STATUS_OK on success, STATUS_??? otherwise.
00674    */
00675   uint8_t MIFARE_Transfer    (uint8_t blockAddr);
00676   
00677   // ************************************************************************************
00678   //@}
00679 
00680 
00681   // ************************************************************************************
00682   //! @name Support functions
00683   // ************************************************************************************
00684   //@{
00685   
00686   /**
00687    * Wrapper for MIFARE protocol communication.
00688    * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout.
00689    * 
00690    * @param sendData      Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A.
00691    * @param sendLen       Number of bytes in sendData.
00692    * @param acceptTimeout True => A timeout is also success
00693    *
00694    * @return STATUS_OK on success, STATUS_??? otherwise.
00695    */
00696   uint8_t PCD_MIFARE_Transceive(uint8_t *sendData, uint8_t sendLen, bool acceptTimeout = false);
00697   
00698   /**
00699    * Translates the SAK (Select Acknowledge) to a PICC type.
00700    * 
00701    * @param sak The SAK byte returned from PICC_Select().
00702    *
00703    * @return PICC_Type
00704    */
00705   uint8_t PICC_GetType         (uint8_t sak);
00706   
00707   /**
00708    * Returns a string pointer to the PICC type name.
00709    * 
00710    * @param type One of the PICC_Type enums.
00711    *
00712    * @return A string pointer to the PICC type name.
00713    */
00714   char*   PICC_GetTypeName     (uint8_t type);
00715   
00716   /**
00717    * Returns a string pointer to a status code name.
00718    * 
00719    * @param code One of the StatusCode enums.
00720    *
00721    * @return A string pointer to a status code name.
00722    */
00723   char*   GetStatusCodeName    (uint8_t code);
00724   
00725   /**
00726    * Calculates the bit pattern needed for the specified access bits. In the [C1 C2 C3] tupples C1 is MSB (=4) and C3 is LSB (=1).
00727    * 
00728    * @param accessBitBuffer Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set.
00729    * @param g0              Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39)
00730    * @param g1              Access bits [C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39)
00731    * @param g2              Access bits [C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39)
00732    * @param g3              Access bits [C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39)
00733    */
00734   void    MIFARE_SetAccessBits (uint8_t *accessBitBuffer,
00735                                 uint8_t g0,
00736                                 uint8_t g1,
00737                                 uint8_t g2,
00738                                 uint8_t g3);
00739                                 
00740   // ************************************************************************************
00741   //@}
00742 
00743 
00744   // ************************************************************************************
00745   //! @name Convenience functions - does not add extra functionality
00746   // ************************************************************************************
00747   //@{
00748   
00749   /**
00750    * Returns true if a PICC responds to PICC_CMD_REQA.
00751    * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored.
00752    * 
00753    * @return bool
00754    */
00755   bool    PICC_IsNewCardPresent(void);
00756   
00757   /**
00758    * Simple wrapper around PICC_Select.
00759    * Returns true if a UID could be read.
00760    * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first.
00761    * The read UID is available in the class variable uid.
00762    * 
00763    * @return bool
00764    */
00765   bool    PICC_ReadCardSerial  (void);
00766   
00767   // ************************************************************************************
00768   //@}
00769 
00770 
00771 private:
00772   SPI              m_SPI;
00773   DigitalOut       m_CS;
00774   DigitalOut       m_RESET;
00775 
00776   /**
00777    * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore.
00778    * 
00779    * @param command    The command to use
00780    * @param blockAddr  The block (0-0xff) number.
00781    * @param data       The data to transfer in step 2
00782    *
00783    * @return STATUS_OK on success, STATUS_??? otherwise.
00784    */
00785   uint8_t MIFARE_TwoStepHelper(uint8_t command, uint8_t blockAddr, uint32_t data);
00786 };
00787 
00788 #endif