pn532.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /**************************************************************************
  2. * @file pn532.c
  3. * @author Yehui from Waveshare
  4. * @license BSD
  5. *
  6. * This is a library for the Waveshare PN532 NFC modules
  7. *
  8. * Check out the links above for our tutorials and wiring diagrams
  9. * These chips use SPI communicate.
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documnetation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS OR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. **************************************************************************/
  29. #include <stdio.h>
  30. #include "pn532.h"
  31. const uint8_t PN532_ACK[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
  32. const uint8_t PN532_FRAME_START[] = {0x00, 0x00, 0xFF};
  33. #define PN532_FRAME_MAX_LENGTH 255
  34. #define PN532_DEFAULT_TIMEOUT 1000
  35. /**
  36. * @brief: Write a frame to the PN532 of at most length bytes in size.
  37. * Note that less than length bytes might be returned!
  38. * @retval: Returns -1 if there is an error parsing the frame.
  39. */
  40. int PN532_WriteFrame(PN532* pn532, uint8_t* data, uint16_t length) {
  41. if (length > PN532_FRAME_MAX_LENGTH || length < 1) {
  42. return PN532_STATUS_ERROR; // Data must be array of 1 to 255 bytes.
  43. }
  44. // Build frame to send as:
  45. // - Preamble (0x00)
  46. // - Start code (0x00, 0xFF)
  47. // - Command length (1 byte)
  48. // - Command length checksum
  49. // - Command bytes
  50. // - Checksum
  51. // - Postamble (0x00)
  52. uint8_t frame[PN532_FRAME_MAX_LENGTH + 7];
  53. uint8_t checksum = 0;
  54. frame[0] = PN532_PREAMBLE;
  55. frame[1] = PN532_STARTCODE1;
  56. frame[2] = PN532_STARTCODE2;
  57. for (uint8_t i = 0; i < 3; i++) {
  58. checksum += frame[i];
  59. }
  60. frame[3] = length & 0xFF;
  61. frame[4] = (~length + 1) & 0xFF;
  62. for (uint8_t i = 0; i < length; i++) {
  63. frame[5 + i] = data[i];
  64. checksum += data[i];
  65. }
  66. frame[length + 5] = ~checksum & 0xFF;
  67. frame[length + 6] = PN532_POSTAMBLE;
  68. if (pn532->write_data(frame, length + 7) != PN532_STATUS_OK) {
  69. return PN532_STATUS_ERROR;
  70. }
  71. return PN532_STATUS_OK;
  72. }
  73. /**
  74. * @brief: Read a response frame from the PN532 of at most length bytes in size.
  75. * Note that less than length bytes might be returned!
  76. * @retval: Returns frame length or -1 if there is an error parsing the frame.
  77. */
  78. int PN532_ReadFrame(PN532* pn532, uint8_t* response, uint16_t length) {
  79. uint8_t buff[PN532_FRAME_MAX_LENGTH + 7];
  80. uint8_t checksum = 0;
  81. // Read frame with expected length of data.
  82. pn532->read_data(buff, length + 7);
  83. // Swallow all the 0x00 values that preceed 0xFF.
  84. uint8_t offset = 0;
  85. while (buff[offset] == 0x00) {
  86. offset += 1;
  87. if (offset >= length + 8){
  88. pn532->log("Response frame preamble does not contain 0x00FF!");
  89. return PN532_STATUS_ERROR;
  90. }
  91. }
  92. if (buff[offset] != 0xFF) {
  93. pn532->log("Response frame preamble does not contain 0x00FF!");
  94. return PN532_STATUS_ERROR;
  95. }
  96. offset += 1;
  97. if (offset >= length + 8) {
  98. pn532->log("Response contains no data!");
  99. return PN532_STATUS_ERROR;
  100. }
  101. // Check length & length checksum match.
  102. uint8_t frame_len = buff[offset];
  103. if (((frame_len + buff[offset+1]) & 0xFF) != 0) {
  104. pn532->log("Response length checksum did not match length!");
  105. return PN532_STATUS_ERROR;
  106. }
  107. // Check frame checksum value matches bytes.
  108. for (uint8_t i = 0; i < frame_len + 1; i++) {
  109. checksum += buff[offset + 2 + i];
  110. }
  111. checksum &= 0xFF;
  112. if (checksum != 0) {
  113. pn532->log("Response checksum did not match expected checksum");
  114. return PN532_STATUS_ERROR;
  115. }
  116. // Return frame data.
  117. for (uint8_t i = 0; i < frame_len; i++) {
  118. response[i] = buff[offset + 2 + i];
  119. }
  120. return frame_len;
  121. }
  122. /**
  123. * @brief: Send specified command to the PN532 and expect up to response_length.
  124. * Will wait up to timeout seconds for a response and read a bytearray into
  125. * response buffer.
  126. * @param pn532: PN532 handler
  127. * @param command: command to send
  128. * @param response: buffer returned
  129. * @param response_length: expected response length
  130. * @param params: can optionally specify an array of bytes to send as parameters
  131. * to the function call, or NULL if there is no need to send parameters.
  132. * @param params_length: length of the argument params
  133. * @param timeout: timout of systick
  134. * @retval: Returns the length of response or -1 if error.
  135. */
  136. int PN532_CallFunction(
  137. PN532* pn532,
  138. uint8_t command,
  139. uint8_t* response,
  140. uint16_t response_length,
  141. uint8_t* params,
  142. uint16_t params_length,
  143. uint32_t timeout
  144. ) {
  145. // Build frame data with command and parameters.
  146. uint8_t buff[PN532_FRAME_MAX_LENGTH];
  147. buff[0] = PN532_HOSTTOPN532;
  148. buff[1] = command & 0xFF;
  149. for (uint8_t i = 0; i < params_length; i++) {
  150. buff[2 + i] = params[i];
  151. }
  152. // Send frame and wait for response.
  153. if (PN532_WriteFrame(pn532, buff, params_length + 2) != PN532_STATUS_OK) {
  154. pn532->wakeup();
  155. pn532->log("Trying to wakeup");
  156. return PN532_STATUS_ERROR;
  157. }
  158. if (!pn532->wait_ready(timeout)) {
  159. return PN532_STATUS_ERROR;
  160. }
  161. // Verify ACK response and wait to be ready for function response.
  162. pn532->read_data(buff, sizeof(PN532_ACK));
  163. for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) {
  164. if (PN532_ACK[i] != buff[i]) {
  165. pn532->log("Did not receive expected ACK from PN532!");
  166. return PN532_STATUS_ERROR;
  167. }
  168. }
  169. if (!pn532->wait_ready(timeout)) {
  170. return PN532_STATUS_ERROR;
  171. }
  172. // Read response bytes.
  173. int frame_len = PN532_ReadFrame(pn532, buff, response_length + 2);
  174. // Check that response is for the called function.
  175. if (! ((buff[0] == PN532_PN532TOHOST) && (buff[1] == (command+1)))) {
  176. pn532->log("Received unexpected command response!");
  177. return PN532_STATUS_ERROR;
  178. }
  179. // Return response data.
  180. for (uint8_t i = 0; i < response_length; i++) {
  181. response[i] = buff[i + 2];
  182. }
  183. // The the number of bytes read
  184. return frame_len - 2;
  185. }
  186. /**
  187. * @brief: Call PN532 GetFirmwareVersion function and return a buff with the IC,
  188. * Ver, Rev, and Support values.
  189. */
  190. int PN532_GetFirmwareVersion(PN532* pn532, uint8_t* version) {
  191. // length of version: 4
  192. if (PN532_CallFunction(pn532, PN532_COMMAND_GETFIRMWAREVERSION,
  193. version, 4, NULL, 0, 500) == PN532_STATUS_ERROR) {
  194. pn532->log("Failed to detect the PN532");
  195. return PN532_STATUS_ERROR;
  196. }
  197. return PN532_STATUS_OK;
  198. }
  199. /**
  200. * @brief: Configure the PN532 to read MiFare cards.
  201. */
  202. int PN532_SamConfiguration(PN532* pn532) {
  203. // Send SAM configuration command with configuration for:
  204. // - 0x01, normal mode
  205. // - 0x14, timeout 50ms * 20 = 1 second
  206. // - 0x01, use IRQ pin
  207. // Note that no other verification is necessary as call_function will
  208. // check the command was executed as expected.
  209. uint8_t params[] = {0x01, 0x14, 0x01};
  210. PN532_CallFunction(pn532, PN532_COMMAND_SAMCONFIGURATION,
  211. NULL, 0, params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  212. return PN532_STATUS_OK;
  213. }
  214. /**
  215. * @brief: Wait for a MiFare card to be available and return its UID when found.
  216. * Will wait up to timeout seconds and return None if no card is found,
  217. * otherwise a bytearray with the UID of the found card is returned.
  218. * @retval: Length of UID, or -1 if error.
  219. */
  220. int PN532_ReadPassiveTarget(
  221. PN532* pn532,
  222. uint8_t* response,
  223. uint8_t card_baud,
  224. uint32_t timeout
  225. ) {
  226. // Send passive read command for 1 card. Expect at most a 7 byte UUID.
  227. uint8_t params[] = {0x01, card_baud};
  228. uint8_t buff[19];
  229. int length = PN532_CallFunction(pn532, PN532_COMMAND_INLISTPASSIVETARGET,
  230. buff, sizeof(buff), params, sizeof(params), timeout);
  231. if (length < 0) {
  232. return PN532_STATUS_ERROR; // No card found
  233. }
  234. // Check only 1 card with up to a 7 byte UID is present.
  235. if (buff[0] != 0x01) {
  236. pn532->log("More than one card detected!");
  237. return PN532_STATUS_ERROR;
  238. }
  239. if (buff[5] > 7) {
  240. pn532->log("Found card with unexpectedly long UID!");
  241. return PN532_STATUS_ERROR;
  242. }
  243. for (uint8_t i = 0; i < buff[5]; i++) {
  244. response[i] = buff[6 + i];
  245. }
  246. return buff[5];
  247. }
  248. /**
  249. * @brief: Authenticate specified block number for a MiFare classic card.
  250. * @param uid: A byte array with the UID of the card.
  251. * @param uid_length: Length of the UID of the card.
  252. * @param block_number: The block to authenticate.
  253. * @param key_number: The key type (like MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B).
  254. * @param key: A byte array with the key data.
  255. * @retval: true if the block was authenticated, or false if not authenticated.
  256. * @retval: PN532 error code.
  257. */
  258. int PN532_MifareClassicAuthenticateBlock(
  259. PN532* pn532,
  260. uint8_t* uid,
  261. uint8_t uid_length,
  262. uint16_t block_number,
  263. uint16_t key_number,
  264. uint8_t* key
  265. ) {
  266. // Build parameters for InDataExchange command to authenticate MiFare card.
  267. uint8_t response[1] = {0xFF};
  268. uint8_t params[3 + MIFARE_UID_MAX_LENGTH + MIFARE_KEY_LENGTH];
  269. params[0] = 0x01;
  270. params[1] = key_number & 0xFF;
  271. params[2] = block_number & 0xFF;
  272. // params[3:3+keylen] = key
  273. for (uint8_t i = 0; i < MIFARE_KEY_LENGTH; i++) {
  274. params[3 + i] = key[i];
  275. }
  276. // params[3+keylen:] = uid
  277. for (uint8_t i = 0; i < uid_length; i++) {
  278. params[3 + MIFARE_KEY_LENGTH + i] = uid[i];
  279. }
  280. // Send InDataExchange request
  281. PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, response, sizeof(response),
  282. params, 3 + MIFARE_KEY_LENGTH + uid_length, PN532_DEFAULT_TIMEOUT);
  283. return response[0];
  284. }
  285. /**
  286. * @brief: Read a block of data from the card. Block number should be the block
  287. * to read.
  288. * @param response: buffer of length 16 returned if the block is successfully read.
  289. * @param block_number: specify a block to read.
  290. * @retval: PN532 error code.
  291. */
  292. int PN532_MifareClassicReadBlock(PN532* pn532, uint8_t* response, uint16_t block_number) {
  293. uint8_t params[] = {0x01, MIFARE_CMD_READ, block_number & 0xFF};
  294. uint8_t buff[MIFARE_BLOCK_LENGTH + 1];
  295. // Send InDataExchange request to read block of MiFare data.
  296. PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, buff, sizeof(buff),
  297. params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  298. // Check first response is 0x00 to show success.
  299. if (buff[0] != PN532_ERROR_NONE) {
  300. return buff[0];
  301. }
  302. for (uint8_t i = 0; i < MIFARE_BLOCK_LENGTH; i++) {
  303. response[i] = buff[i + 1];
  304. }
  305. return buff[0];
  306. }
  307. /**
  308. * @brief: Write a block of data to the card. Block number should be the block
  309. * to write and data should be a byte array of length 16 with the data to
  310. * write.
  311. * @param data: data to write.
  312. * @param block_number: specify a block to write.
  313. * @retval: PN532 error code.
  314. */
  315. int PN532_MifareClassicWriteBlock(PN532* pn532, uint8_t* data, uint16_t block_number) {
  316. uint8_t params[MIFARE_BLOCK_LENGTH + 3];
  317. uint8_t response[1];
  318. params[0] = 0x01; // Max card numbers
  319. params[1] = MIFARE_CMD_WRITE;
  320. params[2] = block_number & 0xFF;
  321. for (uint8_t i = 0; i < MIFARE_BLOCK_LENGTH; i++) {
  322. params[3 + i] = data[i];
  323. }
  324. PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, response,
  325. sizeof(response), params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  326. return response[0];
  327. }
  328. /**
  329. * @brief: Read a block of data from the card. Block number should be the block
  330. * to read.
  331. * @param response: buffer of length 4 returned if the block is successfully read.
  332. * @param block_number: specify a block to read.
  333. * @retval: PN532 error code.
  334. */
  335. int PN532_Ntag2xxReadBlock(PN532* pn532, uint8_t* response, uint16_t block_number) {
  336. uint8_t params[] = {0x01, MIFARE_CMD_READ, block_number & 0xFF};
  337. // The response length of NTAG2xx is same as Mifare's
  338. uint8_t buff[MIFARE_BLOCK_LENGTH + 1];
  339. // Send InDataExchange request to read block of MiFare data.
  340. PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, buff, sizeof(buff),
  341. params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  342. // Check first response is 0x00 to show success.
  343. if (buff[0] != PN532_ERROR_NONE) {
  344. return buff[0];
  345. }
  346. // Although the response length of NTAG2xx is same as Mifare's,
  347. // only the first 4 bytes are available
  348. for (uint8_t i = 0; i < NTAG2XX_BLOCK_LENGTH; i++) {
  349. response[i] = buff[i + 1];
  350. }
  351. return buff[0];
  352. }
  353. /**
  354. * @brief: Write a block of data to the card. Block number should be the block
  355. * to write and data should be a byte array of length 4 with the data to
  356. * write.
  357. * @param data: data to write.
  358. * @param block_number: specify a block to write.
  359. * @retval: PN532 error code.
  360. */
  361. int PN532_Ntag2xxWriteBlock(PN532* pn532, uint8_t* data, uint16_t block_number) {
  362. uint8_t params[NTAG2XX_BLOCK_LENGTH + 3];
  363. uint8_t response[1];
  364. params[0] = 0x01; // Max card numbers
  365. params[1] = MIFARE_ULTRALIGHT_CMD_WRITE;
  366. params[2] = block_number & 0xFF;
  367. for (uint8_t i = 0; i < NTAG2XX_BLOCK_LENGTH; i++) {
  368. params[3 + i] = data[i];
  369. }
  370. PN532_CallFunction(pn532, PN532_COMMAND_INDATAEXCHANGE, response,
  371. sizeof(response), params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  372. return response[0];
  373. }
  374. /**
  375. * @brief: Read the GPIO states.
  376. * @param pin_state: pin state buffer (3 bytes) returned.
  377. * returns 3 bytes containing the pin state where:
  378. * P3[0] = P30, P7[0] = 0, I[0] = I0,
  379. * P3[1] = P31, P7[1] = P71, I[1] = I1,
  380. * P3[2] = P32, P7[2] = P72, I[2] = 0,
  381. * P3[3] = P33, P7[3] = 0, I[3] = 0,
  382. * P3[4] = P34, P7[4] = 0, I[4] = 0,
  383. * P3[5] = P35, P7[5] = 0, I[5] = 0,
  384. * P3[6] = 0, P7[6] = 0, I[6] = 0,
  385. * P3[7] = 0, P7[7] = 0, I[7] = 0,
  386. * @retval: -1 if error
  387. */
  388. int PN532_ReadGpio(PN532* pn532, uint8_t* pins_state) {
  389. return PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state, 3,
  390. NULL, 0, PN532_DEFAULT_TIMEOUT);
  391. }
  392. /**
  393. * @brief: Read the GPIO state of specified pins in (P30 ... P35).
  394. * @param pin_number: specify the pin to read.
  395. * @retval: true if HIGH, false if LOW
  396. */
  397. bool PN532_ReadGpioP(PN532* pn532, uint8_t pin_number) {
  398. uint8_t pins_state[3];
  399. PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state,
  400. sizeof(pins_state), NULL, 0, PN532_DEFAULT_TIMEOUT);
  401. if ((pin_number >= 30) && (pin_number <= 37)) {
  402. return (pins_state[0] >> (pin_number - 30)) & 1 ? true : false;
  403. }
  404. if ((pin_number >= 70) && (pin_number <= 77)) {
  405. return (pins_state[1] >> (pin_number - 70)) & 1 ? true : false;
  406. }
  407. return false;
  408. }
  409. /**
  410. * @brief: Read the GPIO state of I0 or I1 pin.
  411. * @param pin_number: specify the pin to read.
  412. * @retval: true if HIGH, false if LOW
  413. */
  414. bool PN532_ReadGpioI(PN532* pn532, uint8_t pin_number) {
  415. uint8_t pins_state[3];
  416. PN532_CallFunction(pn532, PN532_COMMAND_READGPIO, pins_state,
  417. sizeof(pins_state), NULL, 0, PN532_DEFAULT_TIMEOUT);
  418. if (pin_number <= 7) {
  419. return (pins_state[2] >> pin_number) & 1 ? true : false;
  420. }
  421. return false;
  422. }
  423. /**
  424. * @brief: Write the GPIO states.
  425. * @param pins_state: pin state buffer (2 bytes) to write.
  426. * no need to read pin states before write with the param pin_state
  427. * P3 = pin_state[0], P7 = pin_state[1]
  428. * bits:
  429. * P3[0] = P30, P7[0] = 0,
  430. * P3[1] = P31, P7[1] = P71,
  431. * P3[2] = P32, P7[2] = P72,
  432. * P3[3] = P33, P7[3] = nu,
  433. * P3[4] = P34, P7[4] = nu,
  434. * P3[5] = P35, P7[5] = nu,
  435. * P3[6] = nu, P7[6] = nu,
  436. * P3[7] = Val, P7[7] = Val,
  437. * For each port that is validated (bit Val = 1), all the bits are applied
  438. * simultaneously. It is not possible for example to modify the state of
  439. * the port P32 without applying a value to the ports P30, P31, P33, P34
  440. * and P35.
  441. * @retval: -1 if error
  442. */
  443. int PN532_WriteGpio(PN532* pn532, uint8_t* pins_state) {
  444. uint8_t params[2];
  445. // 0x80, the validation bit.
  446. params[0] = 0x80 | pins_state[0];
  447. params[1] = 0x80 | pins_state[1];
  448. return PN532_CallFunction(pn532, PN532_COMMAND_WRITEGPIO, NULL, 0,
  449. params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  450. }
  451. /**
  452. * @brief: Write the specified pin with given states.
  453. * @param pin_number: specify the pin to write.
  454. * @param pin_state: specify the pin state. true for HIGH, false for LOW.
  455. * @retval: -1 if error
  456. */
  457. int PN532_WriteGpioP(PN532* pn532, uint8_t pin_number, bool pin_state) {
  458. uint8_t pins_state[2];
  459. uint8_t params[2];
  460. if (PN532_ReadGpio(pn532, pins_state) == PN532_STATUS_ERROR) {
  461. return PN532_STATUS_ERROR;
  462. }
  463. if ((pin_number >= 30) && (pin_number <= 37)) {
  464. if (pin_state) {
  465. params[0] = 0x80 | pins_state[0] | 1 << (pin_number - 30);
  466. } else {
  467. params[0] = (0x80 | pins_state[0]) & ~(1 << (pin_number - 30));
  468. }
  469. params[1] = 0x00; // leave p7 unchanged
  470. }
  471. if ((pin_number >= 70) && (pin_number <= 77)) {
  472. if (pin_state) {
  473. params[1] = 0x80 | pins_state[1] | 1 << (pin_number - 70);
  474. } else {
  475. params[1] = (0x80 | pins_state[1]) & ~(1 << (pin_number - 70));
  476. }
  477. params[0] = 0x00; // leave p3 unchanged
  478. }
  479. return PN532_CallFunction(pn532, PN532_COMMAND_WRITEGPIO, NULL, 0,
  480. params, sizeof(params), PN532_DEFAULT_TIMEOUT);
  481. }