forked from adafruit/Adafruit_NFCShield_I2C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Adafruit_NFCShield_I2C.cpp
executable file
·1226 lines (1031 loc) · 38.3 KB
/
Adafruit_NFCShield_I2C.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/*!
@file Adafruit_NFCShield_I2C.cpp
@author Adafruit Industries
@license BSD (see license.txt)
I2C Driver for NXP's PN532 NFC/13.56MHz RFID Transceiver
This is a library for the Adafruit PN532 NFC/RFID shields
This library works with the Adafruit NFC breakout
----> https://www.adafruit.com/products/364
Check out the links above for our tutorials and wiring diagrams
These chips use I2C to communicate
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
@section HISTORY
v1.4 - Added setPassiveActivationRetries()
v1.3 - Modified to work with I2C
v1.2 - Added writeGPIO()
- Added readGPIO()
v1.1 - Changed readPassiveTargetID() to handle multiple UID sizes
- Added the following helper functions for text display
static void PrintHex(const byte * data, const uint32_t numBytes)
static void PrintHexChar(const byte * pbtData, const uint32_t numBytes)
- Added the following Mifare Classic functions:
bool mifareclassic_IsFirstBlock (uint32_t uiBlock)
bool mifareclassic_IsTrailerBlock (uint32_t uiBlock)
uint8_t mifareclassic_AuthenticateBlock (uint8_t * uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t * keyData)
uint8_t mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data)
uint8_t mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t * data)
- Added the following Mifare Ultalight functions:
uint8_t mifareultralight_ReadPage (uint8_t page, uint8_t * buffer)
*/
/**************************************************************************/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Wire.h>
#ifdef __AVR__
#define WIRE Wire
#else // Arduino Due
#define WIRE Wire1
#endif
#include "Adafruit_NFCShield_I2C.h"
byte pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
byte pn532response_firmwarevers[] = {0x00, 0xFF, 0x06, 0xFA, 0xD5, 0x03};
// Uncomment these lines to enable debug output for PN532(I2C) and/or MIFARE related code
// #define PN532DEBUG
// #define MIFAREDEBUG
#define PN532_PACKBUFFSIZ 64
byte pn532_packetbuffer[PN532_PACKBUFFSIZ];
/**************************************************************************/
/*!
@brief Sends a single byte via I2C
@param x The byte to send
*/
/**************************************************************************/
static inline void wiresend(uint8_t x)
{
#if ARDUINO >= 100
WIRE.write((uint8_t)x);
#else
WIRE.send(x);
#endif
}
/**************************************************************************/
/*!
@brief Reads a single byte via I2C
*/
/**************************************************************************/
static inline uint8_t wirerecv(void)
{
#if ARDUINO >= 100
return WIRE.read();
#else
return WIRE.receive();
#endif
}
/**************************************************************************/
/*!
@brief Instantiates a new PN532 class
@param irq Location of the IRQ pin
@param reset Location of the RSTPD_N pin
*/
/**************************************************************************/
Adafruit_NFCShield_I2C::Adafruit_NFCShield_I2C(uint8_t irq, uint8_t reset) {
_irq = irq;
_reset = reset;
pinMode(_irq, INPUT);
pinMode(_reset, OUTPUT);
}
/**************************************************************************/
/*!
@brief Setups the HW
*/
/**************************************************************************/
void Adafruit_NFCShield_I2C::begin() {
WIRE.begin();
// Reset the PN532
digitalWrite(_reset, HIGH);
digitalWrite(_reset, LOW);
delay(400);
digitalWrite(_reset, HIGH);
}
/**************************************************************************/
/*!
@brief Prints a hexadecimal value in plain characters
@param data Pointer to the byte data
@param numBytes Data length in bytes
*/
/**************************************************************************/
void Adafruit_NFCShield_I2C::PrintHex(const byte * data, const uint32_t numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
Serial.print("0x");
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos]&0xff, HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.println("");
}
/**************************************************************************/
/*!
@brief Prints a hexadecimal value in plain characters, along with
the char equivalents in the following format
00 00 00 00 00 00 ......
@param data Pointer to the byte data
@param numBytes Data length in bytes
*/
/**************************************************************************/
void Adafruit_NFCShield_I2C::PrintHexChar(const byte * data, const uint32_t numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos], HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.print(" ");
for (szPos=0; szPos < numBytes; szPos++)
{
if (data[szPos] <= 0x1F)
Serial.print(".");
else
Serial.print((char)data[szPos]);
}
Serial.println("");
}
/**************************************************************************/
/*!
@brief Checks the firmware version of the PN5xx chip
@returns The chip's firmware version and ID
*/
/**************************************************************************/
uint32_t Adafruit_NFCShield_I2C::getFirmwareVersion(void) {
uint32_t response;
pn532_packetbuffer[0] = PN532_COMMAND_GETFIRMWAREVERSION;
if (! sendCommandCheckAck(pn532_packetbuffer, 1))
return 0;
// read data packet
wirereaddata(pn532_packetbuffer, 12);
// check some basic stuff
if (0 != strncmp((char *)pn532_packetbuffer, (char *)pn532response_firmwarevers, 6)) {
#ifdef PN532DEBUG
Serial.println("Firmware doesn't match!");
#endif
return 0;
}
response = pn532_packetbuffer[7];
response <<= 8;
response |= pn532_packetbuffer[8];
response <<= 8;
response |= pn532_packetbuffer[9];
response <<= 8;
response |= pn532_packetbuffer[10];
return response;
}
/**************************************************************************/
/*!
@brief Sends a command and waits a specified period for the ACK
@param cmd Pointer to the command buffer
@param cmdlen The size of the command in bytes
@param timeout timeout before giving up
@returns 1 if everything is OK, 0 if timeout occured before an
ACK was recieved
*/
/**************************************************************************/
// default timeout of one second
boolean Adafruit_NFCShield_I2C::sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout) {
uint16_t timer = 0;
// write the command
wiresendcommand(cmd, cmdlen);
// Wait for chip to say its ready!
while (wirereadstatus() != PN532_I2C_READY) {
if (timeout != 0) {
timer+=10;
if (timer > timeout)
return false;
}
delay(10);
}
#ifdef PN532DEBUG
Serial.println("IRQ received");
#endif
// read acknowledgement
if (!readackframe()) {
#ifdef PN532DEBUG
Serial.println("No ACK frame received!");
#endif
return false;
}
return true; // ack'd command
}
/**************************************************************************/
/*!
Writes an 8-bit value that sets the state of the PN532's GPIO pins
@warning This function is provided exclusively for board testing and
is dangerous since it will throw an error if any pin other
than the ones marked "Can be used as GPIO" are modified! All
pins that can not be used as GPIO should ALWAYS be left high
(value = 1) or the system will become unstable and a HW reset
will be required to recover the PN532.
pinState[0] = P30 Can be used as GPIO
pinState[1] = P31 Can be used as GPIO
pinState[2] = P32 *** RESERVED (Must be 1!) ***
pinState[3] = P33 Can be used as GPIO
pinState[4] = P34 *** RESERVED (Must be 1!) ***
pinState[5] = P35 Can be used as GPIO
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
boolean Adafruit_NFCShield_I2C::writeGPIO(uint8_t pinstate) {
uint8_t errorbit;
// Make sure pinstate does not try to toggle P32 or P34
pinstate |= (1 << PN532_GPIO_P32) | (1 << PN532_GPIO_P34);
// Fill command buffer
pn532_packetbuffer[0] = PN532_COMMAND_WRITEGPIO;
pn532_packetbuffer[1] = PN532_GPIO_VALIDATIONBIT | pinstate; // P3 Pins
pn532_packetbuffer[2] = 0x00; // P7 GPIO Pins (not used ... taken by I2C)
#ifdef PN532DEBUG
Serial.print("Writing P3 GPIO: "); Serial.println(pn532_packetbuffer[1], HEX);
#endif
// Send the WRITEGPIO command (0x0E)
if (! sendCommandCheckAck(pn532_packetbuffer, 3))
return 0x0;
// Read response packet (00 00 FF PLEN PLENCHECKSUM D5 CMD+1(0x0F) DATACHECKSUM)
wirereaddata(pn532_packetbuffer, 8);
#ifdef PN532DEBUG
Serial.print("Received: ");
PrintHex(pn532_packetbuffer, 8);
Serial.println("");
#endif
return (pn532_packetbuffer[6] == 0x0F);
}
/**************************************************************************/
/*!
Reads the state of the PN532's GPIO pins
@returns An 8-bit value containing the pin state where:
pinState[0] = P30
pinState[1] = P31
pinState[2] = P32
pinState[3] = P33
pinState[4] = P34
pinState[5] = P35
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::readGPIO(void) {
pn532_packetbuffer[0] = PN532_COMMAND_READGPIO;
// Send the READGPIO command (0x0C)
if (! sendCommandCheckAck(pn532_packetbuffer, 1))
return 0x0;
// Read response packet (00 00 FF PLEN PLENCHECKSUM D5 CMD+1(0x0D) P3 P7 IO1 DATACHECKSUM)
wirereaddata(pn532_packetbuffer, 11);
/* READGPIO response should be in the following format:
byte Description
------------- ------------------------------------------
b0..6 Frame header and preamble
b7 P3 GPIO Pins
b8 P7 GPIO Pins (not used ... taken by I2C)
b9 Interface Mode Pins (not used ... bus select pins)
b10 checksum */
#ifdef PN532DEBUG
Serial.print("Received: ");
PrintHex(pn532_packetbuffer, 11);
Serial.println("");
Serial.print("P3 GPIO: 0x"); Serial.println(pn532_packetbuffer[7], HEX);
Serial.print("P7 GPIO: 0x"); Serial.println(pn532_packetbuffer[8], HEX);
Serial.print("IO GPIO: 0x"); Serial.println(pn532_packetbuffer[9], HEX);
// Note: You can use the IO GPIO value to detect the serial bus being used
switch(pn532_packetbuffer[9])
{
case 0x00: // Using UART
Serial.println("Using UART (IO = 0x00)");
break;
case 0x01: // Using I2C
Serial.println("Using I2C (IO = 0x01)");
break;
case 0x02: // Using I2C
Serial.println("Using I2C (IO = 0x02)");
break;
}
#endif
return pn532_packetbuffer[6];
}
/**************************************************************************/
/*!
@brief Configures the SAM (Secure Access Module)
*/
/**************************************************************************/
boolean Adafruit_NFCShield_I2C::SAMConfig(void) {
pn532_packetbuffer[0] = PN532_COMMAND_SAMCONFIGURATION;
pn532_packetbuffer[1] = 0x01; // normal mode;
pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
pn532_packetbuffer[3] = 0x01; // use IRQ pin!
if (! sendCommandCheckAck(pn532_packetbuffer, 4))
return false;
// read data packet
wirereaddata(pn532_packetbuffer, 8);
return (pn532_packetbuffer[6] == 0x15);
}
/**************************************************************************/
/*!
Sets the MxRtyPassiveActivation byte of the RFConfiguration register
@param maxRetries 0xFF to wait forever, 0x00..0xFE to timeout
after mxRetries
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
boolean Adafruit_NFCShield_I2C::setPassiveActivationRetries(uint8_t maxRetries) {
pn532_packetbuffer[0] = PN532_COMMAND_RFCONFIGURATION;
pn532_packetbuffer[1] = 5; // Config item 5 (MaxRetries)
pn532_packetbuffer[2] = 0xFF; // MxRtyATR (default = 0xFF)
pn532_packetbuffer[3] = 0x01; // MxRtyPSL (default = 0x01)
pn532_packetbuffer[4] = maxRetries;
#ifdef MIFAREDEBUG
Serial.print("Setting MxRtyPassiveActivation to "); Serial.print(maxRetries, DEC); Serial.println(" ");
#endif
if (! sendCommandCheckAck(pn532_packetbuffer, 5))
return 0x0; // no ACK
return 1;
}
/***** ISO14443A Commands ******/
/**************************************************************************/
/*!
Waits for an ISO14443A target to enter the field
@param cardBaudRate Baud rate of the card
@param uid Pointer to the array that will be populated
with the card's UID (up to 7 bytes)
@param uidLength Pointer to the variable that will hold the
length of the card's UID.
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
boolean Adafruit_NFCShield_I2C::readPassiveTargetID(uint8_t cardbaudrate, uint8_t * uid, uint8_t * uidLength) {
pn532_packetbuffer[0] = PN532_COMMAND_INLISTPASSIVETARGET;
pn532_packetbuffer[1] = 1; // max 1 cards at once (we can set this to 2 later)
pn532_packetbuffer[2] = cardbaudrate;
if (! sendCommandCheckAck(pn532_packetbuffer, 3))
{
#ifdef PN532DEBUG
Serial.println("No card(s) read");
#endif
return 0x0; // no cards read
}
// Wait for a card to enter the field
uint8_t status = PN532_I2C_BUSY;
#ifdef PN532DEBUG
Serial.println("Waiting for IRQ (indicates card presence)");
#endif
while (wirereadstatus() != PN532_I2C_READY)
{
delay(10);
}
#ifdef PN532DEBUG
Serial.println("Found a card");
#endif
// read data packet
wirereaddata(pn532_packetbuffer, 20);
// check some basic stuff
/* ISO14443A card response should be in the following format:
byte Description
------------- ------------------------------------------
b0..6 Frame header and preamble
b7 Tags Found
b8 Tag Number (only one used in this example)
b9..10 SENS_RES
b11 SEL_RES
b12 NFCID Length
b13..NFCIDLen NFCID */
#ifdef MIFAREDEBUG
Serial.print("Found "); Serial.print(pn532_packetbuffer[7], DEC); Serial.println(" tags");
#endif
if (pn532_packetbuffer[7] != 1)
return 0;
uint16_t sens_res = pn532_packetbuffer[9];
sens_res <<= 8;
sens_res |= pn532_packetbuffer[10];
#ifdef MIFAREDEBUG
Serial.print("ATQA: 0x"); Serial.println(sens_res, HEX);
Serial.print("SAK: 0x"); Serial.println(pn532_packetbuffer[11], HEX);
#endif
/* Card appears to be Mifare Classic */
*uidLength = pn532_packetbuffer[12];
#ifdef MIFAREDEBUG
Serial.print("UID:");
#endif
for (uint8_t i=0; i < pn532_packetbuffer[12]; i++)
{
uid[i] = pn532_packetbuffer[13+i];
#ifdef MIFAREDEBUG
Serial.print(" 0x");Serial.print(uid[i], HEX);
#endif
}
#ifdef MIFAREDEBUG
Serial.println();
#endif
return 1;
}
/***** Mifare Classic Functions ******/
/**************************************************************************/
/*!
Indicates whether the specified block number is the first block
in the sector (block 0 relative to the current sector)
*/
/**************************************************************************/
bool Adafruit_NFCShield_I2C::mifareclassic_IsFirstBlock (uint32_t uiBlock)
{
// Test if we are in the small or big sectors
if (uiBlock < 128)
return ((uiBlock) % 4 == 0);
else
return ((uiBlock) % 16 == 0);
}
/**************************************************************************/
/*!
Indicates whether the specified block number is the sector trailer
*/
/**************************************************************************/
bool Adafruit_NFCShield_I2C::mifareclassic_IsTrailerBlock (uint32_t uiBlock)
{
// Test if we are in the small or big sectors
if (uiBlock < 128)
return ((uiBlock + 1) % 4 == 0);
else
return ((uiBlock + 1) % 16 == 0);
}
/**************************************************************************/
/*!
Tries to authenticate a block of memory on a MIFARE card using the
INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual
for more information on sending MIFARE and other commands.
@param uid Pointer to a byte array containing the card UID
@param uidLen The length (in bytes) of the card's UID (Should
be 4 for MIFARE Classic)
@param blockNumber The block number to authenticate. (0..63 for
1KB cards, and 0..255 for 4KB cards).
@param keyNumber Which key type to use during authentication
(0 = MIFARE_CMD_AUTH_A, 1 = MIFARE_CMD_AUTH_B)
@param keyData Pointer to a byte array containing the 6 byte
key value
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareclassic_AuthenticateBlock (uint8_t * uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t * keyData)
{
uint8_t len;
uint8_t i;
// Hang on to the key and uid data
memcpy (_key, keyData, 6);
memcpy (_uid, uid, uidLen);
_uidLen = uidLen;
#ifdef MIFAREDEBUG
Serial.print("Trying to authenticate card ");
Adafruit_NFCShield_I2C::PrintHex(_uid, _uidLen);
Serial.print("Using authentication KEY ");Serial.print(keyNumber ? 'B' : 'A');Serial.print(": ");
Adafruit_NFCShield_I2C::PrintHex(_key, 6);
#endif
// Prepare the authentication command //
pn532_packetbuffer[0] = PN532_COMMAND_INDATAEXCHANGE; /* Data Exchange Header */
pn532_packetbuffer[1] = 1; /* Max card numbers */
pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_B : MIFARE_CMD_AUTH_A;
pn532_packetbuffer[3] = blockNumber; /* Block Number (1K = 0..63, 4K = 0..255 */
memcpy (pn532_packetbuffer+4, _key, 6);
for (i = 0; i < _uidLen; i++)
{
pn532_packetbuffer[10+i] = _uid[i]; /* 4 byte card ID */
}
if (! sendCommandCheckAck(pn532_packetbuffer, 10+_uidLen))
return 0;
// Read the response packet
wirereaddata(pn532_packetbuffer, 12);
// Check if the response is valid and we are authenticated???
// for an auth success it should be bytes 5-7: 0xD5 0x41 0x00
// Mifare auth error is technically byte 7: 0x14 but anything other and 0x00 is not good
if (pn532_packetbuffer[7] != 0x00)
{
#ifdef PN532DEBUG
Serial.print("Authentification failed: ");
Adafruit_PN532::PrintHexChar(pn532_packetbuffer, 12);
#endif
return 0;
}
return 1;
}
/**************************************************************************/
/*!
Tries to read an entire 16-byte data block at the specified block
address.
@param blockNumber The block number to authenticate. (0..63 for
1KB cards, and 0..255 for 4KB cards).
@param data Pointer to the byte array that will hold the
retrieved data (if any)
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data)
{
#ifdef MIFAREDEBUG
Serial.print("Trying to read 16 bytes from block ");Serial.println(blockNumber);
#endif
/* Prepare the command */
pn532_packetbuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
pn532_packetbuffer[1] = 1; /* Card number */
pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */
pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */
/* Send the command */
if (! sendCommandCheckAck(pn532_packetbuffer, 4))
{
#ifdef MIFAREDEBUG
Serial.println("Failed to receive ACK for read command");
#endif
return 0;
}
/* Read the response packet */
wirereaddata(pn532_packetbuffer, 26);
/* If byte 8 isn't 0x00 we probably have an error */
if (pn532_packetbuffer[7] != 0x00)
{
#ifdef MIFAREDEBUG
Serial.println("Unexpected response");
Adafruit_NFCShield_I2C::PrintHexChar(pn532_packetbuffer, 26);
#endif
return 0;
}
/* Copy the 16 data bytes to the output buffer */
/* Block content starts at byte 9 of a valid response */
memcpy (data, pn532_packetbuffer+8, 16);
/* Display data for debug if requested */
#ifdef MIFAREDEBUG
Serial.print("Block ");
Serial.println(blockNumber);
Adafruit_NFCShield_I2C::PrintHexChar(data, 16);
#endif
return 1;
}
/**************************************************************************/
/*!
Tries to write an entire 16-byte data block at the specified block
address.
@param blockNumber The block number to authenticate. (0..63 for
1KB cards, and 0..255 for 4KB cards).
@param data The byte array that contains the data to write.
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t * data)
{
#ifdef MIFAREDEBUG
Serial.print("Trying to write 16 bytes to block ");Serial.println(blockNumber);
#endif
/* Prepare the first command */
pn532_packetbuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
pn532_packetbuffer[1] = 1; /* Card number */
pn532_packetbuffer[2] = MIFARE_CMD_WRITE; /* Mifare Write command = 0xA0 */
pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */
memcpy (pn532_packetbuffer+4, data, 16); /* Data Payload */
/* Send the command */
if (! sendCommandCheckAck(pn532_packetbuffer, 20))
{
#ifdef MIFAREDEBUG
Serial.println("Failed to receive ACK for write command");
#endif
return 0;
}
delay(10);
/* Read the response packet */
wirereaddata(pn532_packetbuffer, 26);
return 1;
}
/**************************************************************************/
/*!
Formats a Mifare Classic card to store NDEF Records
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareclassic_FormatNDEF (void)
{
uint8_t sectorbuffer1[16] = {0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
uint8_t sectorbuffer2[16] = {0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
uint8_t sectorbuffer3[16] = {0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77, 0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// Note 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 must be used for key A
// for the MAD sector in NDEF records (sector 0)
// Write block 1 and 2 to the card
if (!(mifareclassic_WriteDataBlock (1, sectorbuffer1)))
return 0;
if (!(mifareclassic_WriteDataBlock (2, sectorbuffer2)))
return 0;
// Write key A and access rights card
if (!(mifareclassic_WriteDataBlock (3, sectorbuffer3)))
return 0;
// Seems that everything was OK (?!)
return 1;
}
/**************************************************************************/
/*!
Writes an NDEF URI Record to the specified sector (1..15)
Note that this function assumes that the Mifare Classic card is
already formatted to work as an "NFC Forum Tag" and uses a MAD1
file system. You can use the NXP TagWriter app on Android to
properly format cards for this.
@param sectorNumber The sector that the URI record should be written
to (can be 1..15 for a 1K card)
@param uriIdentifier The uri identifier code (0 = none, 0x01 =
"http://www.", etc.)
@param url The uri text to write (max 38 characters).
@returns 1 if everything executed properly, 0 for an error
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareclassic_WriteNDEFURI (uint8_t sectorNumber, uint8_t uriIdentifier, const char * url)
{
// Figure out how long the string is
uint8_t len = strlen(url);
// Make sure we're within a 1K limit for the sector number
if ((sectorNumber < 1) || (sectorNumber > 15))
return 0;
// Make sure the URI payload is between 1 and 38 chars
if ((len < 1) || (len > 38))
return 0;
// Note 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 must be used for key A
// in NDEF records
// Setup the sector buffer (w/pre-formatted TLV wrapper and NDEF message)
uint8_t sectorbuffer1[16] = {0x00, 0x00, 0x03, len+5, 0xD1, 0x01, len+1, 0x55, uriIdentifier, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t sectorbuffer2[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t sectorbuffer3[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
if (len <= 6)
{
// Unlikely we'll get a url this short, but why not ...
memcpy (sectorbuffer1+9, url, len);
sectorbuffer1[len+9] = 0xFE;
}
else if (len == 7)
{
// 0xFE needs to be wrapped around to next block
memcpy (sectorbuffer1+9, url, len);
sectorbuffer2[0] = 0xFE;
}
else if ((len > 7) || (len <= 22))
{
// Url fits in two blocks
memcpy (sectorbuffer1+9, url, 7);
memcpy (sectorbuffer2, url+7, len-7);
sectorbuffer2[len-7] = 0xFE;
}
else if (len == 23)
{
// 0xFE needs to be wrapped around to final block
memcpy (sectorbuffer1+9, url, 7);
memcpy (sectorbuffer2, url+7, len-7);
sectorbuffer3[0] = 0xFE;
}
else
{
// Url fits in three blocks
memcpy (sectorbuffer1+9, url, 7);
memcpy (sectorbuffer2, url+7, 16);
memcpy (sectorbuffer3, url+23, len-24);
sectorbuffer3[len-22] = 0xFE;
}
// Now write all three blocks back to the card
if (!(mifareclassic_WriteDataBlock (sectorNumber*4, sectorbuffer1)))
return 0;
if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+1, sectorbuffer2)))
return 0;
if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+2, sectorbuffer3)))
return 0;
if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+3, sectorbuffer4)))
return 0;
// Seems that everything was OK (?!)
return 1;
}
/***** Mifare Ultralight Functions ******/
/**************************************************************************/
/*!
Tries to read an entire 4-byte page at the specified address.
@param page The page number (0..63 in most cases)
@param buffer Pointer to the byte array that will hold the
retrieved data (if any)
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::mifareultralight_ReadPage (uint8_t page, uint8_t * buffer)
{
if (page >= 64)
{
#ifdef MIFAREDEBUG
Serial.println("Page value out of range");
#endif
return 0;
}
#ifdef MIFAREDEBUG
Serial.print("Reading page ");Serial.println(page);
#endif
/* Prepare the command */
pn532_packetbuffer[0] = PN532_COMMAND_INDATAEXCHANGE;
pn532_packetbuffer[1] = 1; /* Card number */
pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */
pn532_packetbuffer[3] = page; /* Page Number (0..63 in most cases) */
/* Send the command */
if (! sendCommandCheckAck(pn532_packetbuffer, 4))
{
#ifdef MIFAREDEBUG
Serial.println("Failed to receive ACK for write command");
#endif
return 0;
}
/* Read the response packet */
wirereaddata(pn532_packetbuffer, 26);
#ifdef MIFAREDEBUG
Serial.println("Received: ");
Adafruit_NFCShield_I2C::PrintHexChar(pn532_packetbuffer, 26);
#endif
/* If byte 8 isn't 0x00 we probably have an error */
if (pn532_packetbuffer[7] == 0x00)
{
/* Copy the 4 data bytes to the output buffer */
/* Block content starts at byte 9 of a valid response */
/* Note that the command actually reads 16 byte or 4 */
/* pages at a time ... we simply discard the last 12 */
/* bytes */
memcpy (buffer, pn532_packetbuffer+8, 4);
}
else
{
#ifdef MIFAREDEBUG
Serial.println("Unexpected response reading block: ");
Adafruit_NFCShield_I2C::PrintHexChar(pn532_packetbuffer, 26);
#endif
return 0;
}
/* Display data for debug if requested */
#ifdef MIFAREDEBUG
Serial.print("Page ");Serial.print(page);Serial.println(":");
Adafruit_NFCShield_I2C::PrintHexChar(buffer, 4);
#endif
// Return OK signal
return 1;
}
/************** high level I2C */
/**************************************************************************/
/*!
@brief Tries to read the PN532 ACK frame (not to be confused with
the I2C ACK signal)
*/
/**************************************************************************/
boolean Adafruit_NFCShield_I2C::readackframe(void) {
uint8_t ackbuff[6];
wirereaddata(ackbuff, 6);
return (0 == strncmp((char *)ackbuff, (char *)pn532ack, 6));
}
/************** mid level I2C */
/**************************************************************************/
/*!
@brief Checks the IRQ pin to know if the PN532 is ready
@returns 0 if the PN532 is busy, 1 if it is free
*/
/**************************************************************************/
uint8_t Adafruit_NFCShield_I2C::wirereadstatus(void) {
uint8_t x = digitalRead(_irq);
if (x == 1)
return PN532_I2C_BUSY;
else
return PN532_I2C_READY;
}
/**************************************************************************/
/*!
@brief Reads n bytes of data from the PN532 via I2C
@param buff Pointer to the buffer where data will be written
@param n Number of bytes to be read
*/
/**************************************************************************/
void Adafruit_NFCShield_I2C::wirereaddata(uint8_t* buff, uint8_t n) {
uint16_t timer = 0;
delay(2);
#ifdef PN532DEBUG
Serial.print("Reading: ");
#endif
// Start read (n+1 to take into account leading 0x01 with I2C)
WIRE.requestFrom((uint8_t)PN532_I2C_ADDRESS, (uint8_t)(n+2));
// Discard the leading 0x01
wirerecv();
for (uint8_t i=0; i<n; i++) {
delay(1);
buff[i] = wirerecv();
#ifdef PN532DEBUG
Serial.print(" 0x");
Serial.print(buff[i], HEX);
#endif
}
// Discard trailing 0x00 0x00
// wirerecv();
#ifdef PN532DEBUG
Serial.println();
#endif
}
/**************************************************************************/
/*!
@brief Writes a command to the PN532, automatically inserting the
preamble and required frame details (checksum, len, etc.)
@param cmd Pointer to the command buffer
@param cmdlen Command length in bytes
*/
/**************************************************************************/
void Adafruit_NFCShield_I2C::wiresendcommand(uint8_t* cmd, uint8_t cmdlen) {
uint8_t checksum;