MFRC522_I2C.cpp 65 KB

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