├── MFRC522_I2C.cpp ├── MFRC522_I2C.h ├── README.md └── examples └── nodemcu_rfid ├── .cproject ├── .gitignore ├── .project ├── .settings ├── language.settings.xml └── org.eclipse.cdt.core.prefs ├── .travis.yml ├── lib └── MFRC522_I2C │ ├── MFRC522_I2C.cpp │ └── MFRC522_I2C.h ├── platformio.ini └── src └── main.cpp /MFRC522_I2C.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522.cpp - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information. 5 | * Released into the public domain. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | ///////////////////////////////////////////////////////////////////////////////////// 13 | // Functions for setting up the Arduino 14 | ///////////////////////////////////////////////////////////////////////////////////// 15 | 16 | /** 17 | * Constructor. 18 | * Prepares the output pins. 19 | */ 20 | MFRC522::MFRC522( byte chipAddress, 21 | byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 22 | ) { 23 | _chipAddress = chipAddress; 24 | _resetPowerDownPin = resetPowerDownPin; 25 | } // End constructor 26 | 27 | 28 | ///////////////////////////////////////////////////////////////////////////////////// 29 | // Basic interface functions for communicating with the MFRC522 30 | ///////////////////////////////////////////////////////////////////////////////////// 31 | 32 | /** 33 | * Writes a byte to the specified register in the MFRC522 chip. 34 | * The interface is described in the datasheet section 8.1.2. 35 | */ 36 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 37 | byte value ///< The value to write. 38 | ) { 39 | Wire.beginTransmission(_chipAddress); 40 | Wire.write(reg); 41 | Wire.write(value); 42 | Wire.endTransmission(); 43 | } // End PCD_WriteRegister() 44 | 45 | /** 46 | * Writes a number of bytes to the specified register in the MFRC522 chip. 47 | * The interface is described in the datasheet section 8.1.2. 48 | */ 49 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 50 | byte count, ///< The number of bytes to write to the register 51 | byte *values ///< The values to write. Byte array. 52 | ) { 53 | Wire.beginTransmission(_chipAddress); 54 | Wire.write(reg); 55 | for (byte index = 0; index < count; index++) { 56 | Wire.write(values[index]); 57 | } 58 | Wire.endTransmission(); 59 | } // End PCD_WriteRegister() 60 | 61 | /** 62 | * Reads a byte from the specified register in the MFRC522 chip. 63 | * The interface is described in the datasheet section 8.1.2. 64 | */ 65 | byte MFRC522::PCD_ReadRegister( byte reg ///< The register to read from. One of the PCD_Register enums. 66 | ) { 67 | byte value; 68 | //digitalWrite(_chipSelectPin, LOW); // Select slave 69 | Wire.beginTransmission(_chipAddress); 70 | Wire.write(reg); 71 | Wire.endTransmission(); 72 | 73 | Wire.requestFrom(_chipAddress, 1); 74 | value = Wire.read(); 75 | return value; 76 | } // End PCD_ReadRegister() 77 | 78 | /** 79 | * Reads a number of bytes from the specified register in the MFRC522 chip. 80 | * The interface is described in the datasheet section 8.1.2. 81 | */ 82 | void MFRC522::PCD_ReadRegister( byte reg, ///< The register to read from. One of the PCD_Register enums. 83 | byte count, ///< The number of bytes to read 84 | byte *values, ///< Byte array to store the values in. 85 | byte rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated. 86 | ) { 87 | if (count == 0) { 88 | return; 89 | } 90 | byte address = reg; 91 | byte index = 0; // Index in values array. 92 | Wire.beginTransmission(_chipAddress); 93 | Wire.write(address); 94 | Wire.endTransmission(); 95 | Wire.requestFrom(_chipAddress, count); 96 | while (Wire.available()) { 97 | if (index == 0 && rxAlign) { // Only update bit positions rxAlign..7 in values[0] 98 | // Create bit mask for bit positions rxAlign..7 99 | byte mask = 0; 100 | for (byte i = rxAlign; i <= 7; i++) { 101 | mask |= (1 << i); 102 | } 103 | // Read value and tell that we want to read the same address again. 104 | byte value = Wire.read(); 105 | // Apply mask to both current value of values[0] and the new data in value. 106 | values[0] = (values[index] & ~mask) | (value & mask); 107 | } 108 | else { // Normal case 109 | values[index] = Wire.read(); 110 | } 111 | index++; 112 | } 113 | } // End PCD_ReadRegister() 114 | 115 | /** 116 | * Sets the bits given in mask in register reg. 117 | */ 118 | void MFRC522::PCD_SetRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 119 | byte mask ///< The bits to set. 120 | ) { 121 | byte tmp; 122 | tmp = PCD_ReadRegister(reg); 123 | PCD_WriteRegister(reg, tmp | mask); // set bit mask 124 | } // End PCD_SetRegisterBitMask() 125 | 126 | /** 127 | * Clears the bits given in mask from register reg. 128 | */ 129 | void MFRC522::PCD_ClearRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 130 | byte mask ///< The bits to clear. 131 | ) { 132 | byte tmp; 133 | tmp = PCD_ReadRegister(reg); 134 | PCD_WriteRegister(reg, tmp & (~mask)); // clear bit mask 135 | } // End PCD_ClearRegisterBitMask() 136 | 137 | 138 | /** 139 | * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A. 140 | * 141 | * @return STATUS_OK on success, STATUS_??? otherwise. 142 | */ 143 | byte MFRC522::PCD_CalculateCRC( byte *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation. 144 | byte length, ///< In: The number of bytes to transfer. 145 | byte *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first. 146 | ) { 147 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 148 | PCD_WriteRegister(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit 149 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 150 | PCD_WriteRegister(FIFODataReg, length, data); // Write data to the FIFO 151 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); // Start the calculation 152 | 153 | // Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73�s. 154 | word i = 5000; 155 | byte n; 156 | while (1) { 157 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 158 | if (n & 0x04) { // CRCIRq bit set - calculation done 159 | break; 160 | } 161 | if (--i == 0) { // The emergency break. We will eventually terminate on this one after 89ms. Communication with the MFRC522 might be down. 162 | return STATUS_TIMEOUT; 163 | } 164 | } 165 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 166 | 167 | // Transfer the result from the registers to the result buffer 168 | result[0] = PCD_ReadRegister(CRCResultRegL); 169 | result[1] = PCD_ReadRegister(CRCResultRegH); 170 | return STATUS_OK; 171 | } // End PCD_CalculateCRC() 172 | 173 | 174 | ///////////////////////////////////////////////////////////////////////////////////// 175 | // Functions for manipulating the MFRC522 176 | ///////////////////////////////////////////////////////////////////////////////////// 177 | 178 | /** 179 | * Initializes the MFRC522 chip. 180 | */ 181 | void MFRC522::PCD_Init() { 182 | // Set the chipSelectPin as digital output, do not select the slave yet 183 | 184 | // Set the resetPowerDownPin as digital output, do not reset or power down. 185 | pinMode(_resetPowerDownPin, OUTPUT); 186 | 187 | 188 | if (digitalRead(_resetPowerDownPin) == LOW) { //The MFRC522 chip is in power down mode. 189 | digitalWrite(_resetPowerDownPin, HIGH); // Exit power down mode. This triggers a hard reset. 190 | // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 191 | delay(50); 192 | } 193 | else { // Perform a soft reset 194 | PCD_Reset(); 195 | } 196 | 197 | // When communicating with a PICC we need a timeout if something goes wrong. 198 | // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo]. 199 | // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg. 200 | PCD_WriteRegister(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds 201 | PCD_WriteRegister(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25�s. 202 | PCD_WriteRegister(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout. 203 | PCD_WriteRegister(TReloadRegL, 0xE8); 204 | 205 | PCD_WriteRegister(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting 206 | PCD_WriteRegister(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4) 207 | PCD_AntennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset) 208 | } // End PCD_Init() 209 | 210 | /** 211 | * Performs a soft reset on the MFRC522 chip and waits for it to be ready again. 212 | */ 213 | void MFRC522::PCD_Reset() { 214 | PCD_WriteRegister(CommandReg, PCD_SoftReset); // Issue the SoftReset command. 215 | // The datasheet does not mention how long the SoftRest command takes to complete. 216 | // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg) 217 | // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 218 | delay(50); 219 | // Wait for the PowerDown bit in CommandReg to be cleared 220 | while (PCD_ReadRegister(CommandReg) & (1<<4)) { 221 | // PCD still restarting - unlikely after waiting 50ms, but better safe than sorry. 222 | } 223 | } // End PCD_Reset() 224 | 225 | /** 226 | * Turns the antenna on by enabling pins TX1 and TX2. 227 | * After a reset these pins are disabled. 228 | */ 229 | void MFRC522::PCD_AntennaOn() { 230 | byte value = PCD_ReadRegister(TxControlReg); 231 | if ((value & 0x03) != 0x03) { 232 | PCD_WriteRegister(TxControlReg, value | 0x03); 233 | } 234 | } // End PCD_AntennaOn() 235 | 236 | /** 237 | * Turns the antenna off by disabling pins TX1 and TX2. 238 | */ 239 | void MFRC522::PCD_AntennaOff() { 240 | PCD_ClearRegisterBitMask(TxControlReg, 0x03); 241 | } // End PCD_AntennaOff() 242 | 243 | /** 244 | * Get the current MFRC522 Receiver Gain (RxGain[2:0]) value. 245 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 246 | * NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 247 | * 248 | * @return Value of the RxGain, scrubbed to the 3 bits used. 249 | */ 250 | byte MFRC522::PCD_GetAntennaGain() { 251 | return PCD_ReadRegister(RFCfgReg) & (0x07<<4); 252 | } // End PCD_GetAntennaGain() 253 | 254 | /** 255 | * Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask. 256 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 257 | * NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 258 | */ 259 | void MFRC522::PCD_SetAntennaGain(byte mask) { 260 | if (PCD_GetAntennaGain() != mask) { // only bother if there is a change 261 | PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4)); // clear needed to allow 000 pattern 262 | PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits 263 | } 264 | } // End PCD_SetAntennaGain() 265 | 266 | /** 267 | * Performs a self-test of the MFRC522 268 | * See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 269 | * 270 | * @return Whether or not the test passed. 271 | */ 272 | bool MFRC522::PCD_PerformSelfTest() { 273 | // This follows directly the steps outlined in 16.1.1 274 | // 1. Perform a soft reset. 275 | PCD_Reset(); 276 | 277 | // 2. Clear the internal buffer by writing 25 bytes of 00h 278 | byte ZEROES[25] = {0x00}; 279 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // flush the FIFO buffer 280 | PCD_WriteRegister(FIFODataReg, 25, ZEROES); // write 25 bytes of 00h to FIFO 281 | PCD_WriteRegister(CommandReg, PCD_Mem); // transfer to internal buffer 282 | 283 | // 3. Enable self-test 284 | PCD_WriteRegister(AutoTestReg, 0x09); 285 | 286 | // 4. Write 00h to FIFO buffer 287 | PCD_WriteRegister(FIFODataReg, 0x00); 288 | 289 | // 5. Start self-test by issuing the CalcCRC command 290 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); 291 | 292 | // 6. Wait for self-test to complete 293 | word i; 294 | byte n; 295 | for (i = 0; i < 0xFF; i++) { 296 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 297 | if (n & 0x04) { // CRCIRq bit set - calculation done 298 | break; 299 | } 300 | } 301 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 302 | 303 | // 7. Read out resulting 64 bytes from the FIFO buffer. 304 | byte result[64]; 305 | PCD_ReadRegister(FIFODataReg, 64, result, 0); 306 | 307 | // Auto self-test done 308 | // Reset AutoTestReg register to be 0 again. Required for normal operation. 309 | PCD_WriteRegister(AutoTestReg, 0x00); 310 | 311 | // Determine firmware version (see section 9.3.4.8 in spec) 312 | byte version = PCD_ReadRegister(VersionReg); 313 | 314 | // Pick the appropriate reference values 315 | const byte *reference; 316 | switch (version) { 317 | case 0x88: // Fudan Semiconductor FM17522 clone 318 | reference = FM17522_firmware_reference; 319 | break; 320 | case 0x90: // Version 0.0 321 | reference = MFRC522_firmware_referenceV0_0; 322 | break; 323 | case 0x91: // Version 1.0 324 | reference = MFRC522_firmware_referenceV1_0; 325 | break; 326 | case 0x92: // Version 2.0 327 | reference = MFRC522_firmware_referenceV2_0; 328 | break; 329 | default: // Unknown version 330 | return false; 331 | } 332 | 333 | // Verify that the results match up to our expectations 334 | for (i = 0; i < 64; i++) { 335 | if (result[i] != pgm_read_byte(&(reference[i]))) { 336 | return false; 337 | } 338 | } 339 | 340 | // Test passed; all is good. 341 | return true; 342 | } // End PCD_PerformSelfTest() 343 | 344 | ///////////////////////////////////////////////////////////////////////////////////// 345 | // Functions for communicating with PICCs 346 | ///////////////////////////////////////////////////////////////////////////////////// 347 | 348 | /** 349 | * Executes the Transceive command. 350 | * CRC validation can only be done if backData and backLen are specified. 351 | * 352 | * @return STATUS_OK on success, STATUS_??? otherwise. 353 | */ 354 | byte MFRC522::PCD_TransceiveData( byte *sendData, ///< Pointer to the data to transfer to the FIFO. 355 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 356 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 357 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 358 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL. 359 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 360 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 361 | ) { 362 | byte waitIRq = 0x30; // RxIRq and IdleIRq 363 | return PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC); 364 | } // End PCD_TransceiveData() 365 | 366 | /** 367 | * Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO. 368 | * CRC validation can only be done if backData and backLen are specified. 369 | * 370 | * @return STATUS_OK on success, STATUS_??? otherwise. 371 | */ 372 | byte MFRC522::PCD_CommunicateWithPICC( byte command, ///< The command to execute. One of the PCD_Command enums. 373 | byte waitIRq, ///< The bits in the ComIrqReg register that signals successful completion of the command. 374 | byte *sendData, ///< Pointer to the data to transfer to the FIFO. 375 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 376 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 377 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 378 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. 379 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 380 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 381 | ) { 382 | byte n, _validBits; 383 | unsigned int i; 384 | 385 | // Prepare values for BitFramingReg 386 | byte txLastBits = validBits ? *validBits : 0; 387 | byte bitFraming = (rxAlign << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 388 | 389 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 390 | PCD_WriteRegister(ComIrqReg, 0x7F); // Clear all seven interrupt request bits 391 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 392 | PCD_WriteRegister(FIFODataReg, sendLen, sendData); // Write sendData to the FIFO 393 | PCD_WriteRegister(BitFramingReg, bitFraming); // Bit adjustments 394 | PCD_WriteRegister(CommandReg, command); // Execute the command 395 | if (command == PCD_Transceive) { 396 | PCD_SetRegisterBitMask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts 397 | } 398 | 399 | // Wait for the command to complete. 400 | // In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting. 401 | // Each iteration of the do-while-loop takes 17.86�s. 402 | i = 2000; 403 | while (1) { 404 | n = PCD_ReadRegister(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq 405 | if (n & waitIRq) { // One of the interrupts that signal success has been set. 406 | break; 407 | } 408 | if (n & 0x01) { // Timer interrupt - nothing received in 25ms 409 | return STATUS_TIMEOUT; 410 | } 411 | if (--i == 0) { // The emergency break. If all other condions fail we will eventually terminate on this one after 35.7ms. Communication with the MFRC522 might be down. 412 | return STATUS_TIMEOUT; 413 | } 414 | } 415 | 416 | // Stop now if any errors except collisions were detected. 417 | byte errorRegValue = PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr 418 | if (errorRegValue & 0x13) { // BufferOvfl ParityErr ProtocolErr 419 | return STATUS_ERROR; 420 | } 421 | 422 | // If the caller wants data back, get it from the MFRC522. 423 | if (backData && backLen) { 424 | n = PCD_ReadRegister(FIFOLevelReg); // Number of bytes in the FIFO 425 | if (n > *backLen) { 426 | return STATUS_NO_ROOM; 427 | } 428 | *backLen = n; // Number of bytes returned 429 | PCD_ReadRegister(FIFODataReg, n, backData, rxAlign); // Get received data from FIFO 430 | _validBits = PCD_ReadRegister(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid. 431 | if (validBits) { 432 | *validBits = _validBits; 433 | } 434 | } 435 | 436 | // Tell about collisions 437 | if (errorRegValue & 0x08) { // CollErr 438 | return STATUS_COLLISION; 439 | } 440 | 441 | // Perform CRC_A validation if requested. 442 | if (backData && backLen && checkCRC) { 443 | // In this case a MIFARE Classic NAK is not OK. 444 | if (*backLen == 1 && _validBits == 4) { 445 | return STATUS_MIFARE_NACK; 446 | } 447 | // We need at least the CRC_A value and all 8 bits of the last byte must be received. 448 | if (*backLen < 2 || _validBits != 0) { 449 | return STATUS_CRC_WRONG; 450 | } 451 | // Verify CRC_A - do our own calculation and store the control in controlBuffer. 452 | byte controlBuffer[2]; 453 | n = PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]); 454 | if (n != STATUS_OK) { 455 | return n; 456 | } 457 | if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) { 458 | return STATUS_CRC_WRONG; 459 | } 460 | } 461 | 462 | return STATUS_OK; 463 | } // End PCD_CommunicateWithPICC() 464 | 465 | /** 466 | * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. 467 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 468 | * 469 | * @return STATUS_OK on success, STATUS_??? otherwise. 470 | */ 471 | byte MFRC522::PICC_RequestA(byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 472 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 473 | ) { 474 | return PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize); 475 | } // End PICC_RequestA() 476 | 477 | /** 478 | * 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. 479 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 480 | * 481 | * @return STATUS_OK on success, STATUS_??? otherwise. 482 | */ 483 | byte MFRC522::PICC_WakeupA( byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 484 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 485 | ) { 486 | return PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize); 487 | } // End PICC_WakeupA() 488 | 489 | /** 490 | * Transmits REQA or WUPA commands. 491 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 492 | * 493 | * @return STATUS_OK on success, STATUS_??? otherwise. 494 | */ 495 | byte MFRC522::PICC_REQA_or_WUPA( byte command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA 496 | byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 497 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 498 | ) { 499 | byte validBits; 500 | byte status; 501 | 502 | if (bufferATQA == NULL || *bufferSize < 2) { // The ATQA response is 2 bytes long. 503 | return STATUS_NO_ROOM; 504 | } 505 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 506 | validBits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0] 507 | status = PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits); 508 | if (status != STATUS_OK) { 509 | return status; 510 | } 511 | if (*bufferSize != 2 || validBits != 0) { // ATQA must be exactly 16 bits. 512 | return STATUS_ERROR; 513 | } 514 | return STATUS_OK; 515 | } // End PICC_REQA_or_WUPA() 516 | 517 | /** 518 | * Transmits SELECT/ANTICOLLISION commands to select a single PICC. 519 | * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA(). 520 | * On success: 521 | * - 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.) 522 | * - The UID size and value of the chosen PICC is returned in *uid along with the SAK. 523 | * 524 | * A PICC UID consists of 4, 7 or 10 bytes. 525 | * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used: 526 | * UID size Number of UID bytes Cascade levels Example of PICC 527 | * ======== =================== ============== =============== 528 | * single 4 1 MIFARE Classic 529 | * double 7 2 MIFARE Ultralight 530 | * triple 10 3 Not currently in use? 531 | * 532 | * @return STATUS_OK on success, STATUS_??? otherwise. 533 | */ 534 | byte MFRC522::PICC_Select( Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID. 535 | byte validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size. 536 | ) { 537 | bool uidComplete; 538 | bool selectDone; 539 | bool useCascadeTag; 540 | byte cascadeLevel = 1; 541 | byte result; 542 | byte count; 543 | byte index; 544 | byte uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level. 545 | int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level. 546 | byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A 547 | byte bufferUsed; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO. 548 | byte rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received. 549 | byte txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte. 550 | byte *responseBuffer; 551 | byte responseLength; 552 | 553 | // Description of buffer structure: 554 | // Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3 555 | // Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits. 556 | // Byte 2: UID-data or CT See explanation below. CT means Cascade Tag. 557 | // Byte 3: UID-data 558 | // Byte 4: UID-data 559 | // Byte 5: UID-data 560 | // Byte 6: BCC Block Check Character - XOR of bytes 2-5 561 | // Byte 7: CRC_A 562 | // Byte 8: CRC_A 563 | // The BCC and CRC_A is only transmitted if we know all the UID bits of the current Cascade Level. 564 | // 565 | // Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels) 566 | // UID size Cascade level Byte2 Byte3 Byte4 Byte5 567 | // ======== ============= ===== ===== ===== ===== 568 | // 4 bytes 1 uid0 uid1 uid2 uid3 569 | // 7 bytes 1 CT uid0 uid1 uid2 570 | // 2 uid3 uid4 uid5 uid6 571 | // 10 bytes 1 CT uid0 uid1 uid2 572 | // 2 CT uid3 uid4 uid5 573 | // 3 uid6 uid7 uid8 uid9 574 | 575 | // Sanity checks 576 | if (validBits > 80) { 577 | return STATUS_INVALID; 578 | } 579 | 580 | // Prepare MFRC522 581 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 582 | 583 | // Repeat Cascade Level loop until we have a complete UID. 584 | uidComplete = false; 585 | while (!uidComplete) { 586 | // Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2. 587 | switch (cascadeLevel) { 588 | case 1: 589 | buffer[0] = PICC_CMD_SEL_CL1; 590 | uidIndex = 0; 591 | useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes 592 | break; 593 | 594 | case 2: 595 | buffer[0] = PICC_CMD_SEL_CL2; 596 | uidIndex = 3; 597 | useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes 598 | break; 599 | 600 | case 3: 601 | buffer[0] = PICC_CMD_SEL_CL3; 602 | uidIndex = 6; 603 | useCascadeTag = false; // Never used in CL3. 604 | break; 605 | 606 | default: 607 | return STATUS_INTERNAL_ERROR; 608 | break; 609 | } 610 | 611 | // How many UID bits are known in this Cascade Level? 612 | currentLevelKnownBits = validBits - (8 * uidIndex); 613 | if (currentLevelKnownBits < 0) { 614 | currentLevelKnownBits = 0; 615 | } 616 | // Copy the known bits from uid->uidByte[] to buffer[] 617 | index = 2; // destination index in buffer[] 618 | if (useCascadeTag) { 619 | buffer[index++] = PICC_CMD_CT; 620 | } 621 | byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level. 622 | if (bytesToCopy) { 623 | byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag 624 | if (bytesToCopy > maxBytes) { 625 | bytesToCopy = maxBytes; 626 | } 627 | for (count = 0; count < bytesToCopy; count++) { 628 | buffer[index++] = uid->uidByte[uidIndex + count]; 629 | } 630 | } 631 | // Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits 632 | if (useCascadeTag) { 633 | currentLevelKnownBits += 8; 634 | } 635 | 636 | // Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations. 637 | selectDone = false; 638 | while (!selectDone) { 639 | // Find out how many bits and bytes to send and receive. 640 | if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT. 641 | //Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 642 | buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes 643 | // Calculate BCC - Block Check Character 644 | buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5]; 645 | // Calculate CRC_A 646 | result = PCD_CalculateCRC(buffer, 7, &buffer[7]); 647 | if (result != STATUS_OK) { 648 | return result; 649 | } 650 | txLastBits = 0; // 0 => All 8 bits are valid. 651 | bufferUsed = 9; 652 | // Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx) 653 | responseBuffer = &buffer[6]; 654 | responseLength = 3; 655 | } 656 | else { // This is an ANTICOLLISION. 657 | //Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 658 | txLastBits = currentLevelKnownBits % 8; 659 | count = currentLevelKnownBits / 8; // Number of whole bytes in the UID part. 660 | index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs 661 | buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits 662 | bufferUsed = index + (txLastBits ? 1 : 0); 663 | // Store response in the unused part of buffer 664 | responseBuffer = &buffer[index]; 665 | responseLength = sizeof(buffer) - index; 666 | } 667 | 668 | // Set bit adjustments 669 | rxAlign = txLastBits; // Having a seperate variable is overkill. But it makes the next line easier to read. 670 | PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 671 | 672 | // Transmit the buffer and receive the response. 673 | result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign); 674 | if (result == STATUS_COLLISION) { // More than one PICC in the field => collision. 675 | result = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0] 676 | if (result & 0x20) { // CollPosNotValid 677 | return STATUS_COLLISION; // Without a valid collision position we cannot continue 678 | } 679 | byte collisionPos = result & 0x1F; // Values 0-31, 0 means bit 32. 680 | if (collisionPos == 0) { 681 | collisionPos = 32; 682 | } 683 | if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen 684 | return STATUS_INTERNAL_ERROR; 685 | } 686 | // Choose the PICC with the bit set. 687 | currentLevelKnownBits = collisionPos; 688 | count = (currentLevelKnownBits - 1) % 8; // The bit to modify 689 | index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0. 690 | buffer[index] |= (1 << count); 691 | } 692 | else if (result != STATUS_OK) { 693 | return result; 694 | } 695 | else { // STATUS_OK 696 | if (currentLevelKnownBits >= 32) { // This was a SELECT. 697 | selectDone = true; // No more anticollision 698 | // We continue below outside the while. 699 | } 700 | else { // This was an ANTICOLLISION. 701 | // We now have all 32 bits of the UID in this Cascade Level 702 | currentLevelKnownBits = 32; 703 | // Run loop again to do the SELECT. 704 | } 705 | } 706 | } // End of while (!selectDone) 707 | 708 | // We do not check the CBB - it was constructed by us above. 709 | 710 | // Copy the found UID bytes from buffer[] to uid->uidByte[] 711 | index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[] 712 | bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4; 713 | for (count = 0; count < bytesToCopy; count++) { 714 | uid->uidByte[uidIndex + count] = buffer[index++]; 715 | } 716 | 717 | // Check response SAK (Select Acknowledge) 718 | if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A). 719 | return STATUS_ERROR; 720 | } 721 | // Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore. 722 | result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]); 723 | if (result != STATUS_OK) { 724 | return result; 725 | } 726 | if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) { 727 | return STATUS_CRC_WRONG; 728 | } 729 | if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes 730 | cascadeLevel++; 731 | } 732 | else { 733 | uidComplete = true; 734 | uid->sak = responseBuffer[0]; 735 | } 736 | } // End of while (!uidComplete) 737 | 738 | // Set correct uid->size 739 | uid->size = 3 * cascadeLevel + 1; 740 | 741 | return STATUS_OK; 742 | } // End PICC_Select() 743 | 744 | /** 745 | * Instructs a PICC in state ACTIVE(*) to go to state HALT. 746 | * 747 | * @return STATUS_OK on success, STATUS_??? otherwise. 748 | */ 749 | byte MFRC522::PICC_HaltA() { 750 | byte result; 751 | byte buffer[4]; 752 | 753 | // Build command buffer 754 | buffer[0] = PICC_CMD_HLTA; 755 | buffer[1] = 0; 756 | // Calculate CRC_A 757 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 758 | if (result != STATUS_OK) { 759 | return result; 760 | } 761 | 762 | // Send the command. 763 | // The standard says: 764 | // If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the 765 | // HLTA command, this response shall be interpreted as 'not acknowledge'. 766 | // We interpret that this way: Only STATUS_TIMEOUT is an success. 767 | result = PCD_TransceiveData(buffer, sizeof(buffer), NULL, 0); 768 | if (result == STATUS_TIMEOUT) { 769 | return STATUS_OK; 770 | } 771 | if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-) 772 | return STATUS_ERROR; 773 | } 774 | return result; 775 | } // End PICC_HaltA() 776 | 777 | 778 | ///////////////////////////////////////////////////////////////////////////////////// 779 | // Functions for communicating with MIFARE PICCs 780 | ///////////////////////////////////////////////////////////////////////////////////// 781 | 782 | /** 783 | * Executes the MFRC522 MFAuthent command. 784 | * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card. 785 | * 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. 786 | * For use with MIFARE Classic PICCs. 787 | * The PICC must be selected - ie in state ACTIVE(*) - before calling this function. 788 | * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start. 789 | * 790 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 791 | * 792 | * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key. 793 | */ 794 | byte MFRC522::PCD_Authenticate(byte command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B 795 | byte blockAddr, ///< The block number. See numbering in the comments in the .h file. 796 | MIFARE_Key *key, ///< Pointer to the Crypteo1 key to use (6 bytes) 797 | Uid *uid ///< Pointer to Uid struct. The first 4 bytes of the UID is used. 798 | ) { 799 | byte waitIRq = 0x10; // IdleIRq 800 | 801 | // Build command buffer 802 | byte sendData[12]; 803 | sendData[0] = command; 804 | sendData[1] = blockAddr; 805 | for (byte i = 0; i < MF_KEY_SIZE; i++) { // 6 key bytes 806 | sendData[2+i] = key->keyByte[i]; 807 | } 808 | for (byte i = 0; i < 4; i++) { // The first 4 bytes of the UID 809 | sendData[8+i] = uid->uidByte[i]; 810 | } 811 | 812 | // Start the authentication. 813 | return PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData)); 814 | } // End PCD_Authenticate() 815 | 816 | /** 817 | * Used to exit the PCD from its authenticated state. 818 | * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start. 819 | */ 820 | void MFRC522::PCD_StopCrypto1() { 821 | // Clear MFCrypto1On bit 822 | PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0] 823 | } // End PCD_StopCrypto1() 824 | 825 | /** 826 | * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC. 827 | * 828 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 829 | * 830 | * For MIFARE Ultralight only addresses 00h to 0Fh are decoded. 831 | * The MF0ICU1 returns a NAK for higher addresses. 832 | * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument. 833 | * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned. 834 | * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned. 835 | * 836 | * The buffer must be at least 18 bytes because a CRC_A is also returned. 837 | * Checks the CRC_A before returning STATUS_OK. 838 | * 839 | * @return STATUS_OK on success, STATUS_??? otherwise. 840 | */ 841 | byte MFRC522::MIFARE_Read( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from. 842 | byte *buffer, ///< The buffer to store the data in 843 | byte *bufferSize ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK. 844 | ) { 845 | byte result; 846 | 847 | // Sanity check 848 | if (buffer == NULL || *bufferSize < 18) { 849 | return STATUS_NO_ROOM; 850 | } 851 | 852 | // Build command buffer 853 | buffer[0] = PICC_CMD_MF_READ; 854 | buffer[1] = blockAddr; 855 | // Calculate CRC_A 856 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 857 | if (result != STATUS_OK) { 858 | return result; 859 | } 860 | 861 | // Transmit the buffer and receive the response, validate CRC_A. 862 | return PCD_TransceiveData(buffer, 4, buffer, bufferSize, NULL, 0, true); 863 | } // End MIFARE_Read() 864 | 865 | /** 866 | * Writes 16 bytes to the active PICC. 867 | * 868 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 869 | * 870 | * For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE". 871 | * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3) 872 | * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0. 873 | * * 874 | * @return STATUS_OK on success, STATUS_??? otherwise. 875 | */ 876 | byte MFRC522::MIFARE_Write( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to. 877 | byte *buffer, ///< The 16 bytes to write to the PICC 878 | byte bufferSize ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written. 879 | ) { 880 | byte result; 881 | 882 | // Sanity check 883 | if (buffer == NULL || bufferSize < 16) { 884 | return STATUS_INVALID; 885 | } 886 | 887 | // Mifare Classic protocol requires two communications to perform a write. 888 | // Step 1: Tell the PICC we want to write to block blockAddr. 889 | byte cmdBuffer[2]; 890 | cmdBuffer[0] = PICC_CMD_MF_WRITE; 891 | cmdBuffer[1] = blockAddr; 892 | result = PCD_MIFARE_Transceive(cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 893 | if (result != STATUS_OK) { 894 | return result; 895 | } 896 | 897 | // Step 2: Transfer the data 898 | result = PCD_MIFARE_Transceive(buffer, bufferSize); // Adds CRC_A and checks that the response is MF_ACK. 899 | if (result != STATUS_OK) { 900 | return result; 901 | } 902 | 903 | return STATUS_OK; 904 | } // End MIFARE_Write() 905 | 906 | /** 907 | * Writes a 4 byte page to the active MIFARE Ultralight PICC. 908 | * 909 | * @return STATUS_OK on success, STATUS_??? otherwise. 910 | */ 911 | byte MFRC522::MIFARE_Ultralight_Write( byte page, ///< The page (2-15) to write to. 912 | byte *buffer, ///< The 4 bytes to write to the PICC 913 | byte bufferSize ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written. 914 | ) { 915 | byte result; 916 | 917 | // Sanity check 918 | if (buffer == NULL || bufferSize < 4) { 919 | return STATUS_INVALID; 920 | } 921 | 922 | // Build commmand buffer 923 | byte cmdBuffer[6]; 924 | cmdBuffer[0] = PICC_CMD_UL_WRITE; 925 | cmdBuffer[1] = page; 926 | memcpy(&cmdBuffer[2], buffer, 4); 927 | 928 | // Perform the write 929 | result = PCD_MIFARE_Transceive(cmdBuffer, 6); // Adds CRC_A and checks that the response is MF_ACK. 930 | if (result != STATUS_OK) { 931 | return result; 932 | } 933 | return STATUS_OK; 934 | } // End MIFARE_Ultralight_Write() 935 | 936 | /** 937 | * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory. 938 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 939 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 940 | * Use MIFARE_Transfer() to store the result in a block. 941 | * 942 | * @return STATUS_OK on success, STATUS_??? otherwise. 943 | */ 944 | byte MFRC522::MIFARE_Decrement( byte blockAddr, ///< The block (0-0xff) number. 945 | long delta ///< This number is subtracted from the value of block blockAddr. 946 | ) { 947 | return MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta); 948 | } // End MIFARE_Decrement() 949 | 950 | /** 951 | * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory. 952 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 953 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 954 | * Use MIFARE_Transfer() to store the result in a block. 955 | * 956 | * @return STATUS_OK on success, STATUS_??? otherwise. 957 | */ 958 | byte MFRC522::MIFARE_Increment( byte blockAddr, ///< The block (0-0xff) number. 959 | long delta ///< This number is added to the value of block blockAddr. 960 | ) { 961 | return MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta); 962 | } // End MIFARE_Increment() 963 | 964 | /** 965 | * MIFARE Restore copies the value of the addressed block into a volatile memory. 966 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 967 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 968 | * Use MIFARE_Transfer() to store the result in a block. 969 | * 970 | * @return STATUS_OK on success, STATUS_??? otherwise. 971 | */ 972 | byte MFRC522::MIFARE_Restore( byte blockAddr ///< The block (0-0xff) number. 973 | ) { 974 | // The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2. 975 | // Doing only a single step does not work, so I chose to transfer 0L in step two. 976 | return MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L); 977 | } // End MIFARE_Restore() 978 | 979 | /** 980 | * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore. 981 | * 982 | * @return STATUS_OK on success, STATUS_??? otherwise. 983 | */ 984 | byte MFRC522::MIFARE_TwoStepHelper( byte command, ///< The command to use 985 | byte blockAddr, ///< The block (0-0xff) number. 986 | long data ///< The data to transfer in step 2 987 | ) { 988 | byte result; 989 | byte cmdBuffer[2]; // We only need room for 2 bytes. 990 | 991 | // Step 1: Tell the PICC the command and block address 992 | cmdBuffer[0] = command; 993 | cmdBuffer[1] = blockAddr; 994 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 995 | if (result != STATUS_OK) { 996 | return result; 997 | } 998 | 999 | // Step 2: Transfer the data 1000 | result = PCD_MIFARE_Transceive( (byte *)&data, 4, true); // Adds CRC_A and accept timeout as success. 1001 | if (result != STATUS_OK) { 1002 | return result; 1003 | } 1004 | 1005 | return STATUS_OK; 1006 | } // End MIFARE_TwoStepHelper() 1007 | 1008 | /** 1009 | * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block. 1010 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 1011 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 1012 | * 1013 | * @return STATUS_OK on success, STATUS_??? otherwise. 1014 | */ 1015 | byte MFRC522::MIFARE_Transfer( byte blockAddr ///< The block (0-0xff) number. 1016 | ) { 1017 | byte result; 1018 | byte cmdBuffer[2]; // We only need room for 2 bytes. 1019 | 1020 | // Tell the PICC we want to transfer the result into block blockAddr. 1021 | cmdBuffer[0] = PICC_CMD_MF_TRANSFER; 1022 | cmdBuffer[1] = blockAddr; 1023 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 1024 | if (result != STATUS_OK) { 1025 | return result; 1026 | } 1027 | return STATUS_OK; 1028 | } // End MIFARE_Transfer() 1029 | 1030 | /** 1031 | * Helper routine to read the current value from a Value Block. 1032 | * 1033 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1034 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1035 | * the block must be authenticated before calling this function. 1036 | * 1037 | * @param[in] blockAddr The block (0x00-0xff) number. 1038 | * @param[out] value Current value of the Value Block. 1039 | * @return STATUS_OK on success, STATUS_??? otherwise. 1040 | */ 1041 | byte MFRC522::MIFARE_GetValue(byte blockAddr, long *value) { 1042 | byte status; 1043 | byte buffer[18]; 1044 | byte size = sizeof(buffer); 1045 | 1046 | // Read the block 1047 | status = MIFARE_Read(blockAddr, buffer, &size); 1048 | if (status == STATUS_OK) { 1049 | // Extract the value 1050 | *value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1051 | } 1052 | return status; 1053 | } // End MIFARE_GetValue() 1054 | 1055 | /** 1056 | * Helper routine to write a specific value into a Value Block. 1057 | * 1058 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1059 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1060 | * the block must be authenticated before calling this function. 1061 | * 1062 | * @param[in] blockAddr The block (0x00-0xff) number. 1063 | * @param[in] value New value of the Value Block. 1064 | * @return STATUS_OK on success, STATUS_??? otherwise. 1065 | */ 1066 | byte MFRC522::MIFARE_SetValue(byte blockAddr, long value) { 1067 | byte buffer[18]; 1068 | 1069 | // Translate the long into 4 bytes; repeated 2x in value block 1070 | buffer[0] = buffer[ 8] = (value & 0xFF); 1071 | buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8; 1072 | buffer[2] = buffer[10] = (value & 0xFF0000) >> 16; 1073 | buffer[3] = buffer[11] = (value & 0xFF000000) >> 24; 1074 | // Inverse 4 bytes also found in value block 1075 | buffer[4] = ~buffer[0]; 1076 | buffer[5] = ~buffer[1]; 1077 | buffer[6] = ~buffer[2]; 1078 | buffer[7] = ~buffer[3]; 1079 | // Address 2x with inverse address 2x 1080 | buffer[12] = buffer[14] = blockAddr; 1081 | buffer[13] = buffer[15] = ~blockAddr; 1082 | 1083 | // Write the whole data block 1084 | return MIFARE_Write(blockAddr, buffer, 16); 1085 | } // End MIFARE_SetValue() 1086 | 1087 | ///////////////////////////////////////////////////////////////////////////////////// 1088 | // Support functions 1089 | ///////////////////////////////////////////////////////////////////////////////////// 1090 | 1091 | /** 1092 | * Wrapper for MIFARE protocol communication. 1093 | * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout. 1094 | * 1095 | * @return STATUS_OK on success, STATUS_??? otherwise. 1096 | */ 1097 | byte MFRC522::PCD_MIFARE_Transceive( byte *sendData, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A. 1098 | byte sendLen, ///< Number of bytes in sendData. 1099 | bool acceptTimeout ///< True => A timeout is also success 1100 | ) { 1101 | byte result; 1102 | byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A. 1103 | 1104 | // Sanity check 1105 | if (sendData == NULL || sendLen > 16) { 1106 | return STATUS_INVALID; 1107 | } 1108 | 1109 | // Copy sendData[] to cmdBuffer[] and add CRC_A 1110 | memcpy(cmdBuffer, sendData, sendLen); 1111 | result = PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]); 1112 | if (result != STATUS_OK) { 1113 | return result; 1114 | } 1115 | sendLen += 2; 1116 | 1117 | // Transceive the data, store the reply in cmdBuffer[] 1118 | byte waitIRq = 0x30; // RxIRq and IdleIRq 1119 | byte cmdBufferSize = sizeof(cmdBuffer); 1120 | byte validBits = 0; 1121 | result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits); 1122 | if (acceptTimeout && result == STATUS_TIMEOUT) { 1123 | return STATUS_OK; 1124 | } 1125 | if (result != STATUS_OK) { 1126 | return result; 1127 | } 1128 | // The PICC must reply with a 4 bit ACK 1129 | if (cmdBufferSize != 1 || validBits != 4) { 1130 | return STATUS_ERROR; 1131 | } 1132 | if (cmdBuffer[0] != MF_ACK) { 1133 | return STATUS_MIFARE_NACK; 1134 | } 1135 | return STATUS_OK; 1136 | } // End PCD_MIFARE_Transceive() 1137 | 1138 | /** 1139 | * Returns a __FlashStringHelper pointer to a status code name. 1140 | * 1141 | * @return const __FlashStringHelper * 1142 | */ 1143 | const __FlashStringHelper *MFRC522::GetStatusCodeName(byte code ///< One of the StatusCode enums. 1144 | ) { 1145 | switch (code) { 1146 | case STATUS_OK: return F("Success."); break; 1147 | case STATUS_ERROR: return F("Error in communication."); break; 1148 | case STATUS_COLLISION: return F("Collission detected."); break; 1149 | case STATUS_TIMEOUT: return F("Timeout in communication."); break; 1150 | case STATUS_NO_ROOM: return F("A buffer is not big enough."); break; 1151 | case STATUS_INTERNAL_ERROR: return F("Internal error in the code. Should not happen."); break; 1152 | case STATUS_INVALID: return F("Invalid argument."); break; 1153 | case STATUS_CRC_WRONG: return F("The CRC_A does not match."); break; 1154 | case STATUS_MIFARE_NACK: return F("A MIFARE PICC responded with NAK."); break; 1155 | default: return F("Unknown error"); break; 1156 | } 1157 | } // End GetStatusCodeName() 1158 | 1159 | /** 1160 | * Translates the SAK (Select Acknowledge) to a PICC type. 1161 | * 1162 | * @return PICC_Type 1163 | */ 1164 | byte MFRC522::PICC_GetType(byte sak ///< The SAK byte returned from PICC_Select(). 1165 | ) { 1166 | if (sak & 0x04) { // UID not complete 1167 | return PICC_TYPE_NOT_COMPLETE; 1168 | } 1169 | 1170 | switch (sak) { 1171 | case 0x09: return PICC_TYPE_MIFARE_MINI; break; 1172 | case 0x08: return PICC_TYPE_MIFARE_1K; break; 1173 | case 0x18: return PICC_TYPE_MIFARE_4K; break; 1174 | case 0x00: return PICC_TYPE_MIFARE_UL; break; 1175 | case 0x10: 1176 | case 0x11: return PICC_TYPE_MIFARE_PLUS; break; 1177 | case 0x01: return PICC_TYPE_TNP3XXX; break; 1178 | default: break; 1179 | } 1180 | 1181 | if (sak & 0x20) { 1182 | return PICC_TYPE_ISO_14443_4; 1183 | } 1184 | 1185 | if (sak & 0x40) { 1186 | return PICC_TYPE_ISO_18092; 1187 | } 1188 | 1189 | return PICC_TYPE_UNKNOWN; 1190 | } // End PICC_GetType() 1191 | 1192 | /** 1193 | * Returns a __FlashStringHelper pointer to the PICC type name. 1194 | * 1195 | * @return const __FlashStringHelper * 1196 | */ 1197 | const __FlashStringHelper *MFRC522::PICC_GetTypeName(byte piccType ///< One of the PICC_Type enums. 1198 | ) { 1199 | switch (piccType) { 1200 | case PICC_TYPE_ISO_14443_4: return F("PICC compliant with ISO/IEC 14443-4"); break; 1201 | case PICC_TYPE_ISO_18092: return F("PICC compliant with ISO/IEC 18092 (NFC)");break; 1202 | case PICC_TYPE_MIFARE_MINI: return F("MIFARE Mini, 320 bytes"); break; 1203 | case PICC_TYPE_MIFARE_1K: return F("MIFARE 1KB"); break; 1204 | case PICC_TYPE_MIFARE_4K: return F("MIFARE 4KB"); break; 1205 | case PICC_TYPE_MIFARE_UL: return F("MIFARE Ultralight or Ultralight C"); break; 1206 | case PICC_TYPE_MIFARE_PLUS: return F("MIFARE Plus"); break; 1207 | case PICC_TYPE_TNP3XXX: return F("MIFARE TNP3XXX"); break; 1208 | case PICC_TYPE_NOT_COMPLETE: return F("SAK indicates UID is not complete."); break; 1209 | case PICC_TYPE_UNKNOWN: 1210 | default: return F("Unknown type"); break; 1211 | } 1212 | } // End PICC_GetTypeName() 1213 | 1214 | /** 1215 | * Dumps debug info about the selected PICC to Serial. 1216 | * On success the PICC is halted after dumping the data. 1217 | * For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried. 1218 | */ 1219 | void MFRC522::PICC_DumpToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select(). 1220 | ) { 1221 | MIFARE_Key key; 1222 | 1223 | // UID 1224 | Serial.print(F("Card UID:")); 1225 | for (byte i = 0; i < uid->size; i++) { 1226 | if(uid->uidByte[i] < 0x10) 1227 | Serial.print(F(" 0")); 1228 | else 1229 | Serial.print(F(" ")); 1230 | Serial.print(uid->uidByte[i], HEX); 1231 | } 1232 | Serial.println(); 1233 | 1234 | // PICC type 1235 | byte piccType = PICC_GetType(uid->sak); 1236 | Serial.print(F("PICC type: ")); 1237 | Serial.println(PICC_GetTypeName(piccType)); 1238 | 1239 | // Dump contents 1240 | switch (piccType) { 1241 | case PICC_TYPE_MIFARE_MINI: 1242 | case PICC_TYPE_MIFARE_1K: 1243 | case PICC_TYPE_MIFARE_4K: 1244 | // All keys are set to FFFFFFFFFFFFh at chip delivery from the factory. 1245 | for (byte i = 0; i < 6; i++) { 1246 | key.keyByte[i] = 0xFF; 1247 | } 1248 | PICC_DumpMifareClassicToSerial(uid, piccType, &key); 1249 | break; 1250 | 1251 | case PICC_TYPE_MIFARE_UL: 1252 | PICC_DumpMifareUltralightToSerial(); 1253 | break; 1254 | 1255 | case PICC_TYPE_ISO_14443_4: 1256 | case PICC_TYPE_ISO_18092: 1257 | case PICC_TYPE_MIFARE_PLUS: 1258 | case PICC_TYPE_TNP3XXX: 1259 | Serial.println(F("Dumping memory contents not implemented for that PICC type.")); 1260 | break; 1261 | 1262 | case PICC_TYPE_UNKNOWN: 1263 | case PICC_TYPE_NOT_COMPLETE: 1264 | default: 1265 | break; // No memory dump here 1266 | } 1267 | 1268 | Serial.println(); 1269 | PICC_HaltA(); // Already done if it was a MIFARE Classic PICC. 1270 | } // End PICC_DumpToSerial() 1271 | 1272 | /** 1273 | * Dumps memory contents of a MIFARE Classic PICC. 1274 | * On success the PICC is halted after dumping the data. 1275 | */ 1276 | void MFRC522::PICC_DumpMifareClassicToSerial( Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1277 | byte piccType, ///< One of the PICC_Type enums. 1278 | MIFARE_Key *key ///< Key A used for all sectors. 1279 | ) { 1280 | byte no_of_sectors = 0; 1281 | switch (piccType) { 1282 | case PICC_TYPE_MIFARE_MINI: 1283 | // Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 1284 | no_of_sectors = 5; 1285 | break; 1286 | 1287 | case PICC_TYPE_MIFARE_1K: 1288 | // Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 1289 | no_of_sectors = 16; 1290 | break; 1291 | 1292 | case PICC_TYPE_MIFARE_4K: 1293 | // Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 1294 | no_of_sectors = 40; 1295 | break; 1296 | 1297 | default: // Should not happen. Ignore. 1298 | break; 1299 | } 1300 | 1301 | // Dump sectors, highest address first. 1302 | if (no_of_sectors) { 1303 | Serial.println(F("Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits")); 1304 | for (int8_t i = no_of_sectors - 1; i >= 0; i--) { 1305 | PICC_DumpMifareClassicSectorToSerial(uid, key, i); 1306 | } 1307 | } 1308 | PICC_HaltA(); // Halt the PICC before stopping the encrypted session. 1309 | PCD_StopCrypto1(); 1310 | } // End PICC_DumpMifareClassicToSerial() 1311 | 1312 | /** 1313 | * Dumps memory contents of a sector of a MIFARE Classic PICC. 1314 | * Uses PCD_Authenticate(), MIFARE_Read() and PCD_StopCrypto1. 1315 | * Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits. 1316 | */ 1317 | void MFRC522::PICC_DumpMifareClassicSectorToSerial(Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1318 | MIFARE_Key *key, ///< Key A for the sector. 1319 | byte sector ///< The sector to dump, 0..39. 1320 | ) { 1321 | byte status; 1322 | byte firstBlock; // Address of lowest address to dump actually last block dumped) 1323 | byte no_of_blocks; // Number of blocks in sector 1324 | bool isSectorTrailer; // Set to true while handling the "last" (ie highest address) in the sector. 1325 | 1326 | // The access bits are stored in a peculiar fashion. 1327 | // There are four groups: 1328 | // g[3] Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1329 | // g[2] Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1330 | // g[1] Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1331 | // g[0] Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1332 | // Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB. 1333 | // The four CX bits are stored together in a nible cx and an inverted nible cx_. 1334 | byte c1, c2, c3; // Nibbles 1335 | byte c1_, c2_, c3_; // Inverted nibbles 1336 | bool invertedError; // True if one of the inverted nibbles did not match 1337 | byte g[4]; // Access bits for each of the four groups. 1338 | byte group; // 0-3 - active group for access bits 1339 | bool firstInGroup; // True for the first block dumped in the group 1340 | 1341 | // Determine position and size of sector. 1342 | if (sector < 32) { // Sectors 0..31 has 4 blocks each 1343 | no_of_blocks = 4; 1344 | firstBlock = sector * no_of_blocks; 1345 | } 1346 | else if (sector < 40) { // Sectors 32-39 has 16 blocks each 1347 | no_of_blocks = 16; 1348 | firstBlock = 128 + (sector - 32) * no_of_blocks; 1349 | } 1350 | else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors. 1351 | return; 1352 | } 1353 | 1354 | // Dump blocks, highest address first. 1355 | byte byteCount; 1356 | byte buffer[18]; 1357 | byte blockAddr; 1358 | isSectorTrailer = true; 1359 | for (int8_t blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) { 1360 | blockAddr = firstBlock + blockOffset; 1361 | // Sector number - only on first line 1362 | if (isSectorTrailer) { 1363 | if(sector < 10) 1364 | Serial.print(F(" ")); // Pad with spaces 1365 | else 1366 | Serial.print(F(" ")); // Pad with spaces 1367 | Serial.print(sector); 1368 | Serial.print(F(" ")); 1369 | } 1370 | else { 1371 | Serial.print(F(" ")); 1372 | } 1373 | // Block number 1374 | if(blockAddr < 10) 1375 | Serial.print(F(" ")); // Pad with spaces 1376 | else { 1377 | if(blockAddr < 100) 1378 | Serial.print(F(" ")); // Pad with spaces 1379 | else 1380 | Serial.print(F(" ")); // Pad with spaces 1381 | } 1382 | Serial.print(blockAddr); 1383 | Serial.print(F(" ")); 1384 | // Establish encrypted communications before reading the first block 1385 | if (isSectorTrailer) { 1386 | status = PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid); 1387 | if (status != STATUS_OK) { 1388 | Serial.print(F("PCD_Authenticate() failed: ")); 1389 | Serial.println(GetStatusCodeName(status)); 1390 | return; 1391 | } 1392 | } 1393 | // Read block 1394 | byteCount = sizeof(buffer); 1395 | status = MIFARE_Read(blockAddr, buffer, &byteCount); 1396 | if (status != STATUS_OK) { 1397 | Serial.print(F("MIFARE_Read() failed: ")); 1398 | Serial.println(GetStatusCodeName(status)); 1399 | continue; 1400 | } 1401 | // Dump data 1402 | for (byte index = 0; index < 16; index++) { 1403 | if(buffer[index] < 0x10) 1404 | Serial.print(F(" 0")); 1405 | else 1406 | Serial.print(F(" ")); 1407 | Serial.print(buffer[index], HEX); 1408 | if ((index % 4) == 3) { 1409 | Serial.print(F(" ")); 1410 | } 1411 | } 1412 | // Parse sector trailer data 1413 | if (isSectorTrailer) { 1414 | c1 = buffer[7] >> 4; 1415 | c2 = buffer[8] & 0xF; 1416 | c3 = buffer[8] >> 4; 1417 | c1_ = buffer[6] & 0xF; 1418 | c2_ = buffer[6] >> 4; 1419 | c3_ = buffer[7] & 0xF; 1420 | invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF)); 1421 | g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0); 1422 | g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1); 1423 | g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2); 1424 | g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3); 1425 | isSectorTrailer = false; 1426 | } 1427 | 1428 | // Which access group is this block in? 1429 | if (no_of_blocks == 4) { 1430 | group = blockOffset; 1431 | firstInGroup = true; 1432 | } 1433 | else { 1434 | group = blockOffset / 5; 1435 | firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5); 1436 | } 1437 | 1438 | if (firstInGroup) { 1439 | // Print access bits 1440 | Serial.print(F(" [ ")); 1441 | Serial.print((g[group] >> 2) & 1, DEC); Serial.print(F(" ")); 1442 | Serial.print((g[group] >> 1) & 1, DEC); Serial.print(F(" ")); 1443 | Serial.print((g[group] >> 0) & 1, DEC); 1444 | Serial.print(F(" ] ")); 1445 | if (invertedError) { 1446 | Serial.print(F(" Inverted access bits did not match! ")); 1447 | } 1448 | } 1449 | 1450 | if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block 1451 | long value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1452 | Serial.print(F(" Value=0x")); Serial.print(value, HEX); 1453 | Serial.print(F(" Adr=0x")); Serial.print(buffer[12], HEX); 1454 | } 1455 | Serial.println(); 1456 | } 1457 | 1458 | return; 1459 | } // End PICC_DumpMifareClassicSectorToSerial() 1460 | 1461 | /** 1462 | * Dumps memory contents of a MIFARE Ultralight PICC. 1463 | */ 1464 | void MFRC522::PICC_DumpMifareUltralightToSerial() { 1465 | byte status; 1466 | byte byteCount; 1467 | byte buffer[18]; 1468 | byte i; 1469 | 1470 | Serial.println(F("Page 0 1 2 3")); 1471 | // Try the mpages of the original Ultralight. Ultralight C has more pages. 1472 | for (byte page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time. 1473 | // Read pages 1474 | byteCount = sizeof(buffer); 1475 | status = MIFARE_Read(page, buffer, &byteCount); 1476 | if (status != STATUS_OK) { 1477 | Serial.print(F("MIFARE_Read() failed: ")); 1478 | Serial.println(GetStatusCodeName(status)); 1479 | break; 1480 | } 1481 | // Dump data 1482 | for (byte offset = 0; offset < 4; offset++) { 1483 | i = page + offset; 1484 | if(i < 10) 1485 | Serial.print(F(" ")); // Pad with spaces 1486 | else 1487 | Serial.print(F(" ")); // Pad with spaces 1488 | Serial.print(i); 1489 | Serial.print(F(" ")); 1490 | for (byte index = 0; index < 4; index++) { 1491 | i = 4 * offset + index; 1492 | if(buffer[i] < 0x10) 1493 | Serial.print(F(" 0")); 1494 | else 1495 | Serial.print(F(" ")); 1496 | Serial.print(buffer[i], HEX); 1497 | } 1498 | Serial.println(); 1499 | } 1500 | } 1501 | } // End PICC_DumpMifareUltralightToSerial() 1502 | 1503 | /** 1504 | * 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). 1505 | */ 1506 | void MFRC522::MIFARE_SetAccessBits( byte *accessBitBuffer, ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set. 1507 | byte g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1508 | byte g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1509 | byte g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1510 | byte g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1511 | ) { 1512 | byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2); 1513 | byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1); 1514 | byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0); 1515 | 1516 | accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF); 1517 | accessBitBuffer[1] = c1 << 4 | (~c3 & 0xF); 1518 | accessBitBuffer[2] = c3 << 4 | c2; 1519 | } // End MIFARE_SetAccessBits() 1520 | 1521 | 1522 | /** 1523 | * Performs the "magic sequence" needed to get Chinese UID changeable 1524 | * Mifare cards to allow writing to sector 0, where the card UID is stored. 1525 | * 1526 | * Note that you do not need to have selected the card through REQA or WUPA, 1527 | * this sequence works immediately when the card is in the reader vicinity. 1528 | * This means you can use this method even on "bricked" cards that your reader does 1529 | * not recognise anymore (see MFRC522::MIFARE_UnbrickUidSector). 1530 | * 1531 | * Of course with non-bricked devices, you're free to select them before calling this function. 1532 | */ 1533 | bool MFRC522::MIFARE_OpenUidBackdoor(bool logErrors) { 1534 | // Magic sequence: 1535 | // > 50 00 57 CD (HALT + CRC) 1536 | // > 40 (7 bits only) 1537 | // < A (4 bits only) 1538 | // > 43 1539 | // < A (4 bits only) 1540 | // Then you can write to sector 0 without authenticating 1541 | 1542 | PICC_HaltA(); // 50 00 57 CD 1543 | 1544 | byte cmd = 0x40; 1545 | byte validBits = 7; /* Our command is only 7 bits. After receiving card response, 1546 | this will contain amount of valid response bits. */ 1547 | byte response[32]; // Card's response is written here 1548 | byte received; 1549 | byte status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 40 1550 | if(status != STATUS_OK) { 1551 | if(logErrors) { 1552 | Serial.println(F("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?")); 1553 | Serial.print(F("Error name: ")); 1554 | Serial.println(GetStatusCodeName(status)); 1555 | } 1556 | return false; 1557 | } 1558 | if (received != 1 || response[0] != 0x0A) { 1559 | if (logErrors) { 1560 | Serial.print(F("Got bad response on backdoor 0x40 command: ")); 1561 | Serial.print(response[0], HEX); 1562 | Serial.print(F(" (")); 1563 | Serial.print(validBits); 1564 | Serial.print(F(" valid bits)\r\n")); 1565 | } 1566 | return false; 1567 | } 1568 | 1569 | cmd = 0x43; 1570 | validBits = 8; 1571 | status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 43 1572 | if(status != STATUS_OK) { 1573 | if(logErrors) { 1574 | Serial.println(F("Error in communication at command 0x43, after successfully executing 0x40")); 1575 | Serial.print(F("Error name: ")); 1576 | Serial.println(GetStatusCodeName(status)); 1577 | } 1578 | return false; 1579 | } 1580 | if (received != 1 || response[0] != 0x0A) { 1581 | if (logErrors) { 1582 | Serial.print(F("Got bad response on backdoor 0x43 command: ")); 1583 | Serial.print(response[0], HEX); 1584 | Serial.print(F(" (")); 1585 | Serial.print(validBits); 1586 | Serial.print(F(" valid bits)\r\n")); 1587 | } 1588 | return false; 1589 | } 1590 | 1591 | // You can now write to sector 0 without authenticating! 1592 | return true; 1593 | } // End MIFARE_OpenUidBackdoor() 1594 | 1595 | /** 1596 | * Reads entire block 0, including all manufacturer data, and overwrites 1597 | * that block with the new UID, a freshly calculated BCC, and the original 1598 | * manufacturer data. 1599 | * 1600 | * It assumes a default KEY A of 0xFFFFFFFFFFFF. 1601 | * Make sure to have selected the card before this function is called. 1602 | */ 1603 | bool MFRC522::MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors) { 1604 | 1605 | // UID + BCC byte can not be larger than 16 together 1606 | if (!newUid || !uidSize || uidSize > 15) { 1607 | if (logErrors) { 1608 | Serial.println(F("New UID buffer empty, size 0, or size > 15 given")); 1609 | } 1610 | return false; 1611 | } 1612 | 1613 | // Authenticate for reading 1614 | MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 1615 | byte status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1616 | if (status != STATUS_OK) { 1617 | 1618 | if (status == STATUS_TIMEOUT) { 1619 | // We get a read timeout if no card is selected yet, so let's select one 1620 | 1621 | // Wake the card up again if sleeping 1622 | // byte atqa_answer[2]; 1623 | // byte atqa_size = 2; 1624 | // PICC_WakeupA(atqa_answer, &atqa_size); 1625 | 1626 | if (!PICC_IsNewCardPresent() || !PICC_ReadCardSerial()) { 1627 | Serial.println(F("No card was previously selected, and none are available. Failed to set UID.")); 1628 | return false; 1629 | } 1630 | 1631 | status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1632 | if (status != STATUS_OK) { 1633 | // We tried, time to give up 1634 | if (logErrors) { 1635 | Serial.println(F("Failed to authenticate to card for reading, could not set UID: ")); 1636 | Serial.println(GetStatusCodeName(status)); 1637 | } 1638 | return false; 1639 | } 1640 | } 1641 | else { 1642 | if (logErrors) { 1643 | Serial.print(F("PCD_Authenticate() failed: ")); 1644 | Serial.println(GetStatusCodeName(status)); 1645 | } 1646 | return false; 1647 | } 1648 | } 1649 | 1650 | // Read block 0 1651 | byte block0_buffer[18]; 1652 | byte byteCount = sizeof(block0_buffer); 1653 | status = MIFARE_Read((byte)0, block0_buffer, &byteCount); 1654 | if (status != STATUS_OK) { 1655 | if (logErrors) { 1656 | Serial.print(F("MIFARE_Read() failed: ")); 1657 | Serial.println(GetStatusCodeName(status)); 1658 | Serial.println(F("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?")); 1659 | } 1660 | return false; 1661 | } 1662 | 1663 | // Write new UID to the data we just read, and calculate BCC byte 1664 | byte bcc = 0; 1665 | for (int i = 0; i < uidSize; i++) { 1666 | block0_buffer[i] = newUid[i]; 1667 | bcc ^= newUid[i]; 1668 | } 1669 | 1670 | // Write BCC byte to buffer 1671 | block0_buffer[uidSize] = bcc; 1672 | 1673 | // Stop encrypted traffic so we can send raw bytes 1674 | PCD_StopCrypto1(); 1675 | 1676 | // Activate UID backdoor 1677 | if (!MIFARE_OpenUidBackdoor(logErrors)) { 1678 | if (logErrors) { 1679 | Serial.println(F("Activating the UID backdoor failed.")); 1680 | } 1681 | return false; 1682 | } 1683 | 1684 | // Write modified block 0 back to card 1685 | status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1686 | if (status != STATUS_OK) { 1687 | if (logErrors) { 1688 | Serial.print(F("MIFARE_Write() failed: ")); 1689 | Serial.println(GetStatusCodeName(status)); 1690 | } 1691 | return false; 1692 | } 1693 | 1694 | // Wake the card up again 1695 | byte atqa_answer[2]; 1696 | byte atqa_size = 2; 1697 | PICC_WakeupA(atqa_answer, &atqa_size); 1698 | 1699 | return true; 1700 | } 1701 | 1702 | /** 1703 | * Resets entire sector 0 to zeroes, so the card can be read again by readers. 1704 | */ 1705 | bool MFRC522::MIFARE_UnbrickUidSector(bool logErrors) { 1706 | MIFARE_OpenUidBackdoor(logErrors); 1707 | 1708 | byte block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 1709 | 1710 | // Write modified block 0 back to card 1711 | byte status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1712 | if (status != STATUS_OK) { 1713 | if (logErrors) { 1714 | Serial.print(F("MIFARE_Write() failed: ")); 1715 | Serial.println(GetStatusCodeName(status)); 1716 | } 1717 | return false; 1718 | } 1719 | return true; 1720 | } 1721 | 1722 | ///////////////////////////////////////////////////////////////////////////////////// 1723 | // Convenience functions - does not add extra functionality 1724 | ///////////////////////////////////////////////////////////////////////////////////// 1725 | 1726 | /** 1727 | * Returns true if a PICC responds to PICC_CMD_REQA. 1728 | * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored. 1729 | * 1730 | * @return bool 1731 | */ 1732 | bool MFRC522::PICC_IsNewCardPresent() { 1733 | byte bufferATQA[2]; 1734 | byte bufferSize = sizeof(bufferATQA); 1735 | byte result = PICC_RequestA(bufferATQA, &bufferSize); 1736 | return (result == STATUS_OK || result == STATUS_COLLISION); 1737 | } // End PICC_IsNewCardPresent() 1738 | 1739 | /** 1740 | * Simple wrapper around PICC_Select. 1741 | * Returns true if a UID could be read. 1742 | * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first. 1743 | * The read UID is available in the class variable uid. 1744 | * 1745 | * @return bool 1746 | */ 1747 | bool MFRC522::PICC_ReadCardSerial() { 1748 | byte result = PICC_Select(&uid); 1749 | return (result == STATUS_OK); 1750 | } // End PICC_ReadCardSerial() 1751 | -------------------------------------------------------------------------------- /MFRC522_I2C.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MFRC522_I2C.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522_I2C.h - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * Based on code Dr.Leong ( WWW.B2CQSHOP.COM ) 5 | * Created by Miguel Balboa (circuitito.com), Jan, 2012. 6 | * Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.) 7 | * Extended by Tom Clement with functionality to write to sector 0 of UID changeable Mifare cards. 8 | * Extended by Ahmet Remzi Ozcan with I2C functionality. 9 | * Released into the public domain. 10 | * 11 | * Please read this file for an overview and then MFRC522.cpp for comments on the specific functions. 12 | * Search for "mf-rc522" on ebay.com to purchase the MF-RC522 board. 13 | * 14 | * There are three hardware components involved: 15 | * 1) The micro controller: An Arduino 16 | * 2) The PCD (short for Proximity Coupling Device): NXP MFRC522 Contactless Reader IC 17 | * 3) The PICC (short for Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203. 18 | * 19 | * The microcontroller and card reader uses I2C for communication. 20 | * The protocol is described in the MFRC522 datasheet: http://www.nxp.com/documents/data_sheet/MFRC522.pdf 21 | * 22 | * The card reader and the tags communicate using a 13.56MHz electromagnetic field. 23 | * The protocol is defined in ISO/IEC 14443-3 Identification cards -- Contactless integrated circuit cards -- Proximity cards -- Part 3: Initialization and anticollision". 24 | * A free version of the final draft can be found at http://wg8.de/wg8n1496_17n3613_Ballot_FCD14443-3.pdf 25 | * Details are found in chapter 6, Type A – Initialization and anticollision. 26 | * 27 | * If only the PICC UID is wanted, the above documents has all the needed information. 28 | * To read and write from MIFARE PICCs, the MIFARE protocol is used after the PICC has been selected. 29 | * The MIFARE Classic chips and protocol is described in the datasheets: 30 | * 1K: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf 31 | * 4K: http://www.nxp.com/documents/data_sheet/MF1S703x.pdf 32 | * Mini: http://www.idcardmarket.com/download/mifare_S20_datasheet.pdf 33 | * The MIFARE Ultralight chip and protocol is described in the datasheets: 34 | * Ultralight: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf 35 | * Ultralight C: http://www.nxp.com/documents/short_data_sheet/MF0ICU2_SDS.pdf 36 | * 37 | * MIFARE Classic 1K (MF1S503x): 38 | * Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 39 | * The blocks are numbered 0-63. 40 | * 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: 41 | * Bytes 0-5: Key A 42 | * Bytes 6-8: Access Bits 43 | * Bytes 9: User data 44 | * Bytes 10-15: Key B (or user data) 45 | * Block 0 is read-only manufacturer data. 46 | * To access a block, an authentication using a key from the block's sector must be performed first. 47 | * Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11). 48 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 49 | * 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. 50 | * 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. 51 | * MIFARE Classic 4K (MF1S703x): 52 | * Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 53 | * The blocks are numbered 0-255. 54 | * The last block in each sector is the Sector Trailer like above. 55 | * MIFARE Classic Mini (MF1 IC S20): 56 | * Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 57 | * The blocks are numbered 0-19. 58 | * The last block in each sector is the Sector Trailer like above. 59 | * 60 | * MIFARE Ultralight (MF0ICU1): 61 | * Has 16 pages of 4 bytes = 64 bytes. 62 | * Pages 0 + 1 is used for the 7-byte UID. 63 | * Page 2 contains the last check 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) 64 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 65 | * Pages 4-15 are read/write unless blocked by the lock bytes in page 2. 66 | * MIFARE Ultralight C (MF0ICU2): 67 | * Has 48 pages of 4 bytes = 192 bytes. 68 | * Pages 0 + 1 is used for the 7-byte UID. 69 | * Page 2 contains the last check 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) 70 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 71 | * Pages 4-39 are read/write unless blocked by the lock bytes in page 2. 72 | * Page 40 Lock bytes 73 | * Page 41 16 bit one way counter 74 | * Pages 42-43 Authentication configuration 75 | * Pages 44-47 Authentication key 76 | */ 77 | #ifndef MFRC522_h 78 | #define MFRC522_h 79 | 80 | #include 81 | #include 82 | 83 | // Firmware data for self-test 84 | // Reference values based on firmware version 85 | // Hint: if needed, you can remove unused self-test data to save flash memory 86 | // 87 | // Version 0.0 (0x90) 88 | // Philips Semiconductors; Preliminary Specification Revision 2.0 - 01 August 2005; 16.1 Sefttest 89 | const byte MFRC522_firmware_referenceV0_0[] PROGMEM = { 90 | 0x00, 0x87, 0x98, 0x0f, 0x49, 0xFF, 0x07, 0x19, 91 | 0xBF, 0x22, 0x30, 0x49, 0x59, 0x63, 0xAD, 0xCA, 92 | 0x7F, 0xE3, 0x4E, 0x03, 0x5C, 0x4E, 0x49, 0x50, 93 | 0x47, 0x9A, 0x37, 0x61, 0xE7, 0xE2, 0xC6, 0x2E, 94 | 0x75, 0x5A, 0xED, 0x04, 0x3D, 0x02, 0x4B, 0x78, 95 | 0x32, 0xFF, 0x58, 0x3B, 0x7C, 0xE9, 0x00, 0x94, 96 | 0xB4, 0x4A, 0x59, 0x5B, 0xFD, 0xC9, 0x29, 0xDF, 97 | 0x35, 0x96, 0x98, 0x9E, 0x4F, 0x30, 0x32, 0x8D 98 | }; 99 | // Version 1.0 (0x91) 100 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 101 | const byte MFRC522_firmware_referenceV1_0[] PROGMEM = { 102 | 0x00, 0xC6, 0x37, 0xD5, 0x32, 0xB7, 0x57, 0x5C, 103 | 0xC2, 0xD8, 0x7C, 0x4D, 0xD9, 0x70, 0xC7, 0x73, 104 | 0x10, 0xE6, 0xD2, 0xAA, 0x5E, 0xA1, 0x3E, 0x5A, 105 | 0x14, 0xAF, 0x30, 0x61, 0xC9, 0x70, 0xDB, 0x2E, 106 | 0x64, 0x22, 0x72, 0xB5, 0xBD, 0x65, 0xF4, 0xEC, 107 | 0x22, 0xBC, 0xD3, 0x72, 0x35, 0xCD, 0xAA, 0x41, 108 | 0x1F, 0xA7, 0xF3, 0x53, 0x14, 0xDE, 0x7E, 0x02, 109 | 0xD9, 0x0F, 0xB5, 0x5E, 0x25, 0x1D, 0x29, 0x79 110 | }; 111 | // Version 2.0 (0x92) 112 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 113 | const byte MFRC522_firmware_referenceV2_0[] PROGMEM = { 114 | 0x00, 0xEB, 0x66, 0xBA, 0x57, 0xBF, 0x23, 0x95, 115 | 0xD0, 0xE3, 0x0D, 0x3D, 0x27, 0x89, 0x5C, 0xDE, 116 | 0x9D, 0x3B, 0xA7, 0x00, 0x21, 0x5B, 0x89, 0x82, 117 | 0x51, 0x3A, 0xEB, 0x02, 0x0C, 0xA5, 0x00, 0x49, 118 | 0x7C, 0x84, 0x4D, 0xB3, 0xCC, 0xD2, 0x1B, 0x81, 119 | 0x5D, 0x48, 0x76, 0xD5, 0x71, 0x61, 0x21, 0xA9, 120 | 0x86, 0x96, 0x83, 0x38, 0xCF, 0x9D, 0x5B, 0x6D, 121 | 0xDC, 0x15, 0xBA, 0x3E, 0x7D, 0x95, 0x3B, 0x2F 122 | }; 123 | // Clone 124 | // Fudan Semiconductor FM17522 (0x88) 125 | const byte FM17522_firmware_reference[] PROGMEM = { 126 | 0x00, 0xD6, 0x78, 0x8C, 0xE2, 0xAA, 0x0C, 0x18, 127 | 0x2A, 0xB8, 0x7A, 0x7F, 0xD3, 0x6A, 0xCF, 0x0B, 128 | 0xB1, 0x37, 0x63, 0x4B, 0x69, 0xAE, 0x91, 0xC7, 129 | 0xC3, 0x97, 0xAE, 0x77, 0xF4, 0x37, 0xD7, 0x9B, 130 | 0x7C, 0xF5, 0x3C, 0x11, 0x8F, 0x15, 0xC3, 0xD7, 131 | 0xC1, 0x5B, 0x00, 0x2A, 0xD0, 0x75, 0xDE, 0x9E, 132 | 0x51, 0x64, 0xAB, 0x3E, 0xE9, 0x15, 0xB5, 0xAB, 133 | 0x56, 0x9A, 0x98, 0x82, 0x26, 0xEA, 0x2A, 0x62 134 | }; 135 | 136 | class MFRC522 { 137 | public: 138 | // MFRC522 registers. Described in chapter 9 of the datasheet. 139 | enum PCD_Register { 140 | // Page 0: Command and status 141 | // 0x00 // reserved for future use 142 | CommandReg = 0x01 , // starts and stops command execution 143 | ComIEnReg = 0x02 , // enable and disable interrupt request control bits 144 | DivIEnReg = 0x03 , // enable and disable interrupt request control bits 145 | ComIrqReg = 0x04 , // interrupt request bits 146 | DivIrqReg = 0x05 , // interrupt request bits 147 | ErrorReg = 0x06 , // error bits showing the error status of the last command executed 148 | Status1Reg = 0x07 , // communication status bits 149 | Status2Reg = 0x08 , // receiver and transmitter status bits 150 | FIFODataReg = 0x09 , // input and output of 64 byte FIFO buffer 151 | FIFOLevelReg = 0x0A , // number of bytes stored in the FIFO buffer 152 | WaterLevelReg = 0x0B , // level for FIFO underflow and overflow warning 153 | ControlReg = 0x0C , // miscellaneous control registers 154 | BitFramingReg = 0x0D , // adjustments for bit-oriented frames 155 | CollReg = 0x0E , // bit position of the first bit-collision detected on the RF interface 156 | // 0x0F // reserved for future use 157 | 158 | // Page 1: Command 159 | // 0x10 // reserved for future use 160 | ModeReg = 0x11 , // defines general modes for transmitting and receiving 161 | TxModeReg = 0x12 , // defines transmission data rate and framing 162 | RxModeReg = 0x13 , // defines reception data rate and framing 163 | TxControlReg = 0x14 , // controls the logical behavior of the antenna driver pins TX1 and TX2 164 | TxASKReg = 0x15 , // controls the setting of the transmission modulation 165 | TxSelReg = 0x16 , // selects the internal sources for the antenna driver 166 | RxSelReg = 0x17 , // selects internal receiver settings 167 | RxThresholdReg = 0x18 , // selects thresholds for the bit decoder 168 | DemodReg = 0x19 , // defines demodulator settings 169 | // 0x1A // reserved for future use 170 | // 0x1B // reserved for future use 171 | MfTxReg = 0x1C , // controls some MIFARE communication transmit parameters 172 | MfRxReg = 0x1D , // controls some MIFARE communication receive parameters 173 | // 0x1E // reserved for future use 174 | SerialSpeedReg = 0x1F , // selects the speed of the serial UART interface 175 | 176 | // Page 2: Configuration 177 | // 0x20 // reserved for future use 178 | CRCResultRegH = 0x21 , // shows the MSB and LSB values of the CRC calculation 179 | CRCResultRegL = 0x22 , 180 | // 0x23 // reserved for future use 181 | ModWidthReg = 0x24 , // controls the ModWidth setting? 182 | // 0x25 // reserved for future use 183 | RFCfgReg = 0x26 , // configures the receiver gain 184 | GsNReg = 0x27 , // selects the conductance of the antenna driver pins TX1 and TX2 for modulation 185 | CWGsPReg = 0x28 , // defines the conductance of the p-driver output during periods of no modulation 186 | ModGsPReg = 0x29 , // defines the conductance of the p-driver output during periods of modulation 187 | TModeReg = 0x2A , // defines settings for the internal timer 188 | TPrescalerReg = 0x2B , // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg. 189 | TReloadRegH = 0x2C , // defines the 16-bit timer reload value 190 | TReloadRegL = 0x2D , 191 | TCounterValueRegH = 0x2E , // shows the 16-bit timer value 192 | TCounterValueRegL = 0x2F , 193 | 194 | // Page 3: Test Registers 195 | // 0x30 // reserved for future use 196 | TestSel1Reg = 0x31 , // general test signal configuration 197 | TestSel2Reg = 0x32 , // general test signal configuration 198 | TestPinEnReg = 0x33 , // enables pin output driver on pins D1 to D7 199 | TestPinValueReg = 0x34 , // defines the values for D1 to D7 when it is used as an I/O bus 200 | TestBusReg = 0x35 , // shows the status of the internal test bus 201 | AutoTestReg = 0x36 , // controls the digital self test 202 | VersionReg = 0x37 , // shows the software version 203 | AnalogTestReg = 0x38 , // controls the pins AUX1 and AUX2 204 | TestDAC1Reg = 0x39 , // defines the test value for TestDAC1 205 | TestDAC2Reg = 0x3A , // defines the test value for TestDAC2 206 | TestADCReg = 0x3B // shows the value of ADC I and Q channels 207 | // 0x3C // reserved for production tests 208 | // 0x3D // reserved for production tests 209 | // 0x3E // reserved for production tests 210 | // 0x3F // reserved for production tests 211 | }; 212 | 213 | // MFRC522 commands. Described in chapter 10 of the datasheet. 214 | enum PCD_Command { 215 | PCD_Idle = 0x00, // no action, cancels current command execution 216 | PCD_Mem = 0x01, // stores 25 bytes into the internal buffer 217 | PCD_GenerateRandomID = 0x02, // generates a 10-byte random ID number 218 | PCD_CalcCRC = 0x03, // activates the CRC coprocessor or performs a self test 219 | PCD_Transmit = 0x04, // transmits data from the FIFO buffer 220 | PCD_NoCmdChange = 0x07, // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit 221 | PCD_Receive = 0x08, // activates the receiver circuits 222 | PCD_Transceive = 0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission 223 | PCD_MFAuthent = 0x0E, // performs the MIFARE standard authentication as a reader 224 | PCD_SoftReset = 0x0F // resets the MFRC522 225 | }; 226 | 227 | // MFRC522 RxGain[2:0] masks, defines the receiver's signal voltage gain factor (on the PCD). 228 | // Described in 9.3.3.6 / table 98 of the datasheet at http://www.nxp.com/documents/data_sheet/MFRC522.pdf 229 | enum PCD_RxGain { 230 | RxGain_18dB = 0x00 << 4, // 000b - 18 dB, minimum 231 | RxGain_23dB = 0x01 << 4, // 001b - 23 dB 232 | RxGain_18dB_2 = 0x02 << 4, // 010b - 18 dB, it seems 010b is a duplicate for 000b 233 | RxGain_23dB_2 = 0x03 << 4, // 011b - 23 dB, it seems 011b is a duplicate for 001b 234 | RxGain_33dB = 0x04 << 4, // 100b - 33 dB, average, and typical default 235 | RxGain_38dB = 0x05 << 4, // 101b - 38 dB 236 | RxGain_43dB = 0x06 << 4, // 110b - 43 dB 237 | RxGain_48dB = 0x07 << 4, // 111b - 48 dB, maximum 238 | RxGain_min = 0x00 << 4, // 000b - 18 dB, minimum, convenience for RxGain_18dB 239 | RxGain_avg = 0x04 << 4, // 100b - 33 dB, average, convenience for RxGain_33dB 240 | RxGain_max = 0x07 << 4 // 111b - 48 dB, maximum, convenience for RxGain_48dB 241 | }; 242 | 243 | // Commands sent to the PICC. 244 | enum PICC_Command { 245 | // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4) 246 | 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. 247 | 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. 248 | PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision. 249 | PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1 250 | PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2 251 | PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3 252 | PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT. 253 | // The commands used for MIFARE Classic (from http://www.nxp.com/documents/data_sheet/MF1S503x.pdf, Section 9) 254 | // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector. 255 | // The read/write commands can also be used for MIFARE Ultralight. 256 | PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A 257 | PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B 258 | PICC_CMD_MF_READ = 0x30, // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight. 259 | PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight. 260 | PICC_CMD_MF_DECREMENT = 0xC0, // Decrements the contents of a block and stores the result in the internal data register. 261 | PICC_CMD_MF_INCREMENT = 0xC1, // Increments the contents of a block and stores the result in the internal data register. 262 | PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register. 263 | PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block. 264 | // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6) 265 | // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight. 266 | PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 byte page to the PICC. 267 | }; 268 | 269 | // MIFARE constants that does not fit anywhere else 270 | enum MIFARE_Misc { 271 | MF_ACK = 0xA, // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK. 272 | MF_KEY_SIZE = 6 // A Mifare Crypto1 key is 6 bytes. 273 | }; 274 | 275 | // PICC types we can detect. Remember to update PICC_GetTypeName() if you add more. 276 | enum PICC_Type { 277 | PICC_TYPE_UNKNOWN = 0, 278 | PICC_TYPE_ISO_14443_4 = 1, // PICC compliant with ISO/IEC 14443-4 279 | PICC_TYPE_ISO_18092 = 2, // PICC compliant with ISO/IEC 18092 (NFC) 280 | PICC_TYPE_MIFARE_MINI = 3, // MIFARE Classic protocol, 320 bytes 281 | PICC_TYPE_MIFARE_1K = 4, // MIFARE Classic protocol, 1KB 282 | PICC_TYPE_MIFARE_4K = 5, // MIFARE Classic protocol, 4KB 283 | PICC_TYPE_MIFARE_UL = 6, // MIFARE Ultralight or Ultralight C 284 | PICC_TYPE_MIFARE_PLUS = 7, // MIFARE Plus 285 | PICC_TYPE_TNP3XXX = 8, // Only mentioned in NXP AN 10833 MIFARE Type Identification Procedure 286 | PICC_TYPE_NOT_COMPLETE = 255 // SAK indicates UID is not complete. 287 | }; 288 | 289 | // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more. 290 | enum StatusCode { 291 | STATUS_OK = 1, // Success 292 | STATUS_ERROR = 2, // Error in communication 293 | STATUS_COLLISION = 3, // Collission detected 294 | STATUS_TIMEOUT = 4, // Timeout in communication. 295 | STATUS_NO_ROOM = 5, // A buffer is not big enough. 296 | STATUS_INTERNAL_ERROR = 6, // Internal error in the code. Should not happen ;-) 297 | STATUS_INVALID = 7, // Invalid argument. 298 | STATUS_CRC_WRONG = 8, // The CRC_A does not match 299 | STATUS_MIFARE_NACK = 9 // A MIFARE PICC responded with NAK. 300 | }; 301 | 302 | // A struct used for passing the UID of a PICC. 303 | typedef struct { 304 | byte size; // Number of bytes in the UID. 4, 7 or 10. 305 | byte uidByte[10]; 306 | byte sak; // The SAK (Select acknowledge) byte returned from the PICC after successful selection. 307 | } Uid; 308 | 309 | // A struct used for passing a MIFARE Crypto1 key 310 | typedef struct { 311 | byte keyByte[MF_KEY_SIZE]; 312 | } MIFARE_Key; 313 | 314 | // Member variables 315 | Uid uid; // Used by PICC_ReadCardSerial(). 316 | 317 | // Size of the MFRC522 FIFO 318 | static const byte FIFO_SIZE = 64; // The FIFO is 64 bytes. 319 | 320 | ///////////////////////////////////////////////////////////////////////////////////// 321 | // Functions for setting up the Arduino 322 | ///////////////////////////////////////////////////////////////////////////////////// 323 | MFRC522(byte chipAddress, byte resetPowerDownPin); 324 | 325 | ///////////////////////////////////////////////////////////////////////////////////// 326 | // Basic interface functions for communicating with the MFRC522 327 | ///////////////////////////////////////////////////////////////////////////////////// 328 | void PCD_WriteRegister(byte reg, byte value); 329 | void PCD_WriteRegister(byte reg, byte count, byte *values); 330 | byte PCD_ReadRegister(byte reg); 331 | void PCD_ReadRegister(byte reg, byte count, byte *values, byte rxAlign = 0); 332 | void setBitMask(unsigned char reg, unsigned char mask); 333 | void PCD_SetRegisterBitMask(byte reg, byte mask); 334 | void PCD_ClearRegisterBitMask(byte reg, byte mask); 335 | byte PCD_CalculateCRC(byte *data, byte length, byte *result); 336 | 337 | ///////////////////////////////////////////////////////////////////////////////////// 338 | // Functions for manipulating the MFRC522 339 | ///////////////////////////////////////////////////////////////////////////////////// 340 | void PCD_Init(); 341 | void PCD_Reset(); 342 | void PCD_AntennaOn(); 343 | void PCD_AntennaOff(); 344 | byte PCD_GetAntennaGain(); 345 | void PCD_SetAntennaGain(byte mask); 346 | bool PCD_PerformSelfTest(); 347 | 348 | ///////////////////////////////////////////////////////////////////////////////////// 349 | // Functions for communicating with PICCs 350 | ///////////////////////////////////////////////////////////////////////////////////// 351 | byte PCD_TransceiveData(byte *sendData, byte sendLen, byte *backData, byte *backLen, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 352 | byte PCD_CommunicateWithPICC(byte command, byte waitIRq, byte *sendData, byte sendLen, byte *backData = NULL, byte *backLen = NULL, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 353 | byte PICC_RequestA(byte *bufferATQA, byte *bufferSize); 354 | byte PICC_WakeupA(byte *bufferATQA, byte *bufferSize); 355 | byte PICC_REQA_or_WUPA(byte command, byte *bufferATQA, byte *bufferSize); 356 | byte PICC_Select(Uid *uid, byte validBits = 0); 357 | byte PICC_HaltA(); 358 | 359 | ///////////////////////////////////////////////////////////////////////////////////// 360 | // Functions for communicating with MIFARE PICCs 361 | ///////////////////////////////////////////////////////////////////////////////////// 362 | byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid); 363 | void PCD_StopCrypto1(); 364 | byte MIFARE_Read(byte blockAddr, byte *buffer, byte *bufferSize); 365 | byte MIFARE_Write(byte blockAddr, byte *buffer, byte bufferSize); 366 | byte MIFARE_Decrement(byte blockAddr, long delta); 367 | byte MIFARE_Increment(byte blockAddr, long delta); 368 | byte MIFARE_Restore(byte blockAddr); 369 | byte MIFARE_Transfer(byte blockAddr); 370 | byte MIFARE_Ultralight_Write(byte page, byte *buffer, byte bufferSize); 371 | byte MIFARE_GetValue(byte blockAddr, long *value); 372 | byte MIFARE_SetValue(byte blockAddr, long value); 373 | 374 | ///////////////////////////////////////////////////////////////////////////////////// 375 | // Support functions 376 | ///////////////////////////////////////////////////////////////////////////////////// 377 | byte PCD_MIFARE_Transceive(byte *sendData, byte sendLen, bool acceptTimeout = false); 378 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 379 | //const char *GetStatusCodeName(byte code); 380 | const __FlashStringHelper *GetStatusCodeName(byte code); 381 | byte PICC_GetType(byte sak); 382 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 383 | //const char *PICC_GetTypeName(byte type); 384 | const __FlashStringHelper *PICC_GetTypeName(byte type); 385 | void PICC_DumpToSerial(Uid *uid); 386 | void PICC_DumpMifareClassicToSerial(Uid *uid, byte piccType, MIFARE_Key *key); 387 | void PICC_DumpMifareClassicSectorToSerial(Uid *uid, MIFARE_Key *key, byte sector); 388 | void PICC_DumpMifareUltralightToSerial(); 389 | void MIFARE_SetAccessBits(byte *accessBitBuffer, byte g0, byte g1, byte g2, byte g3); 390 | bool MIFARE_OpenUidBackdoor(bool logErrors); 391 | bool MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors); 392 | bool MIFARE_UnbrickUidSector(bool logErrors); 393 | 394 | ///////////////////////////////////////////////////////////////////////////////////// 395 | // Convenience functions - does not add extra functionality 396 | ///////////////////////////////////////////////////////////////////////////////////// 397 | bool PICC_IsNewCardPresent(); 398 | bool PICC_ReadCardSerial(); 399 | 400 | private: 401 | byte _chipAddress; 402 | byte _resetPowerDownPin; // Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 403 | byte MIFARE_TwoStepHelper(byte command, byte blockAddr, long data); 404 | }; 405 | 406 | #endif 407 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MFRC522-I2C-Library 2 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.cproject: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 30 | 40 | 41 | 42 | 43 | 48 | 58 | 59 | 60 | 61 | 66 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | platformio 105 | -f -c eclipse 106 | run -t program 107 | true 108 | true 109 | false 110 | 111 | 112 | platformio 113 | -f -c eclipse 114 | run -t uploadfs 115 | true 116 | true 117 | false 118 | 119 | 120 | platformio 121 | -f -c eclipse 122 | run 123 | true 124 | true 125 | false 126 | 127 | 128 | platformio 129 | -f -c eclipse 130 | run -t upload 131 | true 132 | true 133 | false 134 | 135 | 136 | platformio 137 | -f -c eclipse 138 | run -t clean 139 | true 140 | true 141 | false 142 | 143 | 144 | platformio 145 | -f -c eclipse 146 | update 147 | true 148 | true 149 | false 150 | 151 | 152 | 153 | 154 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.gitignore: -------------------------------------------------------------------------------- 1 | .pioenvs 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | nodemcu_rfid 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.cdt.managedbuilder.core.genmakebuilder 10 | clean,full,incremental, 11 | 12 | 13 | 14 | 15 | org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder 16 | full,incremental, 17 | 18 | 19 | 20 | 21 | 22 | org.eclipse.cdt.core.cnature 23 | org.eclipse.cdt.core.ccnature 24 | org.eclipse.cdt.managedbuilder.core.managedBuildNature 25 | org.eclipse.cdt.managedbuilder.core.ScannerConfigNature 26 | 27 | 28 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.settings/language.settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.settings/org.eclipse.cdt.core.prefs: -------------------------------------------------------------------------------- 1 | eclipse.preferences.version=1 2 | environment/project/0.910961921/PATH/delimiter=\: 3 | environment/project/0.910961921/PATH/operation=replace 4 | environment/project/0.910961921/PATH/value=/Library/Frameworks/Python.framework/Versions/3.5/bin\:/Library/Frameworks/Python.framework/Versions/2.7/bin\:/opt/local/bin\:/opt/local/sbin\:/usr/local/bin\:/usr/bin\:/bin\:/usr/sbin\:/sbin 5 | environment/project/0.910961921/append=true 6 | environment/project/0.910961921/appendContributed=true -------------------------------------------------------------------------------- /examples/nodemcu_rfid/.travis.yml: -------------------------------------------------------------------------------- 1 | # Continuous Integration (CI) is the practice, in software 2 | # engineering, of merging all developer working copies with a shared mainline 3 | # several times a day < http://docs.platformio.org/en/latest/ci/index.html > 4 | # 5 | # Documentation: 6 | # 7 | # * Travis CI Embedded Builds with PlatformIO 8 | # < https://docs.travis-ci.com/user/integration/platformio/ > 9 | # 10 | # * PlatformIO integration with Travis CI 11 | # < http://docs.platformio.org/en/latest/ci/travis.html > 12 | # 13 | # * User Guide for `platformio ci` command 14 | # < http://docs.platformio.org/en/latest/userguide/cmd_ci.html > 15 | # 16 | # 17 | # Please choice one of the following templates (proposed below) and uncomment 18 | # it (remove "# " before each line) or use own configuration according to the 19 | # Travis CI documentation (see above). 20 | # 21 | 22 | 23 | # 24 | # Template #1: General project. Test it using existing `platformio.ini`. 25 | # 26 | 27 | # language: python 28 | # python: 29 | # - "2.7" 30 | # 31 | # sudo: false 32 | # cache: 33 | # directories: 34 | # - "~/.platformio" 35 | # 36 | # install: 37 | # - pip install -U platformio 38 | # 39 | # script: 40 | # - platformio run 41 | 42 | 43 | # 44 | # Template #2: The project is intended to by used as a library with examples 45 | # 46 | 47 | # language: python 48 | # python: 49 | # - "2.7" 50 | # 51 | # sudo: false 52 | # cache: 53 | # directories: 54 | # - "~/.platformio" 55 | # 56 | # env: 57 | # - PLATFORMIO_CI_SRC=path/to/test/file.c 58 | # - PLATFORMIO_CI_SRC=examples/file.ino 59 | # - PLATFORMIO_CI_SRC=path/to/test/directory 60 | # 61 | # install: 62 | # - pip install -U platformio 63 | # 64 | # script: 65 | # - platformio ci --lib="." --board=TYPE_1 --board=TYPE_2 --board=TYPE_N 66 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/lib/MFRC522_I2C/MFRC522_I2C.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * MFRC522.cpp - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522.cpp - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * NOTE: Please also check the comments in MFRC522.h - they provide useful hints and background information. 5 | * Released into the public domain. 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | ///////////////////////////////////////////////////////////////////////////////////// 13 | // Functions for setting up the Arduino 14 | ///////////////////////////////////////////////////////////////////////////////////// 15 | 16 | /** 17 | * Constructor. 18 | * Prepares the output pins. 19 | */ 20 | MFRC522::MFRC522( byte chipAddress, 21 | byte resetPowerDownPin ///< Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 22 | ) { 23 | _chipAddress = chipAddress; 24 | _resetPowerDownPin = resetPowerDownPin; 25 | } // End constructor 26 | 27 | 28 | ///////////////////////////////////////////////////////////////////////////////////// 29 | // Basic interface functions for communicating with the MFRC522 30 | ///////////////////////////////////////////////////////////////////////////////////// 31 | 32 | /** 33 | * Writes a byte to the specified register in the MFRC522 chip. 34 | * The interface is described in the datasheet section 8.1.2. 35 | */ 36 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 37 | byte value ///< The value to write. 38 | ) { 39 | Wire.beginTransmission(_chipAddress); 40 | Wire.write(reg); 41 | Wire.write(value); 42 | Wire.endTransmission(); 43 | } // End PCD_WriteRegister() 44 | 45 | /** 46 | * Writes a number of bytes to the specified register in the MFRC522 chip. 47 | * The interface is described in the datasheet section 8.1.2. 48 | */ 49 | void MFRC522::PCD_WriteRegister( byte reg, ///< The register to write to. One of the PCD_Register enums. 50 | byte count, ///< The number of bytes to write to the register 51 | byte *values ///< The values to write. Byte array. 52 | ) { 53 | Wire.beginTransmission(_chipAddress); 54 | Wire.write(reg); 55 | for (byte index = 0; index < count; index++) { 56 | Wire.write(values[index]); 57 | } 58 | Wire.endTransmission(); 59 | } // End PCD_WriteRegister() 60 | 61 | /** 62 | * Reads a byte from the specified register in the MFRC522 chip. 63 | * The interface is described in the datasheet section 8.1.2. 64 | */ 65 | byte MFRC522::PCD_ReadRegister( byte reg ///< The register to read from. One of the PCD_Register enums. 66 | ) { 67 | byte value; 68 | //digitalWrite(_chipSelectPin, LOW); // Select slave 69 | Wire.beginTransmission(_chipAddress); 70 | Wire.write(reg); 71 | Wire.endTransmission(); 72 | 73 | Wire.requestFrom(_chipAddress, 1); 74 | value = Wire.read(); 75 | return value; 76 | } // End PCD_ReadRegister() 77 | 78 | /** 79 | * Reads a number of bytes from the specified register in the MFRC522 chip. 80 | * The interface is described in the datasheet section 8.1.2. 81 | */ 82 | void MFRC522::PCD_ReadRegister( byte reg, ///< The register to read from. One of the PCD_Register enums. 83 | byte count, ///< The number of bytes to read 84 | byte *values, ///< Byte array to store the values in. 85 | byte rxAlign ///< Only bit positions rxAlign..7 in values[0] are updated. 86 | ) { 87 | if (count == 0) { 88 | return; 89 | } 90 | byte address = reg; 91 | byte index = 0; // Index in values array. 92 | Wire.beginTransmission(_chipAddress); 93 | Wire.write(address); 94 | Wire.endTransmission(); 95 | Wire.requestFrom(_chipAddress, count); 96 | while (Wire.available()) { 97 | if (index == 0 && rxAlign) { // Only update bit positions rxAlign..7 in values[0] 98 | // Create bit mask for bit positions rxAlign..7 99 | byte mask = 0; 100 | for (byte i = rxAlign; i <= 7; i++) { 101 | mask |= (1 << i); 102 | } 103 | // Read value and tell that we want to read the same address again. 104 | byte value = Wire.read(); 105 | // Apply mask to both current value of values[0] and the new data in value. 106 | values[0] = (values[index] & ~mask) | (value & mask); 107 | } 108 | else { // Normal case 109 | values[index] = Wire.read(); 110 | } 111 | index++; 112 | } 113 | } // End PCD_ReadRegister() 114 | 115 | /** 116 | * Sets the bits given in mask in register reg. 117 | */ 118 | void MFRC522::PCD_SetRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 119 | byte mask ///< The bits to set. 120 | ) { 121 | byte tmp; 122 | tmp = PCD_ReadRegister(reg); 123 | PCD_WriteRegister(reg, tmp | mask); // set bit mask 124 | } // End PCD_SetRegisterBitMask() 125 | 126 | /** 127 | * Clears the bits given in mask from register reg. 128 | */ 129 | void MFRC522::PCD_ClearRegisterBitMask( byte reg, ///< The register to update. One of the PCD_Register enums. 130 | byte mask ///< The bits to clear. 131 | ) { 132 | byte tmp; 133 | tmp = PCD_ReadRegister(reg); 134 | PCD_WriteRegister(reg, tmp & (~mask)); // clear bit mask 135 | } // End PCD_ClearRegisterBitMask() 136 | 137 | 138 | /** 139 | * Use the CRC coprocessor in the MFRC522 to calculate a CRC_A. 140 | * 141 | * @return STATUS_OK on success, STATUS_??? otherwise. 142 | */ 143 | byte MFRC522::PCD_CalculateCRC( byte *data, ///< In: Pointer to the data to transfer to the FIFO for CRC calculation. 144 | byte length, ///< In: The number of bytes to transfer. 145 | byte *result ///< Out: Pointer to result buffer. Result is written to result[0..1], low byte first. 146 | ) { 147 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 148 | PCD_WriteRegister(DivIrqReg, 0x04); // Clear the CRCIRq interrupt request bit 149 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 150 | PCD_WriteRegister(FIFODataReg, length, data); // Write data to the FIFO 151 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); // Start the calculation 152 | 153 | // Wait for the CRC calculation to complete. Each iteration of the while-loop takes 17.73�s. 154 | word i = 5000; 155 | byte n; 156 | while (1) { 157 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 158 | if (n & 0x04) { // CRCIRq bit set - calculation done 159 | break; 160 | } 161 | if (--i == 0) { // The emergency break. We will eventually terminate on this one after 89ms. Communication with the MFRC522 might be down. 162 | return STATUS_TIMEOUT; 163 | } 164 | } 165 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 166 | 167 | // Transfer the result from the registers to the result buffer 168 | result[0] = PCD_ReadRegister(CRCResultRegL); 169 | result[1] = PCD_ReadRegister(CRCResultRegH); 170 | return STATUS_OK; 171 | } // End PCD_CalculateCRC() 172 | 173 | 174 | ///////////////////////////////////////////////////////////////////////////////////// 175 | // Functions for manipulating the MFRC522 176 | ///////////////////////////////////////////////////////////////////////////////////// 177 | 178 | /** 179 | * Initializes the MFRC522 chip. 180 | */ 181 | void MFRC522::PCD_Init() { 182 | // Set the chipSelectPin as digital output, do not select the slave yet 183 | 184 | // Set the resetPowerDownPin as digital output, do not reset or power down. 185 | pinMode(_resetPowerDownPin, OUTPUT); 186 | 187 | 188 | if (digitalRead(_resetPowerDownPin) == LOW) { //The MFRC522 chip is in power down mode. 189 | digitalWrite(_resetPowerDownPin, HIGH); // Exit power down mode. This triggers a hard reset. 190 | // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 191 | delay(50); 192 | } 193 | else { // Perform a soft reset 194 | PCD_Reset(); 195 | } 196 | 197 | // When communicating with a PICC we need a timeout if something goes wrong. 198 | // f_timer = 13.56 MHz / (2*TPreScaler+1) where TPreScaler = [TPrescaler_Hi:TPrescaler_Lo]. 199 | // TPrescaler_Hi are the four low bits in TModeReg. TPrescaler_Lo is TPrescalerReg. 200 | PCD_WriteRegister(TModeReg, 0x80); // TAuto=1; timer starts automatically at the end of the transmission in all communication modes at all speeds 201 | PCD_WriteRegister(TPrescalerReg, 0xA9); // TPreScaler = TModeReg[3..0]:TPrescalerReg, ie 0x0A9 = 169 => f_timer=40kHz, ie a timer period of 25�s. 202 | PCD_WriteRegister(TReloadRegH, 0x03); // Reload timer with 0x3E8 = 1000, ie 25ms before timeout. 203 | PCD_WriteRegister(TReloadRegL, 0xE8); 204 | 205 | PCD_WriteRegister(TxASKReg, 0x40); // Default 0x00. Force a 100 % ASK modulation independent of the ModGsPReg register setting 206 | PCD_WriteRegister(ModeReg, 0x3D); // Default 0x3F. Set the preset value for the CRC coprocessor for the CalcCRC command to 0x6363 (ISO 14443-3 part 6.2.4) 207 | PCD_AntennaOn(); // Enable the antenna driver pins TX1 and TX2 (they were disabled by the reset) 208 | } // End PCD_Init() 209 | 210 | /** 211 | * Performs a soft reset on the MFRC522 chip and waits for it to be ready again. 212 | */ 213 | void MFRC522::PCD_Reset() { 214 | PCD_WriteRegister(CommandReg, PCD_SoftReset); // Issue the SoftReset command. 215 | // The datasheet does not mention how long the SoftRest command takes to complete. 216 | // But the MFRC522 might have been in soft power-down mode (triggered by bit 4 of CommandReg) 217 | // Section 8.8.2 in the datasheet says the oscillator start-up time is the start up time of the crystal + 37,74�s. Let us be generous: 50ms. 218 | delay(50); 219 | // Wait for the PowerDown bit in CommandReg to be cleared 220 | while (PCD_ReadRegister(CommandReg) & (1<<4)) { 221 | // PCD still restarting - unlikely after waiting 50ms, but better safe than sorry. 222 | } 223 | } // End PCD_Reset() 224 | 225 | /** 226 | * Turns the antenna on by enabling pins TX1 and TX2. 227 | * After a reset these pins are disabled. 228 | */ 229 | void MFRC522::PCD_AntennaOn() { 230 | byte value = PCD_ReadRegister(TxControlReg); 231 | if ((value & 0x03) != 0x03) { 232 | PCD_WriteRegister(TxControlReg, value | 0x03); 233 | } 234 | } // End PCD_AntennaOn() 235 | 236 | /** 237 | * Turns the antenna off by disabling pins TX1 and TX2. 238 | */ 239 | void MFRC522::PCD_AntennaOff() { 240 | PCD_ClearRegisterBitMask(TxControlReg, 0x03); 241 | } // End PCD_AntennaOff() 242 | 243 | /** 244 | * Get the current MFRC522 Receiver Gain (RxGain[2:0]) value. 245 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 246 | * NOTE: Return value scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 247 | * 248 | * @return Value of the RxGain, scrubbed to the 3 bits used. 249 | */ 250 | byte MFRC522::PCD_GetAntennaGain() { 251 | return PCD_ReadRegister(RFCfgReg) & (0x07<<4); 252 | } // End PCD_GetAntennaGain() 253 | 254 | /** 255 | * Set the MFRC522 Receiver Gain (RxGain) to value specified by given mask. 256 | * See 9.3.3.6 / table 98 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 257 | * NOTE: Given mask is scrubbed with (0x07<<4)=01110000b as RCFfgReg may use reserved bits. 258 | */ 259 | void MFRC522::PCD_SetAntennaGain(byte mask) { 260 | if (PCD_GetAntennaGain() != mask) { // only bother if there is a change 261 | PCD_ClearRegisterBitMask(RFCfgReg, (0x07<<4)); // clear needed to allow 000 pattern 262 | PCD_SetRegisterBitMask(RFCfgReg, mask & (0x07<<4)); // only set RxGain[2:0] bits 263 | } 264 | } // End PCD_SetAntennaGain() 265 | 266 | /** 267 | * Performs a self-test of the MFRC522 268 | * See 16.1.1 in http://www.nxp.com/documents/data_sheet/MFRC522.pdf 269 | * 270 | * @return Whether or not the test passed. 271 | */ 272 | bool MFRC522::PCD_PerformSelfTest() { 273 | // This follows directly the steps outlined in 16.1.1 274 | // 1. Perform a soft reset. 275 | PCD_Reset(); 276 | 277 | // 2. Clear the internal buffer by writing 25 bytes of 00h 278 | byte ZEROES[25] = {0x00}; 279 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // flush the FIFO buffer 280 | PCD_WriteRegister(FIFODataReg, 25, ZEROES); // write 25 bytes of 00h to FIFO 281 | PCD_WriteRegister(CommandReg, PCD_Mem); // transfer to internal buffer 282 | 283 | // 3. Enable self-test 284 | PCD_WriteRegister(AutoTestReg, 0x09); 285 | 286 | // 4. Write 00h to FIFO buffer 287 | PCD_WriteRegister(FIFODataReg, 0x00); 288 | 289 | // 5. Start self-test by issuing the CalcCRC command 290 | PCD_WriteRegister(CommandReg, PCD_CalcCRC); 291 | 292 | // 6. Wait for self-test to complete 293 | word i; 294 | byte n; 295 | for (i = 0; i < 0xFF; i++) { 296 | n = PCD_ReadRegister(DivIrqReg); // DivIrqReg[7..0] bits are: Set2 reserved reserved MfinActIRq reserved CRCIRq reserved reserved 297 | if (n & 0x04) { // CRCIRq bit set - calculation done 298 | break; 299 | } 300 | } 301 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop calculating CRC for new content in the FIFO. 302 | 303 | // 7. Read out resulting 64 bytes from the FIFO buffer. 304 | byte result[64]; 305 | PCD_ReadRegister(FIFODataReg, 64, result, 0); 306 | 307 | // Auto self-test done 308 | // Reset AutoTestReg register to be 0 again. Required for normal operation. 309 | PCD_WriteRegister(AutoTestReg, 0x00); 310 | 311 | // Determine firmware version (see section 9.3.4.8 in spec) 312 | byte version = PCD_ReadRegister(VersionReg); 313 | 314 | // Pick the appropriate reference values 315 | const byte *reference; 316 | switch (version) { 317 | case 0x88: // Fudan Semiconductor FM17522 clone 318 | reference = FM17522_firmware_reference; 319 | break; 320 | case 0x90: // Version 0.0 321 | reference = MFRC522_firmware_referenceV0_0; 322 | break; 323 | case 0x91: // Version 1.0 324 | reference = MFRC522_firmware_referenceV1_0; 325 | break; 326 | case 0x92: // Version 2.0 327 | reference = MFRC522_firmware_referenceV2_0; 328 | break; 329 | default: // Unknown version 330 | return false; 331 | } 332 | 333 | // Verify that the results match up to our expectations 334 | for (i = 0; i < 64; i++) { 335 | if (result[i] != pgm_read_byte(&(reference[i]))) { 336 | return false; 337 | } 338 | } 339 | 340 | // Test passed; all is good. 341 | return true; 342 | } // End PCD_PerformSelfTest() 343 | 344 | ///////////////////////////////////////////////////////////////////////////////////// 345 | // Functions for communicating with PICCs 346 | ///////////////////////////////////////////////////////////////////////////////////// 347 | 348 | /** 349 | * Executes the Transceive command. 350 | * CRC validation can only be done if backData and backLen are specified. 351 | * 352 | * @return STATUS_OK on success, STATUS_??? otherwise. 353 | */ 354 | byte MFRC522::PCD_TransceiveData( byte *sendData, ///< Pointer to the data to transfer to the FIFO. 355 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 356 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 357 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 358 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. Default NULL. 359 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 360 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 361 | ) { 362 | byte waitIRq = 0x30; // RxIRq and IdleIRq 363 | return PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, sendData, sendLen, backData, backLen, validBits, rxAlign, checkCRC); 364 | } // End PCD_TransceiveData() 365 | 366 | /** 367 | * Transfers data to the MFRC522 FIFO, executes a command, waits for completion and transfers data back from the FIFO. 368 | * CRC validation can only be done if backData and backLen are specified. 369 | * 370 | * @return STATUS_OK on success, STATUS_??? otherwise. 371 | */ 372 | byte MFRC522::PCD_CommunicateWithPICC( byte command, ///< The command to execute. One of the PCD_Command enums. 373 | byte waitIRq, ///< The bits in the ComIrqReg register that signals successful completion of the command. 374 | byte *sendData, ///< Pointer to the data to transfer to the FIFO. 375 | byte sendLen, ///< Number of bytes to transfer to the FIFO. 376 | byte *backData, ///< NULL or pointer to buffer if data should be read back after executing the command. 377 | byte *backLen, ///< In: Max number of bytes to write to *backData. Out: The number of bytes returned. 378 | byte *validBits, ///< In/Out: The number of valid bits in the last byte. 0 for 8 valid bits. 379 | byte rxAlign, ///< In: Defines the bit position in backData[0] for the first bit received. Default 0. 380 | bool checkCRC ///< In: True => The last two bytes of the response is assumed to be a CRC_A that must be validated. 381 | ) { 382 | byte n, _validBits; 383 | unsigned int i; 384 | 385 | // Prepare values for BitFramingReg 386 | byte txLastBits = validBits ? *validBits : 0; 387 | byte bitFraming = (rxAlign << 4) + txLastBits; // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 388 | 389 | PCD_WriteRegister(CommandReg, PCD_Idle); // Stop any active command. 390 | PCD_WriteRegister(ComIrqReg, 0x7F); // Clear all seven interrupt request bits 391 | PCD_SetRegisterBitMask(FIFOLevelReg, 0x80); // FlushBuffer = 1, FIFO initialization 392 | PCD_WriteRegister(FIFODataReg, sendLen, sendData); // Write sendData to the FIFO 393 | PCD_WriteRegister(BitFramingReg, bitFraming); // Bit adjustments 394 | PCD_WriteRegister(CommandReg, command); // Execute the command 395 | if (command == PCD_Transceive) { 396 | PCD_SetRegisterBitMask(BitFramingReg, 0x80); // StartSend=1, transmission of data starts 397 | } 398 | 399 | // Wait for the command to complete. 400 | // In PCD_Init() we set the TAuto flag in TModeReg. This means the timer automatically starts when the PCD stops transmitting. 401 | // Each iteration of the do-while-loop takes 17.86�s. 402 | i = 2000; 403 | while (1) { 404 | n = PCD_ReadRegister(ComIrqReg); // ComIrqReg[7..0] bits are: Set1 TxIRq RxIRq IdleIRq HiAlertIRq LoAlertIRq ErrIRq TimerIRq 405 | if (n & waitIRq) { // One of the interrupts that signal success has been set. 406 | break; 407 | } 408 | if (n & 0x01) { // Timer interrupt - nothing received in 25ms 409 | return STATUS_TIMEOUT; 410 | } 411 | if (--i == 0) { // The emergency break. If all other condions fail we will eventually terminate on this one after 35.7ms. Communication with the MFRC522 might be down. 412 | return STATUS_TIMEOUT; 413 | } 414 | } 415 | 416 | // Stop now if any errors except collisions were detected. 417 | byte errorRegValue = PCD_ReadRegister(ErrorReg); // ErrorReg[7..0] bits are: WrErr TempErr reserved BufferOvfl CollErr CRCErr ParityErr ProtocolErr 418 | if (errorRegValue & 0x13) { // BufferOvfl ParityErr ProtocolErr 419 | return STATUS_ERROR; 420 | } 421 | 422 | // If the caller wants data back, get it from the MFRC522. 423 | if (backData && backLen) { 424 | n = PCD_ReadRegister(FIFOLevelReg); // Number of bytes in the FIFO 425 | if (n > *backLen) { 426 | return STATUS_NO_ROOM; 427 | } 428 | *backLen = n; // Number of bytes returned 429 | PCD_ReadRegister(FIFODataReg, n, backData, rxAlign); // Get received data from FIFO 430 | _validBits = PCD_ReadRegister(ControlReg) & 0x07; // RxLastBits[2:0] indicates the number of valid bits in the last received byte. If this value is 000b, the whole byte is valid. 431 | if (validBits) { 432 | *validBits = _validBits; 433 | } 434 | } 435 | 436 | // Tell about collisions 437 | if (errorRegValue & 0x08) { // CollErr 438 | return STATUS_COLLISION; 439 | } 440 | 441 | // Perform CRC_A validation if requested. 442 | if (backData && backLen && checkCRC) { 443 | // In this case a MIFARE Classic NAK is not OK. 444 | if (*backLen == 1 && _validBits == 4) { 445 | return STATUS_MIFARE_NACK; 446 | } 447 | // We need at least the CRC_A value and all 8 bits of the last byte must be received. 448 | if (*backLen < 2 || _validBits != 0) { 449 | return STATUS_CRC_WRONG; 450 | } 451 | // Verify CRC_A - do our own calculation and store the control in controlBuffer. 452 | byte controlBuffer[2]; 453 | n = PCD_CalculateCRC(&backData[0], *backLen - 2, &controlBuffer[0]); 454 | if (n != STATUS_OK) { 455 | return n; 456 | } 457 | if ((backData[*backLen - 2] != controlBuffer[0]) || (backData[*backLen - 1] != controlBuffer[1])) { 458 | return STATUS_CRC_WRONG; 459 | } 460 | } 461 | 462 | return STATUS_OK; 463 | } // End PCD_CommunicateWithPICC() 464 | 465 | /** 466 | * Transmits a REQuest command, Type A. Invites PICCs in state IDLE to go to READY and prepare for anticollision or selection. 7 bit frame. 467 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 468 | * 469 | * @return STATUS_OK on success, STATUS_??? otherwise. 470 | */ 471 | byte MFRC522::PICC_RequestA(byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 472 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 473 | ) { 474 | return PICC_REQA_or_WUPA(PICC_CMD_REQA, bufferATQA, bufferSize); 475 | } // End PICC_RequestA() 476 | 477 | /** 478 | * 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. 479 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 480 | * 481 | * @return STATUS_OK on success, STATUS_??? otherwise. 482 | */ 483 | byte MFRC522::PICC_WakeupA( byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 484 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 485 | ) { 486 | return PICC_REQA_or_WUPA(PICC_CMD_WUPA, bufferATQA, bufferSize); 487 | } // End PICC_WakeupA() 488 | 489 | /** 490 | * Transmits REQA or WUPA commands. 491 | * Beware: When two PICCs are in the field at the same time I often get STATUS_TIMEOUT - probably due do bad antenna design. 492 | * 493 | * @return STATUS_OK on success, STATUS_??? otherwise. 494 | */ 495 | byte MFRC522::PICC_REQA_or_WUPA( byte command, ///< The command to send - PICC_CMD_REQA or PICC_CMD_WUPA 496 | byte *bufferATQA, ///< The buffer to store the ATQA (Answer to request) in 497 | byte *bufferSize ///< Buffer size, at least two bytes. Also number of bytes returned if STATUS_OK. 498 | ) { 499 | byte validBits; 500 | byte status; 501 | 502 | if (bufferATQA == NULL || *bufferSize < 2) { // The ATQA response is 2 bytes long. 503 | return STATUS_NO_ROOM; 504 | } 505 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 506 | validBits = 7; // For REQA and WUPA we need the short frame format - transmit only 7 bits of the last (and only) byte. TxLastBits = BitFramingReg[2..0] 507 | status = PCD_TransceiveData(&command, 1, bufferATQA, bufferSize, &validBits); 508 | if (status != STATUS_OK) { 509 | return status; 510 | } 511 | if (*bufferSize != 2 || validBits != 0) { // ATQA must be exactly 16 bits. 512 | return STATUS_ERROR; 513 | } 514 | return STATUS_OK; 515 | } // End PICC_REQA_or_WUPA() 516 | 517 | /** 518 | * Transmits SELECT/ANTICOLLISION commands to select a single PICC. 519 | * Before calling this function the PICCs must be placed in the READY(*) state by calling PICC_RequestA() or PICC_WakeupA(). 520 | * On success: 521 | * - 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.) 522 | * - The UID size and value of the chosen PICC is returned in *uid along with the SAK. 523 | * 524 | * A PICC UID consists of 4, 7 or 10 bytes. 525 | * Only 4 bytes can be specified in a SELECT command, so for the longer UIDs two or three iterations are used: 526 | * UID size Number of UID bytes Cascade levels Example of PICC 527 | * ======== =================== ============== =============== 528 | * single 4 1 MIFARE Classic 529 | * double 7 2 MIFARE Ultralight 530 | * triple 10 3 Not currently in use? 531 | * 532 | * @return STATUS_OK on success, STATUS_??? otherwise. 533 | */ 534 | byte MFRC522::PICC_Select( Uid *uid, ///< Pointer to Uid struct. Normally output, but can also be used to supply a known UID. 535 | byte validBits ///< The number of known UID bits supplied in *uid. Normally 0. If set you must also supply uid->size. 536 | ) { 537 | bool uidComplete; 538 | bool selectDone; 539 | bool useCascadeTag; 540 | byte cascadeLevel = 1; 541 | byte result; 542 | byte count; 543 | byte index; 544 | byte uidIndex; // The first index in uid->uidByte[] that is used in the current Cascade Level. 545 | int8_t currentLevelKnownBits; // The number of known UID bits in the current Cascade Level. 546 | byte buffer[9]; // The SELECT/ANTICOLLISION commands uses a 7 byte standard frame + 2 bytes CRC_A 547 | byte bufferUsed; // The number of bytes used in the buffer, ie the number of bytes to transfer to the FIFO. 548 | byte rxAlign; // Used in BitFramingReg. Defines the bit position for the first bit received. 549 | byte txLastBits; // Used in BitFramingReg. The number of valid bits in the last transmitted byte. 550 | byte *responseBuffer; 551 | byte responseLength; 552 | 553 | // Description of buffer structure: 554 | // Byte 0: SEL Indicates the Cascade Level: PICC_CMD_SEL_CL1, PICC_CMD_SEL_CL2 or PICC_CMD_SEL_CL3 555 | // Byte 1: NVB Number of Valid Bits (in complete command, not just the UID): High nibble: complete bytes, Low nibble: Extra bits. 556 | // Byte 2: UID-data or CT See explanation below. CT means Cascade Tag. 557 | // Byte 3: UID-data 558 | // Byte 4: UID-data 559 | // Byte 5: UID-data 560 | // Byte 6: BCC Block Check Character - XOR of bytes 2-5 561 | // Byte 7: CRC_A 562 | // Byte 8: CRC_A 563 | // The BCC and CRC_A is only transmitted if we know all the UID bits of the current Cascade Level. 564 | // 565 | // Description of bytes 2-5: (Section 6.5.4 of the ISO/IEC 14443-3 draft: UID contents and cascade levels) 566 | // UID size Cascade level Byte2 Byte3 Byte4 Byte5 567 | // ======== ============= ===== ===== ===== ===== 568 | // 4 bytes 1 uid0 uid1 uid2 uid3 569 | // 7 bytes 1 CT uid0 uid1 uid2 570 | // 2 uid3 uid4 uid5 uid6 571 | // 10 bytes 1 CT uid0 uid1 uid2 572 | // 2 CT uid3 uid4 uid5 573 | // 3 uid6 uid7 uid8 uid9 574 | 575 | // Sanity checks 576 | if (validBits > 80) { 577 | return STATUS_INVALID; 578 | } 579 | 580 | // Prepare MFRC522 581 | PCD_ClearRegisterBitMask(CollReg, 0x80); // ValuesAfterColl=1 => Bits received after collision are cleared. 582 | 583 | // Repeat Cascade Level loop until we have a complete UID. 584 | uidComplete = false; 585 | while (!uidComplete) { 586 | // Set the Cascade Level in the SEL byte, find out if we need to use the Cascade Tag in byte 2. 587 | switch (cascadeLevel) { 588 | case 1: 589 | buffer[0] = PICC_CMD_SEL_CL1; 590 | uidIndex = 0; 591 | useCascadeTag = validBits && uid->size > 4; // When we know that the UID has more than 4 bytes 592 | break; 593 | 594 | case 2: 595 | buffer[0] = PICC_CMD_SEL_CL2; 596 | uidIndex = 3; 597 | useCascadeTag = validBits && uid->size > 7; // When we know that the UID has more than 7 bytes 598 | break; 599 | 600 | case 3: 601 | buffer[0] = PICC_CMD_SEL_CL3; 602 | uidIndex = 6; 603 | useCascadeTag = false; // Never used in CL3. 604 | break; 605 | 606 | default: 607 | return STATUS_INTERNAL_ERROR; 608 | break; 609 | } 610 | 611 | // How many UID bits are known in this Cascade Level? 612 | currentLevelKnownBits = validBits - (8 * uidIndex); 613 | if (currentLevelKnownBits < 0) { 614 | currentLevelKnownBits = 0; 615 | } 616 | // Copy the known bits from uid->uidByte[] to buffer[] 617 | index = 2; // destination index in buffer[] 618 | if (useCascadeTag) { 619 | buffer[index++] = PICC_CMD_CT; 620 | } 621 | byte bytesToCopy = currentLevelKnownBits / 8 + (currentLevelKnownBits % 8 ? 1 : 0); // The number of bytes needed to represent the known bits for this level. 622 | if (bytesToCopy) { 623 | byte maxBytes = useCascadeTag ? 3 : 4; // Max 4 bytes in each Cascade Level. Only 3 left if we use the Cascade Tag 624 | if (bytesToCopy > maxBytes) { 625 | bytesToCopy = maxBytes; 626 | } 627 | for (count = 0; count < bytesToCopy; count++) { 628 | buffer[index++] = uid->uidByte[uidIndex + count]; 629 | } 630 | } 631 | // Now that the data has been copied we need to include the 8 bits in CT in currentLevelKnownBits 632 | if (useCascadeTag) { 633 | currentLevelKnownBits += 8; 634 | } 635 | 636 | // Repeat anti collision loop until we can transmit all UID bits + BCC and receive a SAK - max 32 iterations. 637 | selectDone = false; 638 | while (!selectDone) { 639 | // Find out how many bits and bytes to send and receive. 640 | if (currentLevelKnownBits >= 32) { // All UID bits in this Cascade Level are known. This is a SELECT. 641 | //Serial.print(F("SELECT: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 642 | buffer[1] = 0x70; // NVB - Number of Valid Bits: Seven whole bytes 643 | // Calculate BCC - Block Check Character 644 | buffer[6] = buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5]; 645 | // Calculate CRC_A 646 | result = PCD_CalculateCRC(buffer, 7, &buffer[7]); 647 | if (result != STATUS_OK) { 648 | return result; 649 | } 650 | txLastBits = 0; // 0 => All 8 bits are valid. 651 | bufferUsed = 9; 652 | // Store response in the last 3 bytes of buffer (BCC and CRC_A - not needed after tx) 653 | responseBuffer = &buffer[6]; 654 | responseLength = 3; 655 | } 656 | else { // This is an ANTICOLLISION. 657 | //Serial.print(F("ANTICOLLISION: currentLevelKnownBits=")); Serial.println(currentLevelKnownBits, DEC); 658 | txLastBits = currentLevelKnownBits % 8; 659 | count = currentLevelKnownBits / 8; // Number of whole bytes in the UID part. 660 | index = 2 + count; // Number of whole bytes: SEL + NVB + UIDs 661 | buffer[1] = (index << 4) + txLastBits; // NVB - Number of Valid Bits 662 | bufferUsed = index + (txLastBits ? 1 : 0); 663 | // Store response in the unused part of buffer 664 | responseBuffer = &buffer[index]; 665 | responseLength = sizeof(buffer) - index; 666 | } 667 | 668 | // Set bit adjustments 669 | rxAlign = txLastBits; // Having a seperate variable is overkill. But it makes the next line easier to read. 670 | PCD_WriteRegister(BitFramingReg, (rxAlign << 4) + txLastBits); // RxAlign = BitFramingReg[6..4]. TxLastBits = BitFramingReg[2..0] 671 | 672 | // Transmit the buffer and receive the response. 673 | result = PCD_TransceiveData(buffer, bufferUsed, responseBuffer, &responseLength, &txLastBits, rxAlign); 674 | if (result == STATUS_COLLISION) { // More than one PICC in the field => collision. 675 | result = PCD_ReadRegister(CollReg); // CollReg[7..0] bits are: ValuesAfterColl reserved CollPosNotValid CollPos[4:0] 676 | if (result & 0x20) { // CollPosNotValid 677 | return STATUS_COLLISION; // Without a valid collision position we cannot continue 678 | } 679 | byte collisionPos = result & 0x1F; // Values 0-31, 0 means bit 32. 680 | if (collisionPos == 0) { 681 | collisionPos = 32; 682 | } 683 | if (collisionPos <= currentLevelKnownBits) { // No progress - should not happen 684 | return STATUS_INTERNAL_ERROR; 685 | } 686 | // Choose the PICC with the bit set. 687 | currentLevelKnownBits = collisionPos; 688 | count = (currentLevelKnownBits - 1) % 8; // The bit to modify 689 | index = 1 + (currentLevelKnownBits / 8) + (count ? 1 : 0); // First byte is index 0. 690 | buffer[index] |= (1 << count); 691 | } 692 | else if (result != STATUS_OK) { 693 | return result; 694 | } 695 | else { // STATUS_OK 696 | if (currentLevelKnownBits >= 32) { // This was a SELECT. 697 | selectDone = true; // No more anticollision 698 | // We continue below outside the while. 699 | } 700 | else { // This was an ANTICOLLISION. 701 | // We now have all 32 bits of the UID in this Cascade Level 702 | currentLevelKnownBits = 32; 703 | // Run loop again to do the SELECT. 704 | } 705 | } 706 | } // End of while (!selectDone) 707 | 708 | // We do not check the CBB - it was constructed by us above. 709 | 710 | // Copy the found UID bytes from buffer[] to uid->uidByte[] 711 | index = (buffer[2] == PICC_CMD_CT) ? 3 : 2; // source index in buffer[] 712 | bytesToCopy = (buffer[2] == PICC_CMD_CT) ? 3 : 4; 713 | for (count = 0; count < bytesToCopy; count++) { 714 | uid->uidByte[uidIndex + count] = buffer[index++]; 715 | } 716 | 717 | // Check response SAK (Select Acknowledge) 718 | if (responseLength != 3 || txLastBits != 0) { // SAK must be exactly 24 bits (1 byte + CRC_A). 719 | return STATUS_ERROR; 720 | } 721 | // Verify CRC_A - do our own calculation and store the control in buffer[2..3] - those bytes are not needed anymore. 722 | result = PCD_CalculateCRC(responseBuffer, 1, &buffer[2]); 723 | if (result != STATUS_OK) { 724 | return result; 725 | } 726 | if ((buffer[2] != responseBuffer[1]) || (buffer[3] != responseBuffer[2])) { 727 | return STATUS_CRC_WRONG; 728 | } 729 | if (responseBuffer[0] & 0x04) { // Cascade bit set - UID not complete yes 730 | cascadeLevel++; 731 | } 732 | else { 733 | uidComplete = true; 734 | uid->sak = responseBuffer[0]; 735 | } 736 | } // End of while (!uidComplete) 737 | 738 | // Set correct uid->size 739 | uid->size = 3 * cascadeLevel + 1; 740 | 741 | return STATUS_OK; 742 | } // End PICC_Select() 743 | 744 | /** 745 | * Instructs a PICC in state ACTIVE(*) to go to state HALT. 746 | * 747 | * @return STATUS_OK on success, STATUS_??? otherwise. 748 | */ 749 | byte MFRC522::PICC_HaltA() { 750 | byte result; 751 | byte buffer[4]; 752 | 753 | // Build command buffer 754 | buffer[0] = PICC_CMD_HLTA; 755 | buffer[1] = 0; 756 | // Calculate CRC_A 757 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 758 | if (result != STATUS_OK) { 759 | return result; 760 | } 761 | 762 | // Send the command. 763 | // The standard says: 764 | // If the PICC responds with any modulation during a period of 1 ms after the end of the frame containing the 765 | // HLTA command, this response shall be interpreted as 'not acknowledge'. 766 | // We interpret that this way: Only STATUS_TIMEOUT is an success. 767 | result = PCD_TransceiveData(buffer, sizeof(buffer), NULL, 0); 768 | if (result == STATUS_TIMEOUT) { 769 | return STATUS_OK; 770 | } 771 | if (result == STATUS_OK) { // That is ironically NOT ok in this case ;-) 772 | return STATUS_ERROR; 773 | } 774 | return result; 775 | } // End PICC_HaltA() 776 | 777 | 778 | ///////////////////////////////////////////////////////////////////////////////////// 779 | // Functions for communicating with MIFARE PICCs 780 | ///////////////////////////////////////////////////////////////////////////////////// 781 | 782 | /** 783 | * Executes the MFRC522 MFAuthent command. 784 | * This command manages MIFARE authentication to enable a secure communication to any MIFARE Mini, MIFARE 1K and MIFARE 4K card. 785 | * 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. 786 | * For use with MIFARE Classic PICCs. 787 | * The PICC must be selected - ie in state ACTIVE(*) - before calling this function. 788 | * Remember to call PCD_StopCrypto1() after communicating with the authenticated PICC - otherwise no new communications can start. 789 | * 790 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 791 | * 792 | * @return STATUS_OK on success, STATUS_??? otherwise. Probably STATUS_TIMEOUT if you supply the wrong key. 793 | */ 794 | byte MFRC522::PCD_Authenticate(byte command, ///< PICC_CMD_MF_AUTH_KEY_A or PICC_CMD_MF_AUTH_KEY_B 795 | byte blockAddr, ///< The block number. See numbering in the comments in the .h file. 796 | MIFARE_Key *key, ///< Pointer to the Crypteo1 key to use (6 bytes) 797 | Uid *uid ///< Pointer to Uid struct. The first 4 bytes of the UID is used. 798 | ) { 799 | byte waitIRq = 0x10; // IdleIRq 800 | 801 | // Build command buffer 802 | byte sendData[12]; 803 | sendData[0] = command; 804 | sendData[1] = blockAddr; 805 | for (byte i = 0; i < MF_KEY_SIZE; i++) { // 6 key bytes 806 | sendData[2+i] = key->keyByte[i]; 807 | } 808 | for (byte i = 0; i < 4; i++) { // The first 4 bytes of the UID 809 | sendData[8+i] = uid->uidByte[i]; 810 | } 811 | 812 | // Start the authentication. 813 | return PCD_CommunicateWithPICC(PCD_MFAuthent, waitIRq, &sendData[0], sizeof(sendData)); 814 | } // End PCD_Authenticate() 815 | 816 | /** 817 | * Used to exit the PCD from its authenticated state. 818 | * Remember to call this function after communicating with an authenticated PICC - otherwise no new communications can start. 819 | */ 820 | void MFRC522::PCD_StopCrypto1() { 821 | // Clear MFCrypto1On bit 822 | PCD_ClearRegisterBitMask(Status2Reg, 0x08); // Status2Reg[7..0] bits are: TempSensClear I2CForceHS reserved reserved MFCrypto1On ModemState[2:0] 823 | } // End PCD_StopCrypto1() 824 | 825 | /** 826 | * Reads 16 bytes (+ 2 bytes CRC_A) from the active PICC. 827 | * 828 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 829 | * 830 | * For MIFARE Ultralight only addresses 00h to 0Fh are decoded. 831 | * The MF0ICU1 returns a NAK for higher addresses. 832 | * The MF0ICU1 responds to the READ command by sending 16 bytes starting from the page address defined by the command argument. 833 | * For example; if blockAddr is 03h then pages 03h, 04h, 05h, 06h are returned. 834 | * A roll-back is implemented: If blockAddr is 0Eh, then the contents of pages 0Eh, 0Fh, 00h and 01h are returned. 835 | * 836 | * The buffer must be at least 18 bytes because a CRC_A is also returned. 837 | * Checks the CRC_A before returning STATUS_OK. 838 | * 839 | * @return STATUS_OK on success, STATUS_??? otherwise. 840 | */ 841 | byte MFRC522::MIFARE_Read( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The first page to return data from. 842 | byte *buffer, ///< The buffer to store the data in 843 | byte *bufferSize ///< Buffer size, at least 18 bytes. Also number of bytes returned if STATUS_OK. 844 | ) { 845 | byte result; 846 | 847 | // Sanity check 848 | if (buffer == NULL || *bufferSize < 18) { 849 | return STATUS_NO_ROOM; 850 | } 851 | 852 | // Build command buffer 853 | buffer[0] = PICC_CMD_MF_READ; 854 | buffer[1] = blockAddr; 855 | // Calculate CRC_A 856 | result = PCD_CalculateCRC(buffer, 2, &buffer[2]); 857 | if (result != STATUS_OK) { 858 | return result; 859 | } 860 | 861 | // Transmit the buffer and receive the response, validate CRC_A. 862 | return PCD_TransceiveData(buffer, 4, buffer, bufferSize, NULL, 0, true); 863 | } // End MIFARE_Read() 864 | 865 | /** 866 | * Writes 16 bytes to the active PICC. 867 | * 868 | * For MIFARE Classic the sector containing the block must be authenticated before calling this function. 869 | * 870 | * For MIFARE Ultralight the operation is called "COMPATIBILITY WRITE". 871 | * Even though 16 bytes are transferred to the Ultralight PICC, only the least significant 4 bytes (bytes 0 to 3) 872 | * are written to the specified address. It is recommended to set the remaining bytes 04h to 0Fh to all logic 0. 873 | * * 874 | * @return STATUS_OK on success, STATUS_??? otherwise. 875 | */ 876 | byte MFRC522::MIFARE_Write( byte blockAddr, ///< MIFARE Classic: The block (0-0xff) number. MIFARE Ultralight: The page (2-15) to write to. 877 | byte *buffer, ///< The 16 bytes to write to the PICC 878 | byte bufferSize ///< Buffer size, must be at least 16 bytes. Exactly 16 bytes are written. 879 | ) { 880 | byte result; 881 | 882 | // Sanity check 883 | if (buffer == NULL || bufferSize < 16) { 884 | return STATUS_INVALID; 885 | } 886 | 887 | // Mifare Classic protocol requires two communications to perform a write. 888 | // Step 1: Tell the PICC we want to write to block blockAddr. 889 | byte cmdBuffer[2]; 890 | cmdBuffer[0] = PICC_CMD_MF_WRITE; 891 | cmdBuffer[1] = blockAddr; 892 | result = PCD_MIFARE_Transceive(cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 893 | if (result != STATUS_OK) { 894 | return result; 895 | } 896 | 897 | // Step 2: Transfer the data 898 | result = PCD_MIFARE_Transceive(buffer, bufferSize); // Adds CRC_A and checks that the response is MF_ACK. 899 | if (result != STATUS_OK) { 900 | return result; 901 | } 902 | 903 | return STATUS_OK; 904 | } // End MIFARE_Write() 905 | 906 | /** 907 | * Writes a 4 byte page to the active MIFARE Ultralight PICC. 908 | * 909 | * @return STATUS_OK on success, STATUS_??? otherwise. 910 | */ 911 | byte MFRC522::MIFARE_Ultralight_Write( byte page, ///< The page (2-15) to write to. 912 | byte *buffer, ///< The 4 bytes to write to the PICC 913 | byte bufferSize ///< Buffer size, must be at least 4 bytes. Exactly 4 bytes are written. 914 | ) { 915 | byte result; 916 | 917 | // Sanity check 918 | if (buffer == NULL || bufferSize < 4) { 919 | return STATUS_INVALID; 920 | } 921 | 922 | // Build commmand buffer 923 | byte cmdBuffer[6]; 924 | cmdBuffer[0] = PICC_CMD_UL_WRITE; 925 | cmdBuffer[1] = page; 926 | memcpy(&cmdBuffer[2], buffer, 4); 927 | 928 | // Perform the write 929 | result = PCD_MIFARE_Transceive(cmdBuffer, 6); // Adds CRC_A and checks that the response is MF_ACK. 930 | if (result != STATUS_OK) { 931 | return result; 932 | } 933 | return STATUS_OK; 934 | } // End MIFARE_Ultralight_Write() 935 | 936 | /** 937 | * MIFARE Decrement subtracts the delta from the value of the addressed block, and stores the result in a volatile memory. 938 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 939 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 940 | * Use MIFARE_Transfer() to store the result in a block. 941 | * 942 | * @return STATUS_OK on success, STATUS_??? otherwise. 943 | */ 944 | byte MFRC522::MIFARE_Decrement( byte blockAddr, ///< The block (0-0xff) number. 945 | long delta ///< This number is subtracted from the value of block blockAddr. 946 | ) { 947 | return MIFARE_TwoStepHelper(PICC_CMD_MF_DECREMENT, blockAddr, delta); 948 | } // End MIFARE_Decrement() 949 | 950 | /** 951 | * MIFARE Increment adds the delta to the value of the addressed block, and stores the result in a volatile memory. 952 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 953 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 954 | * Use MIFARE_Transfer() to store the result in a block. 955 | * 956 | * @return STATUS_OK on success, STATUS_??? otherwise. 957 | */ 958 | byte MFRC522::MIFARE_Increment( byte blockAddr, ///< The block (0-0xff) number. 959 | long delta ///< This number is added to the value of block blockAddr. 960 | ) { 961 | return MIFARE_TwoStepHelper(PICC_CMD_MF_INCREMENT, blockAddr, delta); 962 | } // End MIFARE_Increment() 963 | 964 | /** 965 | * MIFARE Restore copies the value of the addressed block into a volatile memory. 966 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 967 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 968 | * Use MIFARE_Transfer() to store the result in a block. 969 | * 970 | * @return STATUS_OK on success, STATUS_??? otherwise. 971 | */ 972 | byte MFRC522::MIFARE_Restore( byte blockAddr ///< The block (0-0xff) number. 973 | ) { 974 | // The datasheet describes Restore as a two step operation, but does not explain what data to transfer in step 2. 975 | // Doing only a single step does not work, so I chose to transfer 0L in step two. 976 | return MIFARE_TwoStepHelper(PICC_CMD_MF_RESTORE, blockAddr, 0L); 977 | } // End MIFARE_Restore() 978 | 979 | /** 980 | * Helper function for the two-step MIFARE Classic protocol operations Decrement, Increment and Restore. 981 | * 982 | * @return STATUS_OK on success, STATUS_??? otherwise. 983 | */ 984 | byte MFRC522::MIFARE_TwoStepHelper( byte command, ///< The command to use 985 | byte blockAddr, ///< The block (0-0xff) number. 986 | long data ///< The data to transfer in step 2 987 | ) { 988 | byte result; 989 | byte cmdBuffer[2]; // We only need room for 2 bytes. 990 | 991 | // Step 1: Tell the PICC the command and block address 992 | cmdBuffer[0] = command; 993 | cmdBuffer[1] = blockAddr; 994 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 995 | if (result != STATUS_OK) { 996 | return result; 997 | } 998 | 999 | // Step 2: Transfer the data 1000 | result = PCD_MIFARE_Transceive( (byte *)&data, 4, true); // Adds CRC_A and accept timeout as success. 1001 | if (result != STATUS_OK) { 1002 | return result; 1003 | } 1004 | 1005 | return STATUS_OK; 1006 | } // End MIFARE_TwoStepHelper() 1007 | 1008 | /** 1009 | * MIFARE Transfer writes the value stored in the volatile memory into one MIFARE Classic block. 1010 | * For MIFARE Classic only. The sector containing the block must be authenticated before calling this function. 1011 | * Only for blocks in "value block" mode, ie with access bits [C1 C2 C3] = [110] or [001]. 1012 | * 1013 | * @return STATUS_OK on success, STATUS_??? otherwise. 1014 | */ 1015 | byte MFRC522::MIFARE_Transfer( byte blockAddr ///< The block (0-0xff) number. 1016 | ) { 1017 | byte result; 1018 | byte cmdBuffer[2]; // We only need room for 2 bytes. 1019 | 1020 | // Tell the PICC we want to transfer the result into block blockAddr. 1021 | cmdBuffer[0] = PICC_CMD_MF_TRANSFER; 1022 | cmdBuffer[1] = blockAddr; 1023 | result = PCD_MIFARE_Transceive( cmdBuffer, 2); // Adds CRC_A and checks that the response is MF_ACK. 1024 | if (result != STATUS_OK) { 1025 | return result; 1026 | } 1027 | return STATUS_OK; 1028 | } // End MIFARE_Transfer() 1029 | 1030 | /** 1031 | * Helper routine to read the current value from a Value Block. 1032 | * 1033 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1034 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1035 | * the block must be authenticated before calling this function. 1036 | * 1037 | * @param[in] blockAddr The block (0x00-0xff) number. 1038 | * @param[out] value Current value of the Value Block. 1039 | * @return STATUS_OK on success, STATUS_??? otherwise. 1040 | */ 1041 | byte MFRC522::MIFARE_GetValue(byte blockAddr, long *value) { 1042 | byte status; 1043 | byte buffer[18]; 1044 | byte size = sizeof(buffer); 1045 | 1046 | // Read the block 1047 | status = MIFARE_Read(blockAddr, buffer, &size); 1048 | if (status == STATUS_OK) { 1049 | // Extract the value 1050 | *value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1051 | } 1052 | return status; 1053 | } // End MIFARE_GetValue() 1054 | 1055 | /** 1056 | * Helper routine to write a specific value into a Value Block. 1057 | * 1058 | * Only for MIFARE Classic and only for blocks in "value block" mode, that 1059 | * is: with access bits [C1 C2 C3] = [110] or [001]. The sector containing 1060 | * the block must be authenticated before calling this function. 1061 | * 1062 | * @param[in] blockAddr The block (0x00-0xff) number. 1063 | * @param[in] value New value of the Value Block. 1064 | * @return STATUS_OK on success, STATUS_??? otherwise. 1065 | */ 1066 | byte MFRC522::MIFARE_SetValue(byte blockAddr, long value) { 1067 | byte buffer[18]; 1068 | 1069 | // Translate the long into 4 bytes; repeated 2x in value block 1070 | buffer[0] = buffer[ 8] = (value & 0xFF); 1071 | buffer[1] = buffer[ 9] = (value & 0xFF00) >> 8; 1072 | buffer[2] = buffer[10] = (value & 0xFF0000) >> 16; 1073 | buffer[3] = buffer[11] = (value & 0xFF000000) >> 24; 1074 | // Inverse 4 bytes also found in value block 1075 | buffer[4] = ~buffer[0]; 1076 | buffer[5] = ~buffer[1]; 1077 | buffer[6] = ~buffer[2]; 1078 | buffer[7] = ~buffer[3]; 1079 | // Address 2x with inverse address 2x 1080 | buffer[12] = buffer[14] = blockAddr; 1081 | buffer[13] = buffer[15] = ~blockAddr; 1082 | 1083 | // Write the whole data block 1084 | return MIFARE_Write(blockAddr, buffer, 16); 1085 | } // End MIFARE_SetValue() 1086 | 1087 | ///////////////////////////////////////////////////////////////////////////////////// 1088 | // Support functions 1089 | ///////////////////////////////////////////////////////////////////////////////////// 1090 | 1091 | /** 1092 | * Wrapper for MIFARE protocol communication. 1093 | * Adds CRC_A, executes the Transceive command and checks that the response is MF_ACK or a timeout. 1094 | * 1095 | * @return STATUS_OK on success, STATUS_??? otherwise. 1096 | */ 1097 | byte MFRC522::PCD_MIFARE_Transceive( byte *sendData, ///< Pointer to the data to transfer to the FIFO. Do NOT include the CRC_A. 1098 | byte sendLen, ///< Number of bytes in sendData. 1099 | bool acceptTimeout ///< True => A timeout is also success 1100 | ) { 1101 | byte result; 1102 | byte cmdBuffer[18]; // We need room for 16 bytes data and 2 bytes CRC_A. 1103 | 1104 | // Sanity check 1105 | if (sendData == NULL || sendLen > 16) { 1106 | return STATUS_INVALID; 1107 | } 1108 | 1109 | // Copy sendData[] to cmdBuffer[] and add CRC_A 1110 | memcpy(cmdBuffer, sendData, sendLen); 1111 | result = PCD_CalculateCRC(cmdBuffer, sendLen, &cmdBuffer[sendLen]); 1112 | if (result != STATUS_OK) { 1113 | return result; 1114 | } 1115 | sendLen += 2; 1116 | 1117 | // Transceive the data, store the reply in cmdBuffer[] 1118 | byte waitIRq = 0x30; // RxIRq and IdleIRq 1119 | byte cmdBufferSize = sizeof(cmdBuffer); 1120 | byte validBits = 0; 1121 | result = PCD_CommunicateWithPICC(PCD_Transceive, waitIRq, cmdBuffer, sendLen, cmdBuffer, &cmdBufferSize, &validBits); 1122 | if (acceptTimeout && result == STATUS_TIMEOUT) { 1123 | return STATUS_OK; 1124 | } 1125 | if (result != STATUS_OK) { 1126 | return result; 1127 | } 1128 | // The PICC must reply with a 4 bit ACK 1129 | if (cmdBufferSize != 1 || validBits != 4) { 1130 | return STATUS_ERROR; 1131 | } 1132 | if (cmdBuffer[0] != MF_ACK) { 1133 | return STATUS_MIFARE_NACK; 1134 | } 1135 | return STATUS_OK; 1136 | } // End PCD_MIFARE_Transceive() 1137 | 1138 | /** 1139 | * Returns a __FlashStringHelper pointer to a status code name. 1140 | * 1141 | * @return const __FlashStringHelper * 1142 | */ 1143 | const __FlashStringHelper *MFRC522::GetStatusCodeName(byte code ///< One of the StatusCode enums. 1144 | ) { 1145 | switch (code) { 1146 | case STATUS_OK: return F("Success."); break; 1147 | case STATUS_ERROR: return F("Error in communication."); break; 1148 | case STATUS_COLLISION: return F("Collission detected."); break; 1149 | case STATUS_TIMEOUT: return F("Timeout in communication."); break; 1150 | case STATUS_NO_ROOM: return F("A buffer is not big enough."); break; 1151 | case STATUS_INTERNAL_ERROR: return F("Internal error in the code. Should not happen."); break; 1152 | case STATUS_INVALID: return F("Invalid argument."); break; 1153 | case STATUS_CRC_WRONG: return F("The CRC_A does not match."); break; 1154 | case STATUS_MIFARE_NACK: return F("A MIFARE PICC responded with NAK."); break; 1155 | default: return F("Unknown error"); break; 1156 | } 1157 | } // End GetStatusCodeName() 1158 | 1159 | /** 1160 | * Translates the SAK (Select Acknowledge) to a PICC type. 1161 | * 1162 | * @return PICC_Type 1163 | */ 1164 | byte MFRC522::PICC_GetType(byte sak ///< The SAK byte returned from PICC_Select(). 1165 | ) { 1166 | if (sak & 0x04) { // UID not complete 1167 | return PICC_TYPE_NOT_COMPLETE; 1168 | } 1169 | 1170 | switch (sak) { 1171 | case 0x09: return PICC_TYPE_MIFARE_MINI; break; 1172 | case 0x08: return PICC_TYPE_MIFARE_1K; break; 1173 | case 0x18: return PICC_TYPE_MIFARE_4K; break; 1174 | case 0x00: return PICC_TYPE_MIFARE_UL; break; 1175 | case 0x10: 1176 | case 0x11: return PICC_TYPE_MIFARE_PLUS; break; 1177 | case 0x01: return PICC_TYPE_TNP3XXX; break; 1178 | default: break; 1179 | } 1180 | 1181 | if (sak & 0x20) { 1182 | return PICC_TYPE_ISO_14443_4; 1183 | } 1184 | 1185 | if (sak & 0x40) { 1186 | return PICC_TYPE_ISO_18092; 1187 | } 1188 | 1189 | return PICC_TYPE_UNKNOWN; 1190 | } // End PICC_GetType() 1191 | 1192 | /** 1193 | * Returns a __FlashStringHelper pointer to the PICC type name. 1194 | * 1195 | * @return const __FlashStringHelper * 1196 | */ 1197 | const __FlashStringHelper *MFRC522::PICC_GetTypeName(byte piccType ///< One of the PICC_Type enums. 1198 | ) { 1199 | switch (piccType) { 1200 | case PICC_TYPE_ISO_14443_4: return F("PICC compliant with ISO/IEC 14443-4"); break; 1201 | case PICC_TYPE_ISO_18092: return F("PICC compliant with ISO/IEC 18092 (NFC)");break; 1202 | case PICC_TYPE_MIFARE_MINI: return F("MIFARE Mini, 320 bytes"); break; 1203 | case PICC_TYPE_MIFARE_1K: return F("MIFARE 1KB"); break; 1204 | case PICC_TYPE_MIFARE_4K: return F("MIFARE 4KB"); break; 1205 | case PICC_TYPE_MIFARE_UL: return F("MIFARE Ultralight or Ultralight C"); break; 1206 | case PICC_TYPE_MIFARE_PLUS: return F("MIFARE Plus"); break; 1207 | case PICC_TYPE_TNP3XXX: return F("MIFARE TNP3XXX"); break; 1208 | case PICC_TYPE_NOT_COMPLETE: return F("SAK indicates UID is not complete."); break; 1209 | case PICC_TYPE_UNKNOWN: 1210 | default: return F("Unknown type"); break; 1211 | } 1212 | } // End PICC_GetTypeName() 1213 | 1214 | /** 1215 | * Dumps debug info about the selected PICC to Serial. 1216 | * On success the PICC is halted after dumping the data. 1217 | * For MIFARE Classic the factory default key of 0xFFFFFFFFFFFF is tried. 1218 | */ 1219 | void MFRC522::PICC_DumpToSerial(Uid *uid ///< Pointer to Uid struct returned from a successful PICC_Select(). 1220 | ) { 1221 | MIFARE_Key key; 1222 | 1223 | // UID 1224 | Serial.print(F("Card UID:")); 1225 | for (byte i = 0; i < uid->size; i++) { 1226 | if(uid->uidByte[i] < 0x10) 1227 | Serial.print(F(" 0")); 1228 | else 1229 | Serial.print(F(" ")); 1230 | Serial.print(uid->uidByte[i], HEX); 1231 | } 1232 | Serial.println(); 1233 | 1234 | // PICC type 1235 | byte piccType = PICC_GetType(uid->sak); 1236 | Serial.print(F("PICC type: ")); 1237 | Serial.println(PICC_GetTypeName(piccType)); 1238 | 1239 | // Dump contents 1240 | switch (piccType) { 1241 | case PICC_TYPE_MIFARE_MINI: 1242 | case PICC_TYPE_MIFARE_1K: 1243 | case PICC_TYPE_MIFARE_4K: 1244 | // All keys are set to FFFFFFFFFFFFh at chip delivery from the factory. 1245 | for (byte i = 0; i < 6; i++) { 1246 | key.keyByte[i] = 0xFF; 1247 | } 1248 | PICC_DumpMifareClassicToSerial(uid, piccType, &key); 1249 | break; 1250 | 1251 | case PICC_TYPE_MIFARE_UL: 1252 | PICC_DumpMifareUltralightToSerial(); 1253 | break; 1254 | 1255 | case PICC_TYPE_ISO_14443_4: 1256 | case PICC_TYPE_ISO_18092: 1257 | case PICC_TYPE_MIFARE_PLUS: 1258 | case PICC_TYPE_TNP3XXX: 1259 | Serial.println(F("Dumping memory contents not implemented for that PICC type.")); 1260 | break; 1261 | 1262 | case PICC_TYPE_UNKNOWN: 1263 | case PICC_TYPE_NOT_COMPLETE: 1264 | default: 1265 | break; // No memory dump here 1266 | } 1267 | 1268 | Serial.println(); 1269 | PICC_HaltA(); // Already done if it was a MIFARE Classic PICC. 1270 | } // End PICC_DumpToSerial() 1271 | 1272 | /** 1273 | * Dumps memory contents of a MIFARE Classic PICC. 1274 | * On success the PICC is halted after dumping the data. 1275 | */ 1276 | void MFRC522::PICC_DumpMifareClassicToSerial( Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1277 | byte piccType, ///< One of the PICC_Type enums. 1278 | MIFARE_Key *key ///< Key A used for all sectors. 1279 | ) { 1280 | byte no_of_sectors = 0; 1281 | switch (piccType) { 1282 | case PICC_TYPE_MIFARE_MINI: 1283 | // Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 1284 | no_of_sectors = 5; 1285 | break; 1286 | 1287 | case PICC_TYPE_MIFARE_1K: 1288 | // Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 1289 | no_of_sectors = 16; 1290 | break; 1291 | 1292 | case PICC_TYPE_MIFARE_4K: 1293 | // Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 1294 | no_of_sectors = 40; 1295 | break; 1296 | 1297 | default: // Should not happen. Ignore. 1298 | break; 1299 | } 1300 | 1301 | // Dump sectors, highest address first. 1302 | if (no_of_sectors) { 1303 | Serial.println(F("Sector Block 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 AccessBits")); 1304 | for (int8_t i = no_of_sectors - 1; i >= 0; i--) { 1305 | PICC_DumpMifareClassicSectorToSerial(uid, key, i); 1306 | } 1307 | } 1308 | PICC_HaltA(); // Halt the PICC before stopping the encrypted session. 1309 | PCD_StopCrypto1(); 1310 | } // End PICC_DumpMifareClassicToSerial() 1311 | 1312 | /** 1313 | * Dumps memory contents of a sector of a MIFARE Classic PICC. 1314 | * Uses PCD_Authenticate(), MIFARE_Read() and PCD_StopCrypto1. 1315 | * Always uses PICC_CMD_MF_AUTH_KEY_A because only Key A can always read the sector trailer access bits. 1316 | */ 1317 | void MFRC522::PICC_DumpMifareClassicSectorToSerial(Uid *uid, ///< Pointer to Uid struct returned from a successful PICC_Select(). 1318 | MIFARE_Key *key, ///< Key A for the sector. 1319 | byte sector ///< The sector to dump, 0..39. 1320 | ) { 1321 | byte status; 1322 | byte firstBlock; // Address of lowest address to dump actually last block dumped) 1323 | byte no_of_blocks; // Number of blocks in sector 1324 | bool isSectorTrailer; // Set to true while handling the "last" (ie highest address) in the sector. 1325 | 1326 | // The access bits are stored in a peculiar fashion. 1327 | // There are four groups: 1328 | // g[3] Access bits for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1329 | // g[2] Access bits for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1330 | // g[1] Access bits for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1331 | // g[0] Access bits for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1332 | // Each group has access bits [C1 C2 C3]. In this code C1 is MSB and C3 is LSB. 1333 | // The four CX bits are stored together in a nible cx and an inverted nible cx_. 1334 | byte c1, c2, c3; // Nibbles 1335 | byte c1_, c2_, c3_; // Inverted nibbles 1336 | bool invertedError; // True if one of the inverted nibbles did not match 1337 | byte g[4]; // Access bits for each of the four groups. 1338 | byte group; // 0-3 - active group for access bits 1339 | bool firstInGroup; // True for the first block dumped in the group 1340 | 1341 | // Determine position and size of sector. 1342 | if (sector < 32) { // Sectors 0..31 has 4 blocks each 1343 | no_of_blocks = 4; 1344 | firstBlock = sector * no_of_blocks; 1345 | } 1346 | else if (sector < 40) { // Sectors 32-39 has 16 blocks each 1347 | no_of_blocks = 16; 1348 | firstBlock = 128 + (sector - 32) * no_of_blocks; 1349 | } 1350 | else { // Illegal input, no MIFARE Classic PICC has more than 40 sectors. 1351 | return; 1352 | } 1353 | 1354 | // Dump blocks, highest address first. 1355 | byte byteCount; 1356 | byte buffer[18]; 1357 | byte blockAddr; 1358 | isSectorTrailer = true; 1359 | for (int8_t blockOffset = no_of_blocks - 1; blockOffset >= 0; blockOffset--) { 1360 | blockAddr = firstBlock + blockOffset; 1361 | // Sector number - only on first line 1362 | if (isSectorTrailer) { 1363 | if(sector < 10) 1364 | Serial.print(F(" ")); // Pad with spaces 1365 | else 1366 | Serial.print(F(" ")); // Pad with spaces 1367 | Serial.print(sector); 1368 | Serial.print(F(" ")); 1369 | } 1370 | else { 1371 | Serial.print(F(" ")); 1372 | } 1373 | // Block number 1374 | if(blockAddr < 10) 1375 | Serial.print(F(" ")); // Pad with spaces 1376 | else { 1377 | if(blockAddr < 100) 1378 | Serial.print(F(" ")); // Pad with spaces 1379 | else 1380 | Serial.print(F(" ")); // Pad with spaces 1381 | } 1382 | Serial.print(blockAddr); 1383 | Serial.print(F(" ")); 1384 | // Establish encrypted communications before reading the first block 1385 | if (isSectorTrailer) { 1386 | status = PCD_Authenticate(PICC_CMD_MF_AUTH_KEY_A, firstBlock, key, uid); 1387 | if (status != STATUS_OK) { 1388 | Serial.print(F("PCD_Authenticate() failed: ")); 1389 | Serial.println(GetStatusCodeName(status)); 1390 | return; 1391 | } 1392 | } 1393 | // Read block 1394 | byteCount = sizeof(buffer); 1395 | status = MIFARE_Read(blockAddr, buffer, &byteCount); 1396 | if (status != STATUS_OK) { 1397 | Serial.print(F("MIFARE_Read() failed: ")); 1398 | Serial.println(GetStatusCodeName(status)); 1399 | continue; 1400 | } 1401 | // Dump data 1402 | for (byte index = 0; index < 16; index++) { 1403 | if(buffer[index] < 0x10) 1404 | Serial.print(F(" 0")); 1405 | else 1406 | Serial.print(F(" ")); 1407 | Serial.print(buffer[index], HEX); 1408 | if ((index % 4) == 3) { 1409 | Serial.print(F(" ")); 1410 | } 1411 | } 1412 | // Parse sector trailer data 1413 | if (isSectorTrailer) { 1414 | c1 = buffer[7] >> 4; 1415 | c2 = buffer[8] & 0xF; 1416 | c3 = buffer[8] >> 4; 1417 | c1_ = buffer[6] & 0xF; 1418 | c2_ = buffer[6] >> 4; 1419 | c3_ = buffer[7] & 0xF; 1420 | invertedError = (c1 != (~c1_ & 0xF)) || (c2 != (~c2_ & 0xF)) || (c3 != (~c3_ & 0xF)); 1421 | g[0] = ((c1 & 1) << 2) | ((c2 & 1) << 1) | ((c3 & 1) << 0); 1422 | g[1] = ((c1 & 2) << 1) | ((c2 & 2) << 0) | ((c3 & 2) >> 1); 1423 | g[2] = ((c1 & 4) << 0) | ((c2 & 4) >> 1) | ((c3 & 4) >> 2); 1424 | g[3] = ((c1 & 8) >> 1) | ((c2 & 8) >> 2) | ((c3 & 8) >> 3); 1425 | isSectorTrailer = false; 1426 | } 1427 | 1428 | // Which access group is this block in? 1429 | if (no_of_blocks == 4) { 1430 | group = blockOffset; 1431 | firstInGroup = true; 1432 | } 1433 | else { 1434 | group = blockOffset / 5; 1435 | firstInGroup = (group == 3) || (group != (blockOffset + 1) / 5); 1436 | } 1437 | 1438 | if (firstInGroup) { 1439 | // Print access bits 1440 | Serial.print(F(" [ ")); 1441 | Serial.print((g[group] >> 2) & 1, DEC); Serial.print(F(" ")); 1442 | Serial.print((g[group] >> 1) & 1, DEC); Serial.print(F(" ")); 1443 | Serial.print((g[group] >> 0) & 1, DEC); 1444 | Serial.print(F(" ] ")); 1445 | if (invertedError) { 1446 | Serial.print(F(" Inverted access bits did not match! ")); 1447 | } 1448 | } 1449 | 1450 | if (group != 3 && (g[group] == 1 || g[group] == 6)) { // Not a sector trailer, a value block 1451 | long value = (long(buffer[3])<<24) | (long(buffer[2])<<16) | (long(buffer[1])<<8) | long(buffer[0]); 1452 | Serial.print(F(" Value=0x")); Serial.print(value, HEX); 1453 | Serial.print(F(" Adr=0x")); Serial.print(buffer[12], HEX); 1454 | } 1455 | Serial.println(); 1456 | } 1457 | 1458 | return; 1459 | } // End PICC_DumpMifareClassicSectorToSerial() 1460 | 1461 | /** 1462 | * Dumps memory contents of a MIFARE Ultralight PICC. 1463 | */ 1464 | void MFRC522::PICC_DumpMifareUltralightToSerial() { 1465 | byte status; 1466 | byte byteCount; 1467 | byte buffer[18]; 1468 | byte i; 1469 | 1470 | Serial.println(F("Page 0 1 2 3")); 1471 | // Try the mpages of the original Ultralight. Ultralight C has more pages. 1472 | for (byte page = 0; page < 16; page +=4) { // Read returns data for 4 pages at a time. 1473 | // Read pages 1474 | byteCount = sizeof(buffer); 1475 | status = MIFARE_Read(page, buffer, &byteCount); 1476 | if (status != STATUS_OK) { 1477 | Serial.print(F("MIFARE_Read() failed: ")); 1478 | Serial.println(GetStatusCodeName(status)); 1479 | break; 1480 | } 1481 | // Dump data 1482 | for (byte offset = 0; offset < 4; offset++) { 1483 | i = page + offset; 1484 | if(i < 10) 1485 | Serial.print(F(" ")); // Pad with spaces 1486 | else 1487 | Serial.print(F(" ")); // Pad with spaces 1488 | Serial.print(i); 1489 | Serial.print(F(" ")); 1490 | for (byte index = 0; index < 4; index++) { 1491 | i = 4 * offset + index; 1492 | if(buffer[i] < 0x10) 1493 | Serial.print(F(" 0")); 1494 | else 1495 | Serial.print(F(" ")); 1496 | Serial.print(buffer[i], HEX); 1497 | } 1498 | Serial.println(); 1499 | } 1500 | } 1501 | } // End PICC_DumpMifareUltralightToSerial() 1502 | 1503 | /** 1504 | * 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). 1505 | */ 1506 | void MFRC522::MIFARE_SetAccessBits( byte *accessBitBuffer, ///< Pointer to byte 6, 7 and 8 in the sector trailer. Bytes [0..2] will be set. 1507 | byte g0, ///< Access bits [C1 C2 C3] for block 0 (for sectors 0-31) or blocks 0-4 (for sectors 32-39) 1508 | byte g1, ///< Access bits C1 C2 C3] for block 1 (for sectors 0-31) or blocks 5-9 (for sectors 32-39) 1509 | byte g2, ///< Access bits C1 C2 C3] for block 2 (for sectors 0-31) or blocks 10-14 (for sectors 32-39) 1510 | byte g3 ///< Access bits C1 C2 C3] for the sector trailer, block 3 (for sectors 0-31) or block 15 (for sectors 32-39) 1511 | ) { 1512 | byte c1 = ((g3 & 4) << 1) | ((g2 & 4) << 0) | ((g1 & 4) >> 1) | ((g0 & 4) >> 2); 1513 | byte c2 = ((g3 & 2) << 2) | ((g2 & 2) << 1) | ((g1 & 2) << 0) | ((g0 & 2) >> 1); 1514 | byte c3 = ((g3 & 1) << 3) | ((g2 & 1) << 2) | ((g1 & 1) << 1) | ((g0 & 1) << 0); 1515 | 1516 | accessBitBuffer[0] = (~c2 & 0xF) << 4 | (~c1 & 0xF); 1517 | accessBitBuffer[1] = c1 << 4 | (~c3 & 0xF); 1518 | accessBitBuffer[2] = c3 << 4 | c2; 1519 | } // End MIFARE_SetAccessBits() 1520 | 1521 | 1522 | /** 1523 | * Performs the "magic sequence" needed to get Chinese UID changeable 1524 | * Mifare cards to allow writing to sector 0, where the card UID is stored. 1525 | * 1526 | * Note that you do not need to have selected the card through REQA or WUPA, 1527 | * this sequence works immediately when the card is in the reader vicinity. 1528 | * This means you can use this method even on "bricked" cards that your reader does 1529 | * not recognise anymore (see MFRC522::MIFARE_UnbrickUidSector). 1530 | * 1531 | * Of course with non-bricked devices, you're free to select them before calling this function. 1532 | */ 1533 | bool MFRC522::MIFARE_OpenUidBackdoor(bool logErrors) { 1534 | // Magic sequence: 1535 | // > 50 00 57 CD (HALT + CRC) 1536 | // > 40 (7 bits only) 1537 | // < A (4 bits only) 1538 | // > 43 1539 | // < A (4 bits only) 1540 | // Then you can write to sector 0 without authenticating 1541 | 1542 | PICC_HaltA(); // 50 00 57 CD 1543 | 1544 | byte cmd = 0x40; 1545 | byte validBits = 7; /* Our command is only 7 bits. After receiving card response, 1546 | this will contain amount of valid response bits. */ 1547 | byte response[32]; // Card's response is written here 1548 | byte received; 1549 | byte status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 40 1550 | if(status != STATUS_OK) { 1551 | if(logErrors) { 1552 | Serial.println(F("Card did not respond to 0x40 after HALT command. Are you sure it is a UID changeable one?")); 1553 | Serial.print(F("Error name: ")); 1554 | Serial.println(GetStatusCodeName(status)); 1555 | } 1556 | return false; 1557 | } 1558 | if (received != 1 || response[0] != 0x0A) { 1559 | if (logErrors) { 1560 | Serial.print(F("Got bad response on backdoor 0x40 command: ")); 1561 | Serial.print(response[0], HEX); 1562 | Serial.print(F(" (")); 1563 | Serial.print(validBits); 1564 | Serial.print(F(" valid bits)\r\n")); 1565 | } 1566 | return false; 1567 | } 1568 | 1569 | cmd = 0x43; 1570 | validBits = 8; 1571 | status = PCD_TransceiveData(&cmd, (byte)1, response, &received, &validBits, (byte)0, false); // 43 1572 | if(status != STATUS_OK) { 1573 | if(logErrors) { 1574 | Serial.println(F("Error in communication at command 0x43, after successfully executing 0x40")); 1575 | Serial.print(F("Error name: ")); 1576 | Serial.println(GetStatusCodeName(status)); 1577 | } 1578 | return false; 1579 | } 1580 | if (received != 1 || response[0] != 0x0A) { 1581 | if (logErrors) { 1582 | Serial.print(F("Got bad response on backdoor 0x43 command: ")); 1583 | Serial.print(response[0], HEX); 1584 | Serial.print(F(" (")); 1585 | Serial.print(validBits); 1586 | Serial.print(F(" valid bits)\r\n")); 1587 | } 1588 | return false; 1589 | } 1590 | 1591 | // You can now write to sector 0 without authenticating! 1592 | return true; 1593 | } // End MIFARE_OpenUidBackdoor() 1594 | 1595 | /** 1596 | * Reads entire block 0, including all manufacturer data, and overwrites 1597 | * that block with the new UID, a freshly calculated BCC, and the original 1598 | * manufacturer data. 1599 | * 1600 | * It assumes a default KEY A of 0xFFFFFFFFFFFF. 1601 | * Make sure to have selected the card before this function is called. 1602 | */ 1603 | bool MFRC522::MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors) { 1604 | 1605 | // UID + BCC byte can not be larger than 16 together 1606 | if (!newUid || !uidSize || uidSize > 15) { 1607 | if (logErrors) { 1608 | Serial.println(F("New UID buffer empty, size 0, or size > 15 given")); 1609 | } 1610 | return false; 1611 | } 1612 | 1613 | // Authenticate for reading 1614 | MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 1615 | byte status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1616 | if (status != STATUS_OK) { 1617 | 1618 | if (status == STATUS_TIMEOUT) { 1619 | // We get a read timeout if no card is selected yet, so let's select one 1620 | 1621 | // Wake the card up again if sleeping 1622 | // byte atqa_answer[2]; 1623 | // byte atqa_size = 2; 1624 | // PICC_WakeupA(atqa_answer, &atqa_size); 1625 | 1626 | if (!PICC_IsNewCardPresent() || !PICC_ReadCardSerial()) { 1627 | Serial.println(F("No card was previously selected, and none are available. Failed to set UID.")); 1628 | return false; 1629 | } 1630 | 1631 | status = PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)1, &key, &uid); 1632 | if (status != STATUS_OK) { 1633 | // We tried, time to give up 1634 | if (logErrors) { 1635 | Serial.println(F("Failed to authenticate to card for reading, could not set UID: ")); 1636 | Serial.println(GetStatusCodeName(status)); 1637 | } 1638 | return false; 1639 | } 1640 | } 1641 | else { 1642 | if (logErrors) { 1643 | Serial.print(F("PCD_Authenticate() failed: ")); 1644 | Serial.println(GetStatusCodeName(status)); 1645 | } 1646 | return false; 1647 | } 1648 | } 1649 | 1650 | // Read block 0 1651 | byte block0_buffer[18]; 1652 | byte byteCount = sizeof(block0_buffer); 1653 | status = MIFARE_Read((byte)0, block0_buffer, &byteCount); 1654 | if (status != STATUS_OK) { 1655 | if (logErrors) { 1656 | Serial.print(F("MIFARE_Read() failed: ")); 1657 | Serial.println(GetStatusCodeName(status)); 1658 | Serial.println(F("Are you sure your KEY A for sector 0 is 0xFFFFFFFFFFFF?")); 1659 | } 1660 | return false; 1661 | } 1662 | 1663 | // Write new UID to the data we just read, and calculate BCC byte 1664 | byte bcc = 0; 1665 | for (int i = 0; i < uidSize; i++) { 1666 | block0_buffer[i] = newUid[i]; 1667 | bcc ^= newUid[i]; 1668 | } 1669 | 1670 | // Write BCC byte to buffer 1671 | block0_buffer[uidSize] = bcc; 1672 | 1673 | // Stop encrypted traffic so we can send raw bytes 1674 | PCD_StopCrypto1(); 1675 | 1676 | // Activate UID backdoor 1677 | if (!MIFARE_OpenUidBackdoor(logErrors)) { 1678 | if (logErrors) { 1679 | Serial.println(F("Activating the UID backdoor failed.")); 1680 | } 1681 | return false; 1682 | } 1683 | 1684 | // Write modified block 0 back to card 1685 | status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1686 | if (status != STATUS_OK) { 1687 | if (logErrors) { 1688 | Serial.print(F("MIFARE_Write() failed: ")); 1689 | Serial.println(GetStatusCodeName(status)); 1690 | } 1691 | return false; 1692 | } 1693 | 1694 | // Wake the card up again 1695 | byte atqa_answer[2]; 1696 | byte atqa_size = 2; 1697 | PICC_WakeupA(atqa_answer, &atqa_size); 1698 | 1699 | return true; 1700 | } 1701 | 1702 | /** 1703 | * Resets entire sector 0 to zeroes, so the card can be read again by readers. 1704 | */ 1705 | bool MFRC522::MIFARE_UnbrickUidSector(bool logErrors) { 1706 | MIFARE_OpenUidBackdoor(logErrors); 1707 | 1708 | byte block0_buffer[] = {0x01, 0x02, 0x03, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 1709 | 1710 | // Write modified block 0 back to card 1711 | byte status = MIFARE_Write((byte)0, block0_buffer, (byte)16); 1712 | if (status != STATUS_OK) { 1713 | if (logErrors) { 1714 | Serial.print(F("MIFARE_Write() failed: ")); 1715 | Serial.println(GetStatusCodeName(status)); 1716 | } 1717 | return false; 1718 | } 1719 | return true; 1720 | } 1721 | 1722 | ///////////////////////////////////////////////////////////////////////////////////// 1723 | // Convenience functions - does not add extra functionality 1724 | ///////////////////////////////////////////////////////////////////////////////////// 1725 | 1726 | /** 1727 | * Returns true if a PICC responds to PICC_CMD_REQA. 1728 | * Only "new" cards in state IDLE are invited. Sleeping cards in state HALT are ignored. 1729 | * 1730 | * @return bool 1731 | */ 1732 | bool MFRC522::PICC_IsNewCardPresent() { 1733 | byte bufferATQA[2]; 1734 | byte bufferSize = sizeof(bufferATQA); 1735 | byte result = PICC_RequestA(bufferATQA, &bufferSize); 1736 | return (result == STATUS_OK || result == STATUS_COLLISION); 1737 | } // End PICC_IsNewCardPresent() 1738 | 1739 | /** 1740 | * Simple wrapper around PICC_Select. 1741 | * Returns true if a UID could be read. 1742 | * Remember to call PICC_IsNewCardPresent(), PICC_RequestA() or PICC_WakeupA() first. 1743 | * The read UID is available in the class variable uid. 1744 | * 1745 | * @return bool 1746 | */ 1747 | bool MFRC522::PICC_ReadCardSerial() { 1748 | byte result = PICC_Select(&uid); 1749 | return (result == STATUS_OK); 1750 | } // End PICC_ReadCardSerial() 1751 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/lib/MFRC522_I2C/MFRC522_I2C.h: -------------------------------------------------------------------------------- 1 | /** 2 | * MFRC522_I2C.h - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS I2C BY AROZCAN 3 | * MFRC522_I2C.h - Based on ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI Library BY COOQROBOT. 4 | * Based on code Dr.Leong ( WWW.B2CQSHOP.COM ) 5 | * Created by Miguel Balboa (circuitito.com), Jan, 2012. 6 | * Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.) 7 | * Extended by Tom Clement with functionality to write to sector 0 of UID changeable Mifare cards. 8 | * Extended by Ahmet Remzi Ozcan with I2C functionality. 9 | * Released into the public domain. 10 | * 11 | * Please read this file for an overview and then MFRC522.cpp for comments on the specific functions. 12 | * Search for "mf-rc522" on ebay.com to purchase the MF-RC522 board. 13 | * 14 | * There are three hardware components involved: 15 | * 1) The micro controller: An Arduino 16 | * 2) The PCD (short for Proximity Coupling Device): NXP MFRC522 Contactless Reader IC 17 | * 3) The PICC (short for Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203. 18 | * 19 | * The microcontroller and card reader uses I2C for communication. 20 | * The protocol is described in the MFRC522 datasheet: http://www.nxp.com/documents/data_sheet/MFRC522.pdf 21 | * 22 | * The card reader and the tags communicate using a 13.56MHz electromagnetic field. 23 | * The protocol is defined in ISO/IEC 14443-3 Identification cards -- Contactless integrated circuit cards -- Proximity cards -- Part 3: Initialization and anticollision". 24 | * A free version of the final draft can be found at http://wg8.de/wg8n1496_17n3613_Ballot_FCD14443-3.pdf 25 | * Details are found in chapter 6, Type A – Initialization and anticollision. 26 | * 27 | * If only the PICC UID is wanted, the above documents has all the needed information. 28 | * To read and write from MIFARE PICCs, the MIFARE protocol is used after the PICC has been selected. 29 | * The MIFARE Classic chips and protocol is described in the datasheets: 30 | * 1K: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf 31 | * 4K: http://www.nxp.com/documents/data_sheet/MF1S703x.pdf 32 | * Mini: http://www.idcardmarket.com/download/mifare_S20_datasheet.pdf 33 | * The MIFARE Ultralight chip and protocol is described in the datasheets: 34 | * Ultralight: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf 35 | * Ultralight C: http://www.nxp.com/documents/short_data_sheet/MF0ICU2_SDS.pdf 36 | * 37 | * MIFARE Classic 1K (MF1S503x): 38 | * Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes. 39 | * The blocks are numbered 0-63. 40 | * 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: 41 | * Bytes 0-5: Key A 42 | * Bytes 6-8: Access Bits 43 | * Bytes 9: User data 44 | * Bytes 10-15: Key B (or user data) 45 | * Block 0 is read-only manufacturer data. 46 | * To access a block, an authentication using a key from the block's sector must be performed first. 47 | * Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11). 48 | * All keys are set to FFFFFFFFFFFFh at chip delivery. 49 | * 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. 50 | * 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. 51 | * MIFARE Classic 4K (MF1S703x): 52 | * Has (32 sectors * 4 blocks/sector + 8 sectors * 16 blocks/sector) * 16 bytes/block = 4096 bytes. 53 | * The blocks are numbered 0-255. 54 | * The last block in each sector is the Sector Trailer like above. 55 | * MIFARE Classic Mini (MF1 IC S20): 56 | * Has 5 sectors * 4 blocks/sector * 16 bytes/block = 320 bytes. 57 | * The blocks are numbered 0-19. 58 | * The last block in each sector is the Sector Trailer like above. 59 | * 60 | * MIFARE Ultralight (MF0ICU1): 61 | * Has 16 pages of 4 bytes = 64 bytes. 62 | * Pages 0 + 1 is used for the 7-byte UID. 63 | * Page 2 contains the last check 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) 64 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 65 | * Pages 4-15 are read/write unless blocked by the lock bytes in page 2. 66 | * MIFARE Ultralight C (MF0ICU2): 67 | * Has 48 pages of 4 bytes = 192 bytes. 68 | * Pages 0 + 1 is used for the 7-byte UID. 69 | * Page 2 contains the last check 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) 70 | * Page 3 is OTP, One Time Programmable bits. Once set to 1 they cannot revert to 0. 71 | * Pages 4-39 are read/write unless blocked by the lock bytes in page 2. 72 | * Page 40 Lock bytes 73 | * Page 41 16 bit one way counter 74 | * Pages 42-43 Authentication configuration 75 | * Pages 44-47 Authentication key 76 | */ 77 | #ifndef MFRC522_h 78 | #define MFRC522_h 79 | 80 | #include 81 | #include 82 | 83 | // Firmware data for self-test 84 | // Reference values based on firmware version 85 | // Hint: if needed, you can remove unused self-test data to save flash memory 86 | // 87 | // Version 0.0 (0x90) 88 | // Philips Semiconductors; Preliminary Specification Revision 2.0 - 01 August 2005; 16.1 Sefttest 89 | const byte MFRC522_firmware_referenceV0_0[] PROGMEM = { 90 | 0x00, 0x87, 0x98, 0x0f, 0x49, 0xFF, 0x07, 0x19, 91 | 0xBF, 0x22, 0x30, 0x49, 0x59, 0x63, 0xAD, 0xCA, 92 | 0x7F, 0xE3, 0x4E, 0x03, 0x5C, 0x4E, 0x49, 0x50, 93 | 0x47, 0x9A, 0x37, 0x61, 0xE7, 0xE2, 0xC6, 0x2E, 94 | 0x75, 0x5A, 0xED, 0x04, 0x3D, 0x02, 0x4B, 0x78, 95 | 0x32, 0xFF, 0x58, 0x3B, 0x7C, 0xE9, 0x00, 0x94, 96 | 0xB4, 0x4A, 0x59, 0x5B, 0xFD, 0xC9, 0x29, 0xDF, 97 | 0x35, 0x96, 0x98, 0x9E, 0x4F, 0x30, 0x32, 0x8D 98 | }; 99 | // Version 1.0 (0x91) 100 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 101 | const byte MFRC522_firmware_referenceV1_0[] PROGMEM = { 102 | 0x00, 0xC6, 0x37, 0xD5, 0x32, 0xB7, 0x57, 0x5C, 103 | 0xC2, 0xD8, 0x7C, 0x4D, 0xD9, 0x70, 0xC7, 0x73, 104 | 0x10, 0xE6, 0xD2, 0xAA, 0x5E, 0xA1, 0x3E, 0x5A, 105 | 0x14, 0xAF, 0x30, 0x61, 0xC9, 0x70, 0xDB, 0x2E, 106 | 0x64, 0x22, 0x72, 0xB5, 0xBD, 0x65, 0xF4, 0xEC, 107 | 0x22, 0xBC, 0xD3, 0x72, 0x35, 0xCD, 0xAA, 0x41, 108 | 0x1F, 0xA7, 0xF3, 0x53, 0x14, 0xDE, 0x7E, 0x02, 109 | 0xD9, 0x0F, 0xB5, 0x5E, 0x25, 0x1D, 0x29, 0x79 110 | }; 111 | // Version 2.0 (0x92) 112 | // NXP Semiconductors; Rev. 3.8 - 17 September 2014; 16.1.1 Self test 113 | const byte MFRC522_firmware_referenceV2_0[] PROGMEM = { 114 | 0x00, 0xEB, 0x66, 0xBA, 0x57, 0xBF, 0x23, 0x95, 115 | 0xD0, 0xE3, 0x0D, 0x3D, 0x27, 0x89, 0x5C, 0xDE, 116 | 0x9D, 0x3B, 0xA7, 0x00, 0x21, 0x5B, 0x89, 0x82, 117 | 0x51, 0x3A, 0xEB, 0x02, 0x0C, 0xA5, 0x00, 0x49, 118 | 0x7C, 0x84, 0x4D, 0xB3, 0xCC, 0xD2, 0x1B, 0x81, 119 | 0x5D, 0x48, 0x76, 0xD5, 0x71, 0x61, 0x21, 0xA9, 120 | 0x86, 0x96, 0x83, 0x38, 0xCF, 0x9D, 0x5B, 0x6D, 121 | 0xDC, 0x15, 0xBA, 0x3E, 0x7D, 0x95, 0x3B, 0x2F 122 | }; 123 | // Clone 124 | // Fudan Semiconductor FM17522 (0x88) 125 | const byte FM17522_firmware_reference[] PROGMEM = { 126 | 0x00, 0xD6, 0x78, 0x8C, 0xE2, 0xAA, 0x0C, 0x18, 127 | 0x2A, 0xB8, 0x7A, 0x7F, 0xD3, 0x6A, 0xCF, 0x0B, 128 | 0xB1, 0x37, 0x63, 0x4B, 0x69, 0xAE, 0x91, 0xC7, 129 | 0xC3, 0x97, 0xAE, 0x77, 0xF4, 0x37, 0xD7, 0x9B, 130 | 0x7C, 0xF5, 0x3C, 0x11, 0x8F, 0x15, 0xC3, 0xD7, 131 | 0xC1, 0x5B, 0x00, 0x2A, 0xD0, 0x75, 0xDE, 0x9E, 132 | 0x51, 0x64, 0xAB, 0x3E, 0xE9, 0x15, 0xB5, 0xAB, 133 | 0x56, 0x9A, 0x98, 0x82, 0x26, 0xEA, 0x2A, 0x62 134 | }; 135 | 136 | class MFRC522 { 137 | public: 138 | // MFRC522 registers. Described in chapter 9 of the datasheet. 139 | enum PCD_Register { 140 | // Page 0: Command and status 141 | // 0x00 // reserved for future use 142 | CommandReg = 0x01 , // starts and stops command execution 143 | ComIEnReg = 0x02 , // enable and disable interrupt request control bits 144 | DivIEnReg = 0x03 , // enable and disable interrupt request control bits 145 | ComIrqReg = 0x04 , // interrupt request bits 146 | DivIrqReg = 0x05 , // interrupt request bits 147 | ErrorReg = 0x06 , // error bits showing the error status of the last command executed 148 | Status1Reg = 0x07 , // communication status bits 149 | Status2Reg = 0x08 , // receiver and transmitter status bits 150 | FIFODataReg = 0x09 , // input and output of 64 byte FIFO buffer 151 | FIFOLevelReg = 0x0A , // number of bytes stored in the FIFO buffer 152 | WaterLevelReg = 0x0B , // level for FIFO underflow and overflow warning 153 | ControlReg = 0x0C , // miscellaneous control registers 154 | BitFramingReg = 0x0D , // adjustments for bit-oriented frames 155 | CollReg = 0x0E , // bit position of the first bit-collision detected on the RF interface 156 | // 0x0F // reserved for future use 157 | 158 | // Page 1: Command 159 | // 0x10 // reserved for future use 160 | ModeReg = 0x11 , // defines general modes for transmitting and receiving 161 | TxModeReg = 0x12 , // defines transmission data rate and framing 162 | RxModeReg = 0x13 , // defines reception data rate and framing 163 | TxControlReg = 0x14 , // controls the logical behavior of the antenna driver pins TX1 and TX2 164 | TxASKReg = 0x15 , // controls the setting of the transmission modulation 165 | TxSelReg = 0x16 , // selects the internal sources for the antenna driver 166 | RxSelReg = 0x17 , // selects internal receiver settings 167 | RxThresholdReg = 0x18 , // selects thresholds for the bit decoder 168 | DemodReg = 0x19 , // defines demodulator settings 169 | // 0x1A // reserved for future use 170 | // 0x1B // reserved for future use 171 | MfTxReg = 0x1C , // controls some MIFARE communication transmit parameters 172 | MfRxReg = 0x1D , // controls some MIFARE communication receive parameters 173 | // 0x1E // reserved for future use 174 | SerialSpeedReg = 0x1F , // selects the speed of the serial UART interface 175 | 176 | // Page 2: Configuration 177 | // 0x20 // reserved for future use 178 | CRCResultRegH = 0x21 , // shows the MSB and LSB values of the CRC calculation 179 | CRCResultRegL = 0x22 , 180 | // 0x23 // reserved for future use 181 | ModWidthReg = 0x24 , // controls the ModWidth setting? 182 | // 0x25 // reserved for future use 183 | RFCfgReg = 0x26 , // configures the receiver gain 184 | GsNReg = 0x27 , // selects the conductance of the antenna driver pins TX1 and TX2 for modulation 185 | CWGsPReg = 0x28 , // defines the conductance of the p-driver output during periods of no modulation 186 | ModGsPReg = 0x29 , // defines the conductance of the p-driver output during periods of modulation 187 | TModeReg = 0x2A , // defines settings for the internal timer 188 | TPrescalerReg = 0x2B , // the lower 8 bits of the TPrescaler value. The 4 high bits are in TModeReg. 189 | TReloadRegH = 0x2C , // defines the 16-bit timer reload value 190 | TReloadRegL = 0x2D , 191 | TCounterValueRegH = 0x2E , // shows the 16-bit timer value 192 | TCounterValueRegL = 0x2F , 193 | 194 | // Page 3: Test Registers 195 | // 0x30 // reserved for future use 196 | TestSel1Reg = 0x31 , // general test signal configuration 197 | TestSel2Reg = 0x32 , // general test signal configuration 198 | TestPinEnReg = 0x33 , // enables pin output driver on pins D1 to D7 199 | TestPinValueReg = 0x34 , // defines the values for D1 to D7 when it is used as an I/O bus 200 | TestBusReg = 0x35 , // shows the status of the internal test bus 201 | AutoTestReg = 0x36 , // controls the digital self test 202 | VersionReg = 0x37 , // shows the software version 203 | AnalogTestReg = 0x38 , // controls the pins AUX1 and AUX2 204 | TestDAC1Reg = 0x39 , // defines the test value for TestDAC1 205 | TestDAC2Reg = 0x3A , // defines the test value for TestDAC2 206 | TestADCReg = 0x3B // shows the value of ADC I and Q channels 207 | // 0x3C // reserved for production tests 208 | // 0x3D // reserved for production tests 209 | // 0x3E // reserved for production tests 210 | // 0x3F // reserved for production tests 211 | }; 212 | 213 | // MFRC522 commands. Described in chapter 10 of the datasheet. 214 | enum PCD_Command { 215 | PCD_Idle = 0x00, // no action, cancels current command execution 216 | PCD_Mem = 0x01, // stores 25 bytes into the internal buffer 217 | PCD_GenerateRandomID = 0x02, // generates a 10-byte random ID number 218 | PCD_CalcCRC = 0x03, // activates the CRC coprocessor or performs a self test 219 | PCD_Transmit = 0x04, // transmits data from the FIFO buffer 220 | PCD_NoCmdChange = 0x07, // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit 221 | PCD_Receive = 0x08, // activates the receiver circuits 222 | PCD_Transceive = 0x0C, // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission 223 | PCD_MFAuthent = 0x0E, // performs the MIFARE standard authentication as a reader 224 | PCD_SoftReset = 0x0F // resets the MFRC522 225 | }; 226 | 227 | // MFRC522 RxGain[2:0] masks, defines the receiver's signal voltage gain factor (on the PCD). 228 | // Described in 9.3.3.6 / table 98 of the datasheet at http://www.nxp.com/documents/data_sheet/MFRC522.pdf 229 | enum PCD_RxGain { 230 | RxGain_18dB = 0x00 << 4, // 000b - 18 dB, minimum 231 | RxGain_23dB = 0x01 << 4, // 001b - 23 dB 232 | RxGain_18dB_2 = 0x02 << 4, // 010b - 18 dB, it seems 010b is a duplicate for 000b 233 | RxGain_23dB_2 = 0x03 << 4, // 011b - 23 dB, it seems 011b is a duplicate for 001b 234 | RxGain_33dB = 0x04 << 4, // 100b - 33 dB, average, and typical default 235 | RxGain_38dB = 0x05 << 4, // 101b - 38 dB 236 | RxGain_43dB = 0x06 << 4, // 110b - 43 dB 237 | RxGain_48dB = 0x07 << 4, // 111b - 48 dB, maximum 238 | RxGain_min = 0x00 << 4, // 000b - 18 dB, minimum, convenience for RxGain_18dB 239 | RxGain_avg = 0x04 << 4, // 100b - 33 dB, average, convenience for RxGain_33dB 240 | RxGain_max = 0x07 << 4 // 111b - 48 dB, maximum, convenience for RxGain_48dB 241 | }; 242 | 243 | // Commands sent to the PICC. 244 | enum PICC_Command { 245 | // The commands used by the PCD to manage communication with several PICCs (ISO 14443-3, Type A, section 6.4) 246 | 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. 247 | 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. 248 | PICC_CMD_CT = 0x88, // Cascade Tag. Not really a command, but used during anti collision. 249 | PICC_CMD_SEL_CL1 = 0x93, // Anti collision/Select, Cascade Level 1 250 | PICC_CMD_SEL_CL2 = 0x95, // Anti collision/Select, Cascade Level 2 251 | PICC_CMD_SEL_CL3 = 0x97, // Anti collision/Select, Cascade Level 3 252 | PICC_CMD_HLTA = 0x50, // HaLT command, Type A. Instructs an ACTIVE PICC to go to state HALT. 253 | // The commands used for MIFARE Classic (from http://www.nxp.com/documents/data_sheet/MF1S503x.pdf, Section 9) 254 | // Use PCD_MFAuthent to authenticate access to a sector, then use these commands to read/write/modify the blocks on the sector. 255 | // The read/write commands can also be used for MIFARE Ultralight. 256 | PICC_CMD_MF_AUTH_KEY_A = 0x60, // Perform authentication with Key A 257 | PICC_CMD_MF_AUTH_KEY_B = 0x61, // Perform authentication with Key B 258 | PICC_CMD_MF_READ = 0x30, // Reads one 16 byte block from the authenticated sector of the PICC. Also used for MIFARE Ultralight. 259 | PICC_CMD_MF_WRITE = 0xA0, // Writes one 16 byte block to the authenticated sector of the PICC. Called "COMPATIBILITY WRITE" for MIFARE Ultralight. 260 | PICC_CMD_MF_DECREMENT = 0xC0, // Decrements the contents of a block and stores the result in the internal data register. 261 | PICC_CMD_MF_INCREMENT = 0xC1, // Increments the contents of a block and stores the result in the internal data register. 262 | PICC_CMD_MF_RESTORE = 0xC2, // Reads the contents of a block into the internal data register. 263 | PICC_CMD_MF_TRANSFER = 0xB0, // Writes the contents of the internal data register to a block. 264 | // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf, Section 8.6) 265 | // The PICC_CMD_MF_READ and PICC_CMD_MF_WRITE can also be used for MIFARE Ultralight. 266 | PICC_CMD_UL_WRITE = 0xA2 // Writes one 4 byte page to the PICC. 267 | }; 268 | 269 | // MIFARE constants that does not fit anywhere else 270 | enum MIFARE_Misc { 271 | MF_ACK = 0xA, // The MIFARE Classic uses a 4 bit ACK/NAK. Any other value than 0xA is NAK. 272 | MF_KEY_SIZE = 6 // A Mifare Crypto1 key is 6 bytes. 273 | }; 274 | 275 | // PICC types we can detect. Remember to update PICC_GetTypeName() if you add more. 276 | enum PICC_Type { 277 | PICC_TYPE_UNKNOWN = 0, 278 | PICC_TYPE_ISO_14443_4 = 1, // PICC compliant with ISO/IEC 14443-4 279 | PICC_TYPE_ISO_18092 = 2, // PICC compliant with ISO/IEC 18092 (NFC) 280 | PICC_TYPE_MIFARE_MINI = 3, // MIFARE Classic protocol, 320 bytes 281 | PICC_TYPE_MIFARE_1K = 4, // MIFARE Classic protocol, 1KB 282 | PICC_TYPE_MIFARE_4K = 5, // MIFARE Classic protocol, 4KB 283 | PICC_TYPE_MIFARE_UL = 6, // MIFARE Ultralight or Ultralight C 284 | PICC_TYPE_MIFARE_PLUS = 7, // MIFARE Plus 285 | PICC_TYPE_TNP3XXX = 8, // Only mentioned in NXP AN 10833 MIFARE Type Identification Procedure 286 | PICC_TYPE_NOT_COMPLETE = 255 // SAK indicates UID is not complete. 287 | }; 288 | 289 | // Return codes from the functions in this class. Remember to update GetStatusCodeName() if you add more. 290 | enum StatusCode { 291 | STATUS_OK = 1, // Success 292 | STATUS_ERROR = 2, // Error in communication 293 | STATUS_COLLISION = 3, // Collission detected 294 | STATUS_TIMEOUT = 4, // Timeout in communication. 295 | STATUS_NO_ROOM = 5, // A buffer is not big enough. 296 | STATUS_INTERNAL_ERROR = 6, // Internal error in the code. Should not happen ;-) 297 | STATUS_INVALID = 7, // Invalid argument. 298 | STATUS_CRC_WRONG = 8, // The CRC_A does not match 299 | STATUS_MIFARE_NACK = 9 // A MIFARE PICC responded with NAK. 300 | }; 301 | 302 | // A struct used for passing the UID of a PICC. 303 | typedef struct { 304 | byte size; // Number of bytes in the UID. 4, 7 or 10. 305 | byte uidByte[10]; 306 | byte sak; // The SAK (Select acknowledge) byte returned from the PICC after successful selection. 307 | } Uid; 308 | 309 | // A struct used for passing a MIFARE Crypto1 key 310 | typedef struct { 311 | byte keyByte[MF_KEY_SIZE]; 312 | } MIFARE_Key; 313 | 314 | // Member variables 315 | Uid uid; // Used by PICC_ReadCardSerial(). 316 | 317 | // Size of the MFRC522 FIFO 318 | static const byte FIFO_SIZE = 64; // The FIFO is 64 bytes. 319 | 320 | ///////////////////////////////////////////////////////////////////////////////////// 321 | // Functions for setting up the Arduino 322 | ///////////////////////////////////////////////////////////////////////////////////// 323 | MFRC522(byte chipAddress, byte resetPowerDownPin); 324 | 325 | ///////////////////////////////////////////////////////////////////////////////////// 326 | // Basic interface functions for communicating with the MFRC522 327 | ///////////////////////////////////////////////////////////////////////////////////// 328 | void PCD_WriteRegister(byte reg, byte value); 329 | void PCD_WriteRegister(byte reg, byte count, byte *values); 330 | byte PCD_ReadRegister(byte reg); 331 | void PCD_ReadRegister(byte reg, byte count, byte *values, byte rxAlign = 0); 332 | void setBitMask(unsigned char reg, unsigned char mask); 333 | void PCD_SetRegisterBitMask(byte reg, byte mask); 334 | void PCD_ClearRegisterBitMask(byte reg, byte mask); 335 | byte PCD_CalculateCRC(byte *data, byte length, byte *result); 336 | 337 | ///////////////////////////////////////////////////////////////////////////////////// 338 | // Functions for manipulating the MFRC522 339 | ///////////////////////////////////////////////////////////////////////////////////// 340 | void PCD_Init(); 341 | void PCD_Reset(); 342 | void PCD_AntennaOn(); 343 | void PCD_AntennaOff(); 344 | byte PCD_GetAntennaGain(); 345 | void PCD_SetAntennaGain(byte mask); 346 | bool PCD_PerformSelfTest(); 347 | 348 | ///////////////////////////////////////////////////////////////////////////////////// 349 | // Functions for communicating with PICCs 350 | ///////////////////////////////////////////////////////////////////////////////////// 351 | byte PCD_TransceiveData(byte *sendData, byte sendLen, byte *backData, byte *backLen, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 352 | byte PCD_CommunicateWithPICC(byte command, byte waitIRq, byte *sendData, byte sendLen, byte *backData = NULL, byte *backLen = NULL, byte *validBits = NULL, byte rxAlign = 0, bool checkCRC = false); 353 | byte PICC_RequestA(byte *bufferATQA, byte *bufferSize); 354 | byte PICC_WakeupA(byte *bufferATQA, byte *bufferSize); 355 | byte PICC_REQA_or_WUPA(byte command, byte *bufferATQA, byte *bufferSize); 356 | byte PICC_Select(Uid *uid, byte validBits = 0); 357 | byte PICC_HaltA(); 358 | 359 | ///////////////////////////////////////////////////////////////////////////////////// 360 | // Functions for communicating with MIFARE PICCs 361 | ///////////////////////////////////////////////////////////////////////////////////// 362 | byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid); 363 | void PCD_StopCrypto1(); 364 | byte MIFARE_Read(byte blockAddr, byte *buffer, byte *bufferSize); 365 | byte MIFARE_Write(byte blockAddr, byte *buffer, byte bufferSize); 366 | byte MIFARE_Decrement(byte blockAddr, long delta); 367 | byte MIFARE_Increment(byte blockAddr, long delta); 368 | byte MIFARE_Restore(byte blockAddr); 369 | byte MIFARE_Transfer(byte blockAddr); 370 | byte MIFARE_Ultralight_Write(byte page, byte *buffer, byte bufferSize); 371 | byte MIFARE_GetValue(byte blockAddr, long *value); 372 | byte MIFARE_SetValue(byte blockAddr, long value); 373 | 374 | ///////////////////////////////////////////////////////////////////////////////////// 375 | // Support functions 376 | ///////////////////////////////////////////////////////////////////////////////////// 377 | byte PCD_MIFARE_Transceive(byte *sendData, byte sendLen, bool acceptTimeout = false); 378 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 379 | //const char *GetStatusCodeName(byte code); 380 | const __FlashStringHelper *GetStatusCodeName(byte code); 381 | byte PICC_GetType(byte sak); 382 | // old function used too much memory, now name moved to flash; if you need char, copy from flash to memory 383 | //const char *PICC_GetTypeName(byte type); 384 | const __FlashStringHelper *PICC_GetTypeName(byte type); 385 | void PICC_DumpToSerial(Uid *uid); 386 | void PICC_DumpMifareClassicToSerial(Uid *uid, byte piccType, MIFARE_Key *key); 387 | void PICC_DumpMifareClassicSectorToSerial(Uid *uid, MIFARE_Key *key, byte sector); 388 | void PICC_DumpMifareUltralightToSerial(); 389 | void MIFARE_SetAccessBits(byte *accessBitBuffer, byte g0, byte g1, byte g2, byte g3); 390 | bool MIFARE_OpenUidBackdoor(bool logErrors); 391 | bool MIFARE_SetUid(byte *newUid, byte uidSize, bool logErrors); 392 | bool MIFARE_UnbrickUidSector(bool logErrors); 393 | 394 | ///////////////////////////////////////////////////////////////////////////////////// 395 | // Convenience functions - does not add extra functionality 396 | ///////////////////////////////////////////////////////////////////////////////////// 397 | bool PICC_IsNewCardPresent(); 398 | bool PICC_ReadCardSerial(); 399 | 400 | private: 401 | byte _chipAddress; 402 | byte _resetPowerDownPin; // Arduino pin connected to MFRC522's reset and power down input (Pin 6, NRSTPD, active low) 403 | byte MIFARE_TwoStepHelper(byte command, byte blockAddr, long data); 404 | }; 405 | 406 | #endif 407 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/platformio.ini: -------------------------------------------------------------------------------- 1 | # 2 | # Project Configuration File 3 | # 4 | # A detailed documentation with the EXAMPLES is located here: 5 | # http://docs.platformio.org/en/latest/projectconf.html 6 | # 7 | 8 | # A sign `#` at the beginning of the line indicates a comment 9 | # Comment lines are ignored. 10 | 11 | # Simple and base environment 12 | # [env:mybaseenv] 13 | # platform = %INSTALLED_PLATFORM_NAME_HERE% 14 | # framework = 15 | # board = 16 | # 17 | # Automatic targets - enable auto-uploading 18 | # targets = upload 19 | 20 | [env:nodemcu] 21 | platform = espressif 22 | framework = arduino 23 | board = nodemcu 24 | -------------------------------------------------------------------------------- /examples/nodemcu_rfid/src/main.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | #include "MFRC522_I2C.h" 5 | 6 | #define SDA_PIN D5 7 | #define SCL_PIN D6 8 | #define RST_PIN D3 9 | 10 | MFRC522 mfrc522(0x28, RST_PIN); // Create MFRC522 instance. 11 | 12 | void ShowReaderDetails(); 13 | 14 | void setup() { 15 | Serial.begin(9600); // Initialize serial communications with the PC 16 | Wire.begin(SDA_PIN, SCL_PIN); // Initialize I2C 17 | mfrc522.PCD_Init(); // Init MFRC522 18 | ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details 19 | Serial.println(F("Scan PICC to see UID, type, and data blocks...")); 20 | } 21 | 22 | void loop() { 23 | // Look for new cards 24 | if ( ! mfrc522.PICC_IsNewCardPresent()) { 25 | return; 26 | } 27 | 28 | // Select one of the cards 29 | if ( ! mfrc522.PICC_ReadCardSerial()) { 30 | return; 31 | } 32 | 33 | // Dump debug info about the card; PICC_HaltA() is automatically called 34 | mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); 35 | } 36 | 37 | void ShowReaderDetails() { 38 | // Get the MFRC522 software version 39 | byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg); 40 | Serial.print(F("MFRC522 Software Version: 0x")); 41 | Serial.print(v, HEX); 42 | if (v == 0x91) 43 | Serial.print(F(" = v1.0")); 44 | else if (v == 0x92) 45 | Serial.print(F(" = v2.0")); 46 | else 47 | Serial.print(F(" (unknown)")); 48 | Serial.println(""); 49 | // When 0x00 or 0xFF is returned, communication probably failed 50 | if ((v == 0x00) || (v == 0xFF)) { 51 | Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?")); 52 | } 53 | } 54 | 55 | --------------------------------------------------------------------------------