RFID-RC522 code for testing a cheap 13.56 MHz module with the Nucleo F401RE. Based on the MFRC522 code by Martin Olejar.

Dependencies:   mbed

Dependents:   RFID-RC522

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