MFRC522_I2C.cpp 77 KB

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