Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
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 char uidcheck[100]; 00311 uint8_t sak; // The SAK (Select acknowledge) byte returned from the PICC after successful selection. 00312 } Uid; 00313 00314 // A struct used for passing a MIFARE Crypto1 key 00315 typedef struct { 00316 uint8_t keyByte[MF_KEY_SIZE]; 00317 } MIFARE_Key; 00318 00319 // Member variables 00320 Uid uid; // Used by PICC_ReadCardSerial(). 00321 00322 // Size of the MFRC522 FIFO 00323 static const uint8_t FIFO_SIZE = 64; // The FIFO is 64 bytes. 00324 00325 /** 00326 * MFRC522 constructor 00327 * 00328 * @param mosi SPI MOSI pin 00329 * @param miso SPI MISO pin 00330 * @param sclk SPI SCLK pin 00331 * @param cs SPI CS pin 00332 * @param reset Reset pin 00333 */ 00334 MFRC522(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName reset); 00335 00336 /** 00337 * MFRC522 destructor 00338 */ 00339 ~MFRC522(); 00340 00341 00342 // ************************************************************************************ 00343 //! @name Functions for manipulating the MFRC522 00344 // ************************************************************************************ 00345 //@{ 00346 00347 /** 00348 * Initializes the MFRC522 chip. 00349 */ 00350 void PCD_Init (void); 00351 00352 /** 00353 * Performs a soft reset on the MFRC522 chip and waits for it to be ready again. 00354 */ 00355 void PCD_Reset (void); 00356 00357 /** 00358 * Turns the antenna on by enabling pins TX1 and TX2. 00359 * After a reset these pins disabled. 00360 */ 00361 void PCD_AntennaOn (void); 00362 00363 /** 00364 * Writes a byte to the specified register in the MFRC522 chip. 00365 * The interface is described in the datasheet section 8.1.2. 00366 * 00367 * @param reg The register to write to. One of the PCD_Register enums. 00368 * @param value The value to write. 00369 */ 00370 void PCD_WriteRegister (uint8_t reg, uint8_t value); 00371 00372 /** 00373 * Writes a number of bytes to the specified register in the MFRC522 chip. 00374 * The interface is described in the datasheet section 8.1.2. 00375 * 00376 * @param reg The register to write to. One of the PCD_Register enums. 00377 * @param count The number of bytes to write to the register 00378 * @param values The values to write. Byte array. 00379 */ 00380 void PCD_WriteRegister (uint8_t reg, uint8_t count, uint8_t *values); 00381 00382 /** 00383 * Reads a byte from the specified register in the MFRC522 chip. 00384 * The interface is described in the datasheet section 8.1.2. 00385 * 00386 * @param reg The register to read from. One of the PCD_Register enums. 00387 * @returns Register value 00388 */ 00389 uint8_t PCD_ReadRegister (uint8_t reg); 00390 00391 /** 00392 * Reads a number of bytes from the specified register in the MFRC522 chip. 00393 * The interface is described in the datasheet section 8.1.2. 00394 * 00395 * @param reg The register to read from. One of the PCD_Register enums. 00396 * @param count The number of bytes to read. 00397 * @param values Byte array to store the values in. 00398 * @param rxAlign Only bit positions rxAlign..7 in values[0] are updated. 00399 */ 00400 void PCD_ReadRegister (uint8_t reg, uint8_t count, uint8_t *values, uint8_t rxAlign = 0); 00401 00402 /** 00403 * Sets the bits given in mask in register reg. 00404 * 00405 * @param reg The register to update. One of the PCD_Register enums. 00406 * @param mask The bits to set. 00407 */ 00408 void PCD_SetRegisterBits(uint8_t reg, uint8_t mask); 00409 00410 /** 00411 * Clears the bits given in mask from register reg. 00412 * 00413 * @param reg The register to update. One of the PCD_Register enums. 00414 * @param mask The bits to clear. 00415 */ 00416 void PCD_ClrRegisterBits(uint8_t reg, uint8_t mask); 00417 00418 /** 00419 * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A. 00420 * 00421 * @param data Pointer to the data to transfer to the FIFO for CRC calculation. 00422 * @param length The number of bytes to transfer. 00423 * @param result Pointer to result buffer. Result is written to result[0..1], low byte first. 00424 * @return STATUS_OK on success, STATUS_??? otherwise. 00425 */ 00426 uint8_t PCD_CalculateCRC (uint8_t *data, uint8_t length, uint8_t *result); 00427 00428 /** 00429 * Executes the Transceive command. 00430 * CRC validation can only be done if backData and backLen are specified. 00431 * 00432 * @param sendData Pointer to the data to transfer to the FIFO. 00433 * @param sendLen Number of bytes to transfer to the FIFO. 00434 * @param backData NULL or pointer to buffer if data should be read back after executing the command. 00435 * @param backLen Max number of bytes to write to *backData. Out: The number of bytes returned. 00436 * @param validBits The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL. 00437 * @param rxAlign Defines the bit position in backData[0] for the first bit received. Default 0. 00438 * @param checkCRC True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 00439 * 00440 * @return STATUS_OK on success, STATUS_??? otherwise. 00441 */ 00442 uint8_t PCD_TransceiveData (uint8_t *sendData, 00443 uint8_t sendLen, 00444 uint8_t *backData, 00445 uint8_t *backLen, 00446 uint8_t *validBits = NULL, 00447 uint8_t rxAlign = 0, 00448 bool checkCRC = false); 00449 00450 00451 /** 00452 * Transfers data to the MFRC522 FIFO, executes a commend, waits for completion and transfers data back from the FIFO. 00453 * CRC validation can only be done if backData and backLen are specified. 00454 * 00455 * @param command The command to execute. One of the PCD_Command enums. 00456 * @param waitIRq The bits in the ComIrqReg register that signals successful completion of the command. 00457 * @param sendData Pointer to the data to transfer to the FIFO. 00458 * @param sendLen Number of bytes to transfer to the FIFO. 00459 * @param backData NULL or pointer to buffer if data should be read back after executing the command. 00460 * @param backLen In: Max number of bytes to write to *backData. Out: The number of bytes returned. 00461 * @param validBits In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. 00462 * @param rxAlign In: Defines the bit position in backData[0] for the first bit received. Default 0. 00463 * @param checkCRC In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 00464 * 00465 * @return STATUS_OK on success, STATUS_??? otherwise. 00466 */ 00467 uint8_t PCD_CommunicateWithPICC(uint8_t command, 00468 uint8_t waitIRq, 00469 uint8_t *sendData, 00470 uint8_t sendLen, 00471 uint8_t *backData = NULL, 00472 uint8_t *backLen = NULL, 00473 uint8_t *validBits = NULL, 00474 uint8_t rxAlign = 0, 00475 bool checkCRC = false); 00476 00477 /** 00478 * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. 00479 * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 00480 * 00481 * @param bufferATQA The buffer to store the ATQA (Answer to request) in 00482 * @param bufferSize Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 00483 * 00484 * @return STATUS_OK on success, STATUS_??? otherwise. 00485 */ 00486 uint8_t PICC_RequestA (uint8_t *bufferATQA, uint8_t *bufferSize); 00487 00488 /** 00489 * 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. 00490 * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 00491 * 00492 * @param bufferATQA The buffer to store the ATQA (Answer to request) in 00493 * @param bufferSize Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 00494 * 00495 * @return STATUS_OK on success, STATUS_??? otherwise. 00496 */ 00497 uint8_t PICC_WakeupA (uint8_t *bufferATQA, uint8_t *bufferSize); 00498 00499 /** 00500 * Transmits REQA or WUPA commands. 00501 * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 00502 * 00503 * @param command The command to send - PICC_CMD_REQA or PICC_CMD_WUPA 00504 * @param bufferATQA The buffer to store the ATQA (Answer to request) in 00505 * @param bufferSize Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 00506 * 00507 * @return STATUS_OK on success, STATUS_??? otherwise. 00508 */ 00509 uint8_t PICC_REQA_or_WUPA (uint8_t command, uint8_t *bufferATQA, uint8_t *bufferSize); 00510 00511 /** 00512 * Transmits SELECT/ANTICOLLISION commands to select a single PICC. 00513 * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA(). 00514 * On success: 00515 * - 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.) 00516 * - The UID size and value of the chosen PICC is returned in *uid along with the SAK. 00517 * 00518 * A PICC UID consists of 4, 7 or 10 bytes. 00519 * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used: 00520 * 00521 * UID size Number of UID bytes Cascade levels Example of PICC 00522 * ======== =================== ============== =============== 00523 * single 4 1 MIFARE Classic 00524 * double 7 2 MIFARE Ultralight 00525 * triple 10 3 Not currently in use? 00526 * 00527 * 00528 * @param uid Pointer to Uid struct. Normally output, but can also be used to supply a known UID. 00529 * @param validBits The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size. 00530 * 00531 * @return STATUS_OK on success, STATUS_??? otherwise. 00532 */ 00533 uint8_t PICC_Select (Uid *uid, uint8_t validBits = 0); 00534 00535 /** 00536 * Instructs a PICC in state ACTIVE(*) to go to state HALT. 00537 * 00538 * @return STATUS_OK on success, STATUS_??? otherwise. 00539 */ 00540 uint8_t PICC_HaltA (void); 00541 00542 // ************************************************************************************ 00543 //@} 00544 00545 00546 // ************************************************************************************ 00547 //! @name Functions for communicating with MIFARE PICCs 00548 // ************************************************************************************ 00549 //@{ 00550 00551 /** 00552 * Executes the MFRC522 MFAuthent command. 00553 * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card. 00554 * 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. 00555 * For use with MIFARE Classic PICCs. 00556 * The PICC must be selected - ie in state ACTIVE(*) - before calling this function. 00557 * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start. 00558 * 00559 * All keys are set to FFFFFFFFFFFFh at chip delivery. 00560 * 00561 * @param command PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B 00562 * @param blockAddr The block number. See numbering in the comments in the .h file. 00563 * @param key Pointer to the Crypteo1 key to use (6 bytes) 00564 * @param uid Pointer to Uid struct. The first 4 bytes of the UID is used. 00565 * 00566 * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key. 00567 */ 00568 uint8_t PCD_Authenticate (uint8_t command, uint8_t blockAddr, MIFARE_Key *key, Uid *uid); 00569 00570 /** 00571 * Used to exit the PCD from its authenticated state. 00572 * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start. 00573 */ 00574 void PCD_StopCrypto1 (void); 00575 00576 /** 00577 * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC. 00578 * 00579 * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 00580 * 00581 * For MIFARE Ultralight only addresses 00h to 0Fh are decoded. 00582 * The MF0ICU1 returns a NAK for higher addresses. 00583 * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument. 00584 * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned. 00585 * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned. 00586 * 00587 * The buffer must be at least 18 bytes because a CRC_A is also returned. 00588 * Checks the CRC_A before returning STATUS_OK. 00589 * 00590 * @param blockAddr MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from. 00591 * @param buffer The buffer to store the data in 00592 * @param bufferSize Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK. 00593 * 00594 * @return STATUS_OK on success, STATUS_??? otherwise. 00595 */ 00596 uint8_t MIFARE_Read (uint8_t blockAddr, uint8_t *buffer, uint8_t *bufferSize); 00597 00598 /** 00599 * Writes 16 bytes to the active PICC. 00600 * 00601 * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 00602 * 00603 * For MIFARE Ultralight the opretaion is called "COMPATIBILITY WRITE". 00604 * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3) 00605 * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0. 00606 * 00607 * @param blockAddr MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to. 00608 * @param buffer The 16 bytes to write to the PICC 00609 * @param bufferSize Buffer size, must be at least 16 bytes. Exactly 16 bytes are written. 00610 * 00611 * @return STATUS_OK on success, STATUS_??? otherwise. 00612 */ 00613 uint8_t MIFARE_Write (uint8_t blockAddr, uint8_t *buffer, uint8_t bufferSize); 00614 00615 /** 00616 * Writes a 4 byte page to the active MIFARE Ultralight PICC. 00617 * 00618 * @param page The page (2-15) to write to. 00619 * @param buffer The 4 bytes to write to the PICC 00620 * @param bufferSize Buffer size, must be at least 4 bytes. Exactly 4 bytes are written. 00621 * 00622 * @return STATUS_OK on success, STATUS_??? otherwise. 00623 */ 00624 uint8_t MIFARE_UltralightWrite(uint8_t page, uint8_t *buffer, uint8_t bufferSize); 00625 00626 /** 00627 * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory. 00628 * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 00629 * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 00630 * Use MIFARE_Transfer() to store the result in a block. 00631 * 00632 * @param blockAddr The block (0-0xff) number. 00633 * @param delta This number is subtracted from the value of block blockAddr. 00634 * 00635 * @return STATUS_OK on success, STATUS_??? otherwise. 00636 */ 00637 uint8_t MIFARE_Decrement (uint8_t blockAddr, uint32_t delta); 00638 00639 /** 00640 * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory. 00641 * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 00642 * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 00643 * Use MIFARE_Transfer() to store the result in a block. 00644 * 00645 * @param blockAddr The block (0-0xff) number. 00646 * @param delta This number is added to the value of block blockAddr. 00647 * 00648 * @return STATUS_OK on success, STATUS_??? otherwise. 00649 */ 00650 uint8_t MIFARE_Increment (uint8_t blockAddr, uint32_t delta); 00651 00652 /** 00653 * MIFARE Restore copies the value of the addressed block into a volatile memory. 00654 * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 00655 * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 00656 * Use MIFARE_Transfer() to store the result in a block. 00657 * 00658 * @param blockAddr The block (0-0xff) number. 00659 * 00660 * @return STATUS_OK on success, STATUS_??? otherwise. 00661 */ 00662 uint8_t MIFARE_Restore (uint8_t blockAddr); 00663 00664 /** 00665 * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block. 00666 * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 00667 * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 00668 * 00669 * @param blockAddr The block (0-0xff) number. 00670 * 00671 * @return STATUS_OK on success, STATUS_??? otherwise. 00672 */ 00673 uint8_t MIFARE_Transfer (uint8_t blockAddr); 00674 00675 // ************************************************************************************ 00676 //@} 00677 00678 00679 // ************************************************************************************ 00680 //! @name Support functions 00681 // ************************************************************************************ 00682 //@{ 00683 00684 /** 00685 * Wrapper for MIFARE protocol communication. 00686 * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout. 00687 * 00688 * @param sendData Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A. 00689 * @param sendLen Number of bytes in sendData. 00690 * @param acceptTimeout True => A timeout is also success 00691 * 00692 * @return STATUS_OK on success, STATUS_??? otherwise. 00693 */ 00694 uint8_t PCD_MIFARE_Transceive(uint8_t *sendData, uint8_t sendLen, bool acceptTimeout = false); 00695 00696 /** 00697 * Translates the SAK (Select Acknowledge) to a PICC type. 00698 * 00699 * @param sak The SAK byte returned from PICC_Select(). 00700 * 00701 * @return PICC_Type 00702 */ 00703 uint8_t PICC_GetType (uint8_t sak); 00704 00705 /** 00706 * Returns a string pointer to the PICC type name. 00707 * 00708 * @param type One of the PICC_Type enums. 00709 * 00710 * @return A string pointer to the PICC type name. 00711 */ 00712 char* PICC_GetTypeName (uint8_t type); 00713 00714 /** 00715 * Returns a string pointer to a status code name. 00716 * 00717 * @param code One of the StatusCode enums. 00718 * 00719 * @return A string pointer to a status code name. 00720 */ 00721 char* GetStatusCodeName (uint8_t code); 00722 00723 /** 00724 * 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). 00725 * 00726 * @param accessBitBuffer Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set. 00727 * @param g0 Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 00728 * @param g1 Access bits [C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 00729 * @param g2 Access bits [C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 00730 * @param g3 Access bits [C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 00731 */ 00732 void MIFARE_SetAccessBits (uint8_t *accessBitBuffer, 00733 uint8_t g0, 00734 uint8_t g1, 00735 uint8_t g2, 00736 uint8_t g3); 00737 00738 // ************************************************************************************ 00739 //@} 00740 00741 00742 // ************************************************************************************ 00743 //! @name Convenience functions - does not add extra functionality 00744 // ************************************************************************************ 00745 //@{ 00746 00747 /** 00748 * Returns true if a PICC responds to PICC_CMD_REQA. 00749 * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored. 00750 * 00751 * @return bool 00752 */ 00753 bool PICC_IsNewCardPresent(void); 00754 00755 /** 00756 * Simple wrapper around PICC_Select. 00757 * Returns true if a UID could be read. 00758 * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first. 00759 * The read UID is available in the class variable uid. 00760 * 00761 * @return bool 00762 */ 00763 bool PICC_ReadCardSerial (void); 00764 00765 // ************************************************************************************ 00766 //@} 00767 00768 00769 private: 00770 SPI m_SPI; 00771 DigitalOut m_CS; 00772 DigitalOut m_RESET; 00773 00774 /** 00775 * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore. 00776 * 00777 * @param command The command to use 00778 * @param blockAddr The block (0-0xff) number. 00779 * @param data The data to transfer in step 2 00780 * 00781 * @return STATUS_OK on success, STATUS_??? otherwise. 00782 */ 00783 uint8_t MIFARE_TwoStepHelper(uint8_t command, uint8_t blockAddr, uint32_t data); 00784 }; 00785 00786 #endif
Generated on Sat Jul 16 2022 17:50:49 by
1.7.2