MifareClassicValueBlock.ino 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /**
  2. * ----------------------------------------------------------------------------
  3. * This is a MFRC522 library example; see https://github.com/miguelbalboa/rfid
  4. * for further details and other examples.
  5. *
  6. * NOTE: The library file MFRC522.h has a lot of useful info. Please read it.
  7. *
  8. * Released into the public domain.
  9. * ----------------------------------------------------------------------------
  10. * This sample shows how to setup blocks on a MIFARE Classic PICC (= card/tag)
  11. * to be in "Value Block" mode: in this mode the operations Increment/Decrement,
  12. * Restore and Transfer can be used.
  13. *
  14. * BEWARE: Data will be written to the PICC, in sector #1 (blocks #4 to #7).
  15. *
  16. *
  17. * Typical pin layout used:
  18. * -----------------------------------------------------------------------------------------
  19. * MFRC522 Arduino Arduino Arduino Arduino Arduino
  20. * Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
  21. * Signal Pin Pin Pin Pin Pin Pin
  22. * -----------------------------------------------------------------------------------------
  23. * RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
  24. * SPI SS SDA(SS) 10 53 D10 10 10
  25. * SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
  26. * SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
  27. * SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
  28. *
  29. * More pin layouts for other boards can be found here: https://github.com/miguelbalboa/rfid#pin-layout
  30. *
  31. */
  32. #include <SPI.h>
  33. #include <MFRC522.h>
  34. #define RST_PIN 9 // Configurable, see typical pin layout above
  35. #define SS_PIN 10 // Configurable, see typical pin layout above
  36. MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
  37. MFRC522::MIFARE_Key key;
  38. /**
  39. * Initialize.
  40. */
  41. void setup() {
  42. Serial.begin(9600); // Initialize serial communications with the PC
  43. while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  44. SPI.begin(); // Init SPI bus
  45. mfrc522.PCD_Init(); // Init MFRC522 card
  46. // Prepare the key (used both as key A and as key B)
  47. // using FFFFFFFFFFFFh which is the default at chip delivery from the factory
  48. for (byte i = 0; i < 6; i++) {
  49. key.keyByte[i] = 0xFF;
  50. }
  51. Serial.println(F("Scan a MIFARE Classic PICC to demonstrate Value Block mode."));
  52. Serial.print(F("Using key (for A and B):"));
  53. dump_byte_array(key.keyByte, MFRC522::MF_KEY_SIZE);
  54. Serial.println();
  55. Serial.println(F("BEWARE: Data will be written to the PICC, in sector #1"));
  56. }
  57. /**
  58. * Main loop.
  59. */
  60. void loop() {
  61. // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  62. if ( ! mfrc522.PICC_IsNewCardPresent())
  63. return;
  64. // Select one of the cards
  65. if ( ! mfrc522.PICC_ReadCardSerial())
  66. return;
  67. // Show some details of the PICC (that is: the tag/card)
  68. Serial.print(F("Card UID:"));
  69. dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  70. Serial.println();
  71. Serial.print(F("PICC type: "));
  72. MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  73. Serial.println(mfrc522.PICC_GetTypeName(piccType));
  74. // Check for compatibility
  75. if ( piccType != MFRC522::PICC_TYPE_MIFARE_MINI
  76. && piccType != MFRC522::PICC_TYPE_MIFARE_1K
  77. && piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
  78. Serial.println(F("This sample only works with MIFARE Classic cards."));
  79. return;
  80. }
  81. // In this sample we use the second sector,
  82. // that is: sector #1, covering block #4 up to and including block #7
  83. byte sector = 1;
  84. byte valueBlockA = 5;
  85. byte valueBlockB = 6;
  86. byte trailerBlock = 7;
  87. MFRC522::StatusCode status;
  88. byte buffer[18];
  89. byte size = sizeof(buffer);
  90. int32_t value;
  91. // Authenticate using key A
  92. Serial.println(F("Authenticating using key A..."));
  93. status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  94. if (status != MFRC522::STATUS_OK) {
  95. Serial.print(F("PCD_Authenticate() failed: "));
  96. Serial.println(mfrc522.GetStatusCodeName(status));
  97. return;
  98. }
  99. // Show the whole sector as it currently is
  100. Serial.println(F("Current data in sector:"));
  101. mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
  102. Serial.println();
  103. // We need a sector trailer that defines blocks 5 and 6 as Value Blocks and enables key B
  104. // The last block in a sector (block #3 for Mifare Classic 1K) is the Sector Trailer.
  105. // See http://www.nxp.com/documents/data_sheet/MF1S503x.pdf sections 8.6 and 8.7:
  106. // Bytes 0-5: Key A
  107. // Bytes 6-8: Access Bits
  108. // Bytes 9: User data
  109. // Bytes 10-15: Key B (or user data)
  110. byte trailerBuffer[] = {
  111. 255, 255, 255, 255, 255, 255, // Keep default key A
  112. 0, 0, 0,
  113. 0,
  114. 255, 255, 255, 255, 255, 255}; // Keep default key B
  115. // The access bits are stored in a peculiar fashion.
  116. // There are four groups:
  117. // g[0] Access bits for block 0 (for sectors 0-31)
  118. // or blocks 0-4 (for sectors 32-39)
  119. // g[1] Access bits for block 1 (for sectors 0-31)
  120. // or blocks 5-9 (for sectors 32-39)
  121. // g[2] Access bits for block 2 (for sectors 0-31)
  122. // or blocks 10-14 (for sectors 32-39)
  123. // g[3] Access bits for the Sector Trailer: block 3 (for sectors 0-31)
  124. // or block 15 (for sectors 32-39)
  125. // Each group has access bits [C1 C2 C3], in this code C1 is MSB and C3 is LSB.
  126. // Determine the bit pattern needed using MIFARE_SetAccessBits:
  127. // g0=0 access bits for block 0 (of this sector) using [0 0 0] = 000b = 0
  128. // which means key A|B have r/w for block 0 of this sector
  129. // which (in this example) translates to block #4 within sector #1;
  130. // this is the transport configuration (at factory delivery).
  131. // g1=6 access bits for block 1 (of this sector) using [1 1 0] = 110b = 6
  132. // which means block 1 (of this sector) is used as a value block,
  133. // which (in this example) translates to block #5 within sector #1;
  134. // where key A|B have r, key B has w, key B can increment,
  135. // and key A|B can decrement, transfer, and restore.
  136. // g2=6 same thing for block 2 (of this sector): set it to a value block;
  137. // which (in this example) translates to block #6 within sector #1;
  138. // g3=3 access bits for block 3 (of this sector): the Sector Trailer here;
  139. // using [0 1 1] = 011b = 3 which means only key B has r/w access
  140. // to the Sector Trailer (block 3 of this sector) from now on
  141. // which (in this example) translates to block #7 within sector #1;
  142. mfrc522.MIFARE_SetAccessBits(&trailerBuffer[6], 0, 6, 6, 3);
  143. // Read the sector trailer as it is currently stored on the PICC
  144. Serial.println(F("Reading sector trailer..."));
  145. status = mfrc522.MIFARE_Read(trailerBlock, buffer, &size);
  146. if (status != MFRC522::STATUS_OK) {
  147. Serial.print(F("MIFARE_Read() failed: "));
  148. Serial.println(mfrc522.GetStatusCodeName(status));
  149. return;
  150. }
  151. // Check if it matches the desired access pattern already;
  152. // because if it does, we don't need to write it again...
  153. if ( buffer[6] != trailerBuffer[6]
  154. || buffer[7] != trailerBuffer[7]
  155. || buffer[8] != trailerBuffer[8]) {
  156. // They don't match (yet), so write it to the PICC
  157. Serial.println(F("Writing new sector trailer..."));
  158. status = mfrc522.MIFARE_Write(trailerBlock, trailerBuffer, 16);
  159. if (status != MFRC522::STATUS_OK) {
  160. Serial.print(F("MIFARE_Write() failed: "));
  161. Serial.println(mfrc522.GetStatusCodeName(status));
  162. return;
  163. }
  164. }
  165. // Authenticate using key B
  166. Serial.println(F("Authenticating again using key B..."));
  167. status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
  168. if (status != MFRC522::STATUS_OK) {
  169. Serial.print(F("PCD_Authenticate() failed: "));
  170. Serial.println(mfrc522.GetStatusCodeName(status));
  171. return;
  172. }
  173. // A value block has a 32 bit signed value stored three times
  174. // and an 8 bit address stored 4 times. Make sure that valueBlockA
  175. // and valueBlockB have that format (note that it will only format
  176. // the block when it doesn't comply to the expected format already).
  177. formatValueBlock(valueBlockA);
  178. formatValueBlock(valueBlockB);
  179. // Add 1 to the value of valueBlockA and store the result in valueBlockA.
  180. Serial.print("Adding 1 to value of block "); Serial.println(valueBlockA);
  181. status = mfrc522.MIFARE_Increment(valueBlockA, 1);
  182. if (status != MFRC522::STATUS_OK) {
  183. Serial.print(F("MIFARE_Increment() failed: "));
  184. Serial.println(mfrc522.GetStatusCodeName(status));
  185. return;
  186. }
  187. status = mfrc522.MIFARE_Transfer(valueBlockA);
  188. if (status != MFRC522::STATUS_OK) {
  189. Serial.print(F("MIFARE_Transfer() failed: "));
  190. Serial.println(mfrc522.GetStatusCodeName(status));
  191. return;
  192. }
  193. // Show the new value of valueBlockA
  194. status = mfrc522.MIFARE_GetValue(valueBlockA, &value);
  195. if (status != MFRC522::STATUS_OK) {
  196. Serial.print(F("mifare_GetValue() failed: "));
  197. Serial.println(mfrc522.GetStatusCodeName(status));
  198. return;
  199. }
  200. Serial.print("New value of value block "); Serial.print(valueBlockA);
  201. Serial.print(" = "); Serial.println(value);
  202. // Decrement 10 from the value of valueBlockB and store the result in valueBlockB.
  203. Serial.print("Subtracting 10 from value of block "); Serial.println(valueBlockB);
  204. status = mfrc522.MIFARE_Decrement(valueBlockB, 10);
  205. if (status != MFRC522::STATUS_OK) {
  206. Serial.print(F("MIFARE_Decrement() failed: "));
  207. Serial.println(mfrc522.GetStatusCodeName(status));
  208. return;
  209. }
  210. status = mfrc522.MIFARE_Transfer(valueBlockB);
  211. if (status != MFRC522::STATUS_OK) {
  212. Serial.print(F("MIFARE_Transfer() failed: "));
  213. Serial.println(mfrc522.GetStatusCodeName(status));
  214. return;
  215. }
  216. // Show the new value of valueBlockB
  217. status = mfrc522.MIFARE_GetValue(valueBlockB, &value);
  218. if (status != MFRC522::STATUS_OK) {
  219. Serial.print(F("mifare_GetValue() failed: "));
  220. Serial.println(mfrc522.GetStatusCodeName(status));
  221. return;
  222. }
  223. Serial.print(F("New value of value block ")); Serial.print(valueBlockB);
  224. Serial.print(F(" = ")); Serial.println(value);
  225. // Check some boundary...
  226. if (value <= -100) {
  227. Serial.println(F("Below -100, so resetting it to 255 = 0xFF just for fun..."));
  228. status = mfrc522.MIFARE_SetValue(valueBlockB, 255);
  229. if (status != MFRC522::STATUS_OK) {
  230. Serial.print(F("mifare_SetValue() failed: "));
  231. Serial.println(mfrc522.GetStatusCodeName(status));
  232. return;
  233. }
  234. }
  235. // Dump the sector data
  236. mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);
  237. Serial.println();
  238. // Halt PICC
  239. mfrc522.PICC_HaltA();
  240. // Stop encryption on PCD
  241. mfrc522.PCD_StopCrypto1();
  242. }
  243. /**
  244. * Helper routine to dump a byte array as hex values to Serial.
  245. */
  246. void dump_byte_array(byte *buffer, byte bufferSize) {
  247. for (byte i = 0; i < bufferSize; i++) {
  248. Serial.print(buffer[i] < 0x10 ? " 0" : " ");
  249. Serial.print(buffer[i], HEX);
  250. }
  251. }
  252. /**
  253. * Ensure that a given block is formatted as a Value Block.
  254. */
  255. void formatValueBlock(byte blockAddr) {
  256. byte buffer[18];
  257. byte size = sizeof(buffer);
  258. MFRC522::StatusCode status;
  259. Serial.print(F("Reading block ")); Serial.println(blockAddr);
  260. status = mfrc522.MIFARE_Read(blockAddr, buffer, &size);
  261. if (status != MFRC522::STATUS_OK) {
  262. Serial.print(F("MIFARE_Read() failed: "));
  263. Serial.println(mfrc522.GetStatusCodeName(status));
  264. return;
  265. }
  266. if ( (buffer[0] == (byte)~buffer[4])
  267. && (buffer[1] == (byte)~buffer[5])
  268. && (buffer[2] == (byte)~buffer[6])
  269. && (buffer[3] == (byte)~buffer[7])
  270. && (buffer[0] == buffer[8])
  271. && (buffer[1] == buffer[9])
  272. && (buffer[2] == buffer[10])
  273. && (buffer[3] == buffer[11])
  274. && (buffer[12] == (byte)~buffer[13])
  275. && (buffer[12] == buffer[14])
  276. && (buffer[12] == (byte)~buffer[15])) {
  277. Serial.println(F("Block has correct Value Block format."));
  278. }
  279. else {
  280. Serial.println(F("Formatting as Value Block..."));
  281. byte valueBlock[] = {
  282. 0, 0, 0, 0,
  283. 255, 255, 255, 255,
  284. 0, 0, 0, 0,
  285. blockAddr, ~blockAddr, blockAddr, ~blockAddr };
  286. status = mfrc522.MIFARE_Write(blockAddr, valueBlock, 16);
  287. if (status != MFRC522::STATUS_OK) {
  288. Serial.print(F("MIFARE_Write() failed: "));
  289. Serial.println(mfrc522.GetStatusCodeName(status));
  290. }
  291. }
  292. }