├── .gitignore ├── NDEF ├── Due.h ├── LICENSE.txt ├── MifareClassic.cpp ├── MifareClassic.h ├── MifareUltralight.cpp ├── MifareUltralight.h ├── Ndef.cpp ├── Ndef.h ├── NdefMessage.cpp ├── NdefMessage.h ├── NdefRecord.cpp ├── NdefRecord.h ├── NfcAdapter.cpp ├── NfcAdapter.h ├── NfcDriver.h ├── NfcTag.cpp ├── NfcTag.h ├── README.md ├── examples │ ├── CleanTag │ │ └── CleanTag.ino │ ├── EraseTag │ │ └── EraseTag.ino │ ├── FormatTag │ │ └── FormatTag.ino │ ├── P2P_Receive │ │ └── P2P_Receive.ino │ ├── P2P_Receive_LCD │ │ └── P2P_Receive_LCD.ino │ ├── P2P_Send │ │ └── P2P_Send.ino │ ├── ReadTag │ │ └── ReadTag.ino │ ├── ReadTagExtended │ │ └── ReadTagExtended.ino │ ├── WriteTag │ │ └── WriteTag.ino │ └── WriteTagMultipleRecords │ │ └── WriteTagMultipleRecords.ino ├── keywords.txt └── tests │ ├── NdefMemoryTest │ └── NdefMemoryTest.ino │ ├── NdefMessageTest │ └── NdefMessageTest.ino │ ├── NdefUnitTest │ └── NdefUnitTest.ino │ └── NfcTagTest │ └── NfcTagTest.ino ├── PN532 ├── PN532.cpp ├── PN532.h ├── PN532Interface.h ├── PN532_debug.h ├── README.md ├── emulatetag.cpp ├── emulatetag.h ├── examples │ ├── FeliCa_card_detection │ │ └── FeliCa_card_detection.pde │ ├── FeliCa_card_read │ │ └── FeliCa_card_read.pde │ ├── android_hce │ │ └── android_hce.ino │ ├── emulate_tag_ndef │ │ └── emulate_tag_ndef.ino │ ├── iso14443a_uid │ │ └── iso14443a_uid.pde │ ├── mifareclassic_formatndef │ │ └── mifareclassic_formatndef.pde │ ├── mifareclassic_memdump │ │ └── mifareclassic_memdump.pde │ ├── mifareclassic_ndeftoclassic │ │ └── mifareclassic_ndeftoclassic.pde │ ├── mifareclassic_updatendef │ │ └── mifareclassic_updatendef.pde │ ├── p2p_raw │ │ └── p2p_raw.ino │ ├── p2p_with_ndef_library │ │ └── p2p_with_ndef_library.ino │ └── readMifare │ │ └── readMifare.pde ├── license.txt ├── llcp.cpp ├── llcp.h ├── mac_link.cpp ├── mac_link.h ├── snep.cpp └── snep.h ├── PN532_HSU ├── PN532_HSU.cpp └── PN532_HSU.h ├── PN532_I2C ├── PN532_I2C.cpp └── PN532_I2C.h ├── PN532_SPI ├── PN532_SPI.cpp └── PN532_SPI.h ├── PN532_SWHSU ├── PN532_SWHSU.cpp └── PN532_SWHSU.h └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /NDEF/Due.h: -------------------------------------------------------------------------------- 1 | // redefine some stuff so code works on Due 2 | // http://arduino.cc/forum/index.php?&topic=153761.0 3 | 4 | #ifndef Due_h 5 | #define Due_h 6 | 7 | #if defined(__SAM3X8E__) 8 | #define PROGMEM 9 | #define pgm_read_byte(x) (*((char *)x)) 10 | // #define pgm_read_word(x) (*((short *)(x & 0xfffffffe))) 11 | #define pgm_read_word(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x))) 12 | #define pgm_read_byte_near(x) (*((char *)x)) 13 | #define pgm_read_byte_far(x) (*((char *)x)) 14 | // #define pgm_read_word_near(x) (*((short *)(x & 0xfffffffe)) 15 | // #define pgm_read_word_far(x) (*((short *)(x & 0xfffffffe))) 16 | #define pgm_read_word_near(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x))) 17 | #define pgm_read_word_far(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x)))) 18 | #define PSTR(x) x 19 | #if defined F 20 | #undef F 21 | #endif 22 | #define F(X) (X) 23 | #endif 24 | 25 | #endif -------------------------------------------------------------------------------- /NDEF/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Software License Agreement (BSD License) 2 | 3 | Copyright (c) 2013-2014, Don Coleman 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holders nor the 17 | names of its contributors may be used to endorse or promote products 18 | derived from this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY 21 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 22 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY 24 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 25 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 26 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 27 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 29 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /NDEF/MifareClassic.cpp: -------------------------------------------------------------------------------- 1 | #include "MifareClassic.h" 2 | 3 | #define BLOCK_SIZE 16 4 | #define LONG_TLV_SIZE 4 5 | #define SHORT_TLV_SIZE 2 6 | 7 | #define MIFARE_CLASSIC ("Mifare Classic") 8 | 9 | MifareClassic::MifareClassic(PN532& nfcShield) 10 | { 11 | _nfcShield = &nfcShield; 12 | } 13 | 14 | MifareClassic::~MifareClassic() 15 | { 16 | } 17 | 18 | NfcTag MifareClassic::read(byte *uid, unsigned int uidLength) 19 | { 20 | uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; 21 | int currentBlock = 4; 22 | int messageStartIndex = 0; 23 | int messageLength = 0; 24 | byte data[BLOCK_SIZE]; 25 | 26 | // read first block to get message length 27 | int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); 28 | if (success) 29 | { 30 | success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, data); 31 | if (success) 32 | { 33 | if (!decodeTlv(data, messageLength, messageStartIndex)) { 34 | return NfcTag(uid, uidLength, "ERROR"); // TODO should the error message go in NfcTag? 35 | } 36 | } 37 | else 38 | { 39 | Serial.print(F("Error. Failed read block "));Serial.println(currentBlock); 40 | return NfcTag(uid, uidLength, MIFARE_CLASSIC); 41 | } 42 | } 43 | else 44 | { 45 | Serial.println(F("Tag is not NDEF formatted.")); 46 | // TODO set tag.isFormatted = false 47 | return NfcTag(uid, uidLength, MIFARE_CLASSIC); 48 | } 49 | 50 | // this should be nested in the message length loop 51 | int index = 0; 52 | int bufferSize = getBufferSize(messageLength); 53 | uint8_t buffer[bufferSize]; 54 | 55 | #ifdef MIFARE_CLASSIC_DEBUG 56 | Serial.print(F("Message Length "));Serial.println(messageLength); 57 | Serial.print(F("Buffer Size "));Serial.println(bufferSize); 58 | #endif 59 | 60 | while (index < bufferSize) 61 | { 62 | 63 | // authenticate on every sector 64 | if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock)) 65 | { 66 | success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); 67 | if (!success) 68 | { 69 | Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock); 70 | // TODO error handling 71 | } 72 | } 73 | 74 | // read the data 75 | success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, &buffer[index]); 76 | if (success) 77 | { 78 | #ifdef MIFARE_CLASSIC_DEBUG 79 | Serial.print(F("Block "));Serial.print(currentBlock);Serial.print(" "); 80 | _nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE); 81 | #endif 82 | } 83 | else 84 | { 85 | Serial.print(F("Read failed "));Serial.println(currentBlock); 86 | // TODO handle errors here 87 | } 88 | 89 | index += BLOCK_SIZE; 90 | currentBlock++; 91 | 92 | // skip the trailer block 93 | if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock)) 94 | { 95 | #ifdef MIFARE_CLASSIC_DEBUG 96 | Serial.print(F("Skipping block "));Serial.println(currentBlock); 97 | #endif 98 | currentBlock++; 99 | } 100 | } 101 | 102 | return NfcTag(uid, uidLength, MIFARE_CLASSIC, &buffer[messageStartIndex], messageLength); 103 | } 104 | 105 | int MifareClassic::getBufferSize(int messageLength) 106 | { 107 | 108 | int bufferSize = messageLength; 109 | 110 | // TLV header is 2 or 4 bytes, TLV terminator is 1 byte. 111 | if (messageLength < 0xFF) 112 | { 113 | bufferSize += SHORT_TLV_SIZE + 1; 114 | } 115 | else 116 | { 117 | bufferSize += LONG_TLV_SIZE + 1; 118 | } 119 | 120 | // bufferSize needs to be a multiple of BLOCK_SIZE 121 | if (bufferSize % BLOCK_SIZE != 0) 122 | { 123 | bufferSize = ((bufferSize / BLOCK_SIZE) + 1) * BLOCK_SIZE; 124 | } 125 | 126 | return bufferSize; 127 | } 128 | 129 | // skip null tlvs (0x0) before the real message 130 | // technically unlimited null tlvs, but we assume 131 | // T & L of TLV in the first block we read 132 | int MifareClassic::getNdefStartIndex(byte *data) 133 | { 134 | 135 | for (int i = 0; i < BLOCK_SIZE; i++) 136 | { 137 | if (data[i] == 0x0) 138 | { 139 | // do nothing, skip 140 | } 141 | else if (data[i] == 0x3) 142 | { 143 | return i; 144 | } 145 | else 146 | { 147 | Serial.print("Unknown TLV ");Serial.println(data[i], HEX); 148 | return -2; 149 | } 150 | } 151 | 152 | return -1; 153 | } 154 | 155 | // Decode the NDEF data length from the Mifare TLV 156 | // Leading null TLVs (0x0) are skipped 157 | // Assuming T & L of TLV will be in the first block 158 | // messageLength and messageStartIndex written to the parameters 159 | // success or failure status is returned 160 | // 161 | // { 0x3, LENGTH } 162 | // { 0x3, 0xFF, LENGTH, LENGTH } 163 | bool MifareClassic::decodeTlv(byte *data, int &messageLength, int &messageStartIndex) 164 | { 165 | int i = getNdefStartIndex(data); 166 | 167 | if (i < 0 || data[i] != 0x3) 168 | { 169 | Serial.println(F("Error. Can't decode message length.")); 170 | return false; 171 | } 172 | else 173 | { 174 | if (data[i+1] == 0xFF) 175 | { 176 | messageLength = ((0xFF & data[i+2]) << 8) | (0xFF & data[i+3]); 177 | messageStartIndex = i + LONG_TLV_SIZE; 178 | } 179 | else 180 | { 181 | messageLength = data[i+1]; 182 | messageStartIndex = i + SHORT_TLV_SIZE; 183 | } 184 | } 185 | 186 | return true; 187 | } 188 | 189 | // Intialized NDEF tag contains one empty NDEF TLV 03 00 FE - AN1304 6.3.1 190 | // We are formatting in read/write mode with a NDEF TLV 03 03 and an empty NDEF record D0 00 00 FE - AN1304 6.3.2 191 | boolean MifareClassic::formatNDEF(byte * uid, unsigned int uidLength) 192 | { 193 | uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; 194 | uint8_t emptyNdefMesg[16] = {0x03, 0x03, 0xD0, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 195 | uint8_t sectorbuffer0[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; 196 | uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; 197 | 198 | boolean success = _nfcShield->mifareclassic_AuthenticateBlock (uid, uidLength, 0, 0, keya); 199 | if (!success) 200 | { 201 | Serial.println(F("Unable to authenticate block 0 to enable card formatting!")); 202 | return false; 203 | } 204 | success = _nfcShield->mifareclassic_FormatNDEF(); 205 | if (!success) 206 | { 207 | Serial.println(F("Unable to format the card for NDEF")); 208 | } 209 | else 210 | { 211 | for (int i=4; i<64; i+=4) { 212 | success = _nfcShield->mifareclassic_AuthenticateBlock (uid, uidLength, i, 0, keya); 213 | 214 | if (success) { 215 | if (i == 4) // special handling for block 4 216 | { 217 | if (!(_nfcShield->mifareclassic_WriteDataBlock (i, emptyNdefMesg))) 218 | { 219 | Serial.print(F("Unable to write block "));Serial.println(i); 220 | } 221 | } 222 | else 223 | { 224 | if (!(_nfcShield->mifareclassic_WriteDataBlock (i, sectorbuffer0))) 225 | { 226 | Serial.print(F("Unable to write block "));Serial.println(i); 227 | } 228 | } 229 | if (!(_nfcShield->mifareclassic_WriteDataBlock (i+1, sectorbuffer0))) 230 | { 231 | Serial.print(F("Unable to write block "));Serial.println(i+1); 232 | } 233 | if (!(_nfcShield->mifareclassic_WriteDataBlock (i+2, sectorbuffer0))) 234 | { 235 | Serial.print(F("Unable to write block "));Serial.println(i+2); 236 | } 237 | if (!(_nfcShield->mifareclassic_WriteDataBlock (i+3, sectorbuffer4))) 238 | { 239 | Serial.print(F("Unable to write block "));Serial.println(i+3); 240 | } 241 | } else { 242 | unsigned int iii=uidLength; 243 | Serial.print(F("Unable to authenticate block "));Serial.println(i); 244 | _nfcShield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&iii); 245 | } 246 | } 247 | } 248 | return success; 249 | } 250 | 251 | #define NR_SHORTSECTOR (32) // Number of short sectors on Mifare 1K/4K 252 | #define NR_LONGSECTOR (8) // Number of long sectors on Mifare 4K 253 | #define NR_BLOCK_OF_SHORTSECTOR (4) // Number of blocks in a short sector 254 | #define NR_BLOCK_OF_LONGSECTOR (16) // Number of blocks in a long sector 255 | 256 | // Determine the sector trailer block based on sector number 257 | #define BLOCK_NUMBER_OF_SECTOR_TRAILER(sector) (((sector)mifareclassic_AuthenticateBlock (uid, uidLength, BLOCK_NUMBER_OF_SECTOR_TRAILER(idx), 1, (uint8_t *)KEY_DEFAULT_KEYAB); 277 | if (!success) 278 | { 279 | Serial.print(F("Authentication failed for sector ")); Serial.println(idx); 280 | return false; 281 | } 282 | 283 | // Step 2: Write to the other blocks 284 | if (idx == 0) 285 | { 286 | memset(blockBuffer, 0, sizeof(blockBuffer)); 287 | if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer))) 288 | { 289 | Serial.print(F("Unable to write to sector ")); Serial.println(idx); 290 | } 291 | } 292 | else 293 | { 294 | memset(blockBuffer, 0, sizeof(blockBuffer)); 295 | // this block has not to be overwritten for block 0. It contains Tag id and other unique data. 296 | if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer))) 297 | { 298 | Serial.print(F("Unable to write to sector ")); Serial.println(idx); 299 | } 300 | if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer))) 301 | { 302 | Serial.print(F("Unable to write to sector ")); Serial.println(idx); 303 | } 304 | } 305 | 306 | memset(blockBuffer, 0, sizeof(blockBuffer)); 307 | 308 | if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 1, blockBuffer))) 309 | { 310 | Serial.print(F("Unable to write to sector ")); Serial.println(idx); 311 | } 312 | 313 | // Step 3: Reset both keys to 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 314 | memcpy(blockBuffer, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB)); 315 | memcpy(blockBuffer + 6, blankAccessBits, sizeof(blankAccessBits)); 316 | blockBuffer[9] = 0x69; 317 | memcpy(blockBuffer + 10, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB)); 318 | 319 | // Step 4: Write the trailer block 320 | if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)), blockBuffer))) 321 | { 322 | Serial.print(F("Unable to write trailer block of sector ")); Serial.println(idx); 323 | } 324 | } 325 | return true; 326 | } 327 | 328 | boolean MifareClassic::write(NdefMessage& m, byte * uid, unsigned int uidLength) 329 | { 330 | 331 | uint8_t encoded[m.getEncodedSize()]; 332 | m.encode(encoded); 333 | 334 | uint8_t buffer[getBufferSize(sizeof(encoded))]; 335 | memset(buffer, 0, sizeof(buffer)); 336 | 337 | #ifdef MIFARE_CLASSIC_DEBUG 338 | Serial.print(F("sizeof(encoded) "));Serial.println(sizeof(encoded)); 339 | Serial.print(F("sizeof(buffer) "));Serial.println(sizeof(buffer)); 340 | #endif 341 | 342 | if (sizeof(encoded) < 0xFF) 343 | { 344 | buffer[0] = 0x3; 345 | buffer[1] = sizeof(encoded); 346 | memcpy(&buffer[2], encoded, sizeof(encoded)); 347 | buffer[2+sizeof(encoded)] = 0xFE; // terminator 348 | } 349 | else 350 | { 351 | buffer[0] = 0x3; 352 | buffer[1] = 0xFF; 353 | buffer[2] = ((sizeof(encoded) >> 8) & 0xFF); 354 | buffer[3] = (sizeof(encoded) & 0xFF); 355 | memcpy(&buffer[4], encoded, sizeof(encoded)); 356 | buffer[4+sizeof(encoded)] = 0xFE; // terminator 357 | } 358 | 359 | // Write to tag 360 | int index = 0; 361 | int currentBlock = 4; 362 | uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key 363 | 364 | while (index < sizeof(buffer)) 365 | { 366 | 367 | if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock)) 368 | { 369 | int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key); 370 | if (!success) 371 | { 372 | Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock); 373 | return false; 374 | } 375 | } 376 | 377 | int write_success = _nfcShield->mifareclassic_WriteDataBlock (currentBlock, &buffer[index]); 378 | if (write_success) 379 | { 380 | #ifdef MIFARE_CLASSIC_DEBUG 381 | Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - "); 382 | _nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE); 383 | #endif 384 | } 385 | else 386 | { 387 | Serial.print(F("Write failed "));Serial.println(currentBlock); 388 | return false; 389 | } 390 | index += BLOCK_SIZE; 391 | currentBlock++; 392 | 393 | if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock)) 394 | { 395 | // can't write to trailer block 396 | #ifdef MIFARE_CLASSIC_DEBUG 397 | Serial.print(F("Skipping block "));Serial.println(currentBlock); 398 | #endif 399 | currentBlock++; 400 | } 401 | 402 | } 403 | 404 | return true; 405 | } -------------------------------------------------------------------------------- /NDEF/MifareClassic.h: -------------------------------------------------------------------------------- 1 | #ifndef MifareClassic_h 2 | #define MifareClassic_h 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class MifareClassic 10 | { 11 | public: 12 | MifareClassic(PN532& nfcShield); 13 | ~MifareClassic(); 14 | NfcTag read(byte *uid, unsigned int uidLength); 15 | boolean write(NdefMessage& ndefMessage, byte *uid, unsigned int uidLength); 16 | boolean formatNDEF(byte * uid, unsigned int uidLength); 17 | boolean formatMifare(byte * uid, unsigned int uidLength); 18 | private: 19 | PN532* _nfcShield; 20 | int getBufferSize(int messageLength); 21 | int getNdefStartIndex(byte *data); 22 | bool decodeTlv(byte *data, int &messageLength, int &messageStartIndex); 23 | }; 24 | 25 | #endif -------------------------------------------------------------------------------- /NDEF/MifareUltralight.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define ULTRALIGHT_PAGE_SIZE 4 4 | #define ULTRALIGHT_READ_SIZE 4 // we should be able to read 16 bytes at a time 5 | 6 | #define ULTRALIGHT_DATA_START_PAGE 4 7 | #define ULTRALIGHT_MESSAGE_LENGTH_INDEX 1 8 | #define ULTRALIGHT_DATA_START_INDEX 2 9 | #define ULTRALIGHT_MAX_PAGE 63 10 | 11 | #define NFC_FORUM_TAG_TYPE_2 ("NFC Forum Type 2") 12 | 13 | MifareUltralight::MifareUltralight(PN532& nfcShield) 14 | { 15 | nfc = &nfcShield; 16 | ndefStartIndex = 0; 17 | messageLength = 0; 18 | } 19 | 20 | MifareUltralight::~MifareUltralight() 21 | { 22 | } 23 | 24 | NfcTag MifareUltralight::read(byte * uid, unsigned int uidLength) 25 | { 26 | if (isUnformatted()) 27 | { 28 | Serial.println(F("WARNING: Tag is not formatted.")); 29 | return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2); 30 | } 31 | 32 | readCapabilityContainer(); // meta info for tag 33 | findNdefMessage(); 34 | calculateBufferSize(); 35 | 36 | if (messageLength == 0) { // data is 0x44 0x03 0x00 0xFE 37 | NdefMessage message = NdefMessage(); 38 | message.addEmptyRecord(); 39 | return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, message); 40 | } 41 | 42 | boolean success; 43 | uint8_t page; 44 | uint8_t index = 0; 45 | byte buffer[bufferSize]; 46 | for (page = ULTRALIGHT_DATA_START_PAGE; page < ULTRALIGHT_MAX_PAGE; page++) 47 | { 48 | // read the data 49 | success = nfc->mifareultralight_ReadPage(page, &buffer[index]); 50 | if (success) 51 | { 52 | #ifdef MIFARE_ULTRALIGHT_DEBUG 53 | Serial.print(F("Page "));Serial.print(page);Serial.print(" "); 54 | nfc->PrintHexChar(&buffer[index], ULTRALIGHT_PAGE_SIZE); 55 | #endif 56 | } 57 | else 58 | { 59 | Serial.print(F("Read failed "));Serial.println(page); 60 | // TODO error handling 61 | messageLength = 0; 62 | break; 63 | } 64 | 65 | if (index >= (messageLength + ndefStartIndex)) 66 | { 67 | break; 68 | } 69 | 70 | index += ULTRALIGHT_PAGE_SIZE; 71 | } 72 | 73 | NdefMessage ndefMessage = NdefMessage(&buffer[ndefStartIndex], messageLength); 74 | return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, ndefMessage); 75 | 76 | } 77 | 78 | boolean MifareUltralight::isUnformatted() 79 | { 80 | uint8_t page = 4; 81 | byte data[ULTRALIGHT_READ_SIZE]; 82 | boolean success = nfc->mifareultralight_ReadPage (page, data); 83 | if (success) 84 | { 85 | return (data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[3] == 0xFF); 86 | } 87 | else 88 | { 89 | Serial.print(F("Error. Failed read page "));Serial.println(page); 90 | return false; 91 | } 92 | } 93 | 94 | // page 3 has tag capabilities 95 | void MifareUltralight::readCapabilityContainer() 96 | { 97 | byte data[ULTRALIGHT_PAGE_SIZE]; 98 | int success = nfc->mifareultralight_ReadPage (3, data); 99 | if (success) 100 | { 101 | // See AN1303 - different rules for Mifare Family byte2 = (additional data + 48)/8 102 | tagCapacity = data[2] * 8; 103 | #ifdef MIFARE_ULTRALIGHT_DEBUG 104 | Serial.print(F("Tag capacity "));Serial.print(tagCapacity);Serial.println(F(" bytes")); 105 | #endif 106 | 107 | // TODO future versions should get lock information 108 | } 109 | } 110 | 111 | // read enough of the message to find the ndef message length 112 | void MifareUltralight::findNdefMessage() 113 | { 114 | int page; 115 | byte data[12]; // 3 pages 116 | byte* data_ptr = &data[0]; 117 | 118 | // the nxp read command reads 4 pages, unfortunately adafruit give me one page at a time 119 | boolean success = true; 120 | for (page = 4; page < 6; page++) 121 | { 122 | success = success && nfc->mifareultralight_ReadPage(page, data_ptr); 123 | #ifdef MIFARE_ULTRALIGHT_DEBUG 124 | Serial.print(F("Page "));Serial.print(page);Serial.print(F(" - ")); 125 | nfc->PrintHexChar(data_ptr, 4); 126 | #endif 127 | data_ptr += ULTRALIGHT_PAGE_SIZE; 128 | } 129 | 130 | if (success) 131 | { 132 | if (data[0] == 0x03) 133 | { 134 | messageLength = data[1]; 135 | ndefStartIndex = 2; 136 | } 137 | else if (data[5] == 0x3) // page 5 byte 1 138 | { 139 | // TODO should really read the lock control TLV to ensure byte[5] is correct 140 | messageLength = data[6]; 141 | ndefStartIndex = 7; 142 | } 143 | } 144 | 145 | #ifdef MIFARE_ULTRALIGHT_DEBUG 146 | Serial.print(F("messageLength "));Serial.println(messageLength); 147 | Serial.print(F("ndefStartIndex "));Serial.println(ndefStartIndex); 148 | #endif 149 | } 150 | 151 | // buffer is larger than the message, need to handle some data before and after 152 | // message and need to ensure we read full pages 153 | void MifareUltralight::calculateBufferSize() 154 | { 155 | // TLV terminator 0xFE is 1 byte 156 | bufferSize = messageLength + ndefStartIndex + 1; 157 | 158 | if (bufferSize % ULTRALIGHT_READ_SIZE != 0) 159 | { 160 | // buffer must be an increment of page size 161 | bufferSize = ((bufferSize / ULTRALIGHT_READ_SIZE) + 1) * ULTRALIGHT_READ_SIZE; 162 | } 163 | } 164 | 165 | boolean MifareUltralight::write(NdefMessage& m, byte * uid, unsigned int uidLength) 166 | { 167 | if (isUnformatted()) 168 | { 169 | Serial.println(F("WARNING: Tag is not formatted.")); 170 | return false; 171 | } 172 | readCapabilityContainer(); // meta info for tag 173 | 174 | messageLength = m.getEncodedSize(); 175 | ndefStartIndex = messageLength < 0xFF ? 2 : 4; 176 | calculateBufferSize(); 177 | 178 | if(bufferSize>tagCapacity) { 179 | #ifdef MIFARE_ULTRALIGHT_DEBUG 180 | Serial.print(F("Encoded Message length exceeded tag Capacity "));Serial.println(tagCapacity); 181 | #endif 182 | return false; 183 | } 184 | 185 | uint8_t encoded[bufferSize]; 186 | uint8_t * src = encoded; 187 | unsigned int position = 0; 188 | uint8_t page = ULTRALIGHT_DATA_START_PAGE; 189 | 190 | // Set message size. With ultralight should always be less than 0xFF but who knows? 191 | 192 | encoded[0] = 0x3; 193 | if (messageLength < 0xFF) 194 | { 195 | encoded[1] = messageLength; 196 | } 197 | else 198 | { 199 | encoded[1] = 0xFF; 200 | encoded[2] = ((messageLength >> 8) & 0xFF); 201 | encoded[3] = (messageLength & 0xFF); 202 | } 203 | 204 | m.encode(encoded+ndefStartIndex); 205 | // this is always at least 1 byte copy because of terminator. 206 | memset(encoded+ndefStartIndex+messageLength,0,bufferSize-ndefStartIndex-messageLength); 207 | encoded[ndefStartIndex+messageLength] = 0xFE; // terminator 208 | 209 | #ifdef MIFARE_ULTRALIGHT_DEBUG 210 | Serial.print(F("messageLength "));Serial.println(messageLength); 211 | Serial.print(F("Tag Capacity "));Serial.println(tagCapacity); 212 | nfc->PrintHex(encoded,bufferSize); 213 | #endif 214 | 215 | while (position < bufferSize){ //bufferSize is always times pagesize so no "last chunk" check 216 | // write page 217 | if (!nfc->mifareultralight_WritePage(page, src)) 218 | return false; 219 | #ifdef MIFARE_ULTRALIGHT_DEBUG 220 | Serial.print(F("Wrote page "));Serial.print(page);Serial.print(F(" - ")); 221 | nfc->PrintHex(src,ULTRALIGHT_PAGE_SIZE); 222 | #endif 223 | page++; 224 | src+=ULTRALIGHT_PAGE_SIZE; 225 | position+=ULTRALIGHT_PAGE_SIZE; 226 | } 227 | return true; 228 | } 229 | 230 | // Mifare Ultralight can't be reset to factory state 231 | // zero out tag data like the NXP Tag Write Android application 232 | boolean MifareUltralight::clean() 233 | { 234 | readCapabilityContainer(); // meta info for tag 235 | 236 | uint8_t pages = (tagCapacity / ULTRALIGHT_PAGE_SIZE) + ULTRALIGHT_DATA_START_PAGE; 237 | 238 | // factory tags have 0xFF, but OTP-CC blocks have already been set so we use 0x00 239 | uint8_t data[4] = { 0x00, 0x00, 0x00, 0x00 }; 240 | 241 | for (int i = ULTRALIGHT_DATA_START_PAGE; i < pages; i++) { 242 | #ifdef MIFARE_ULTRALIGHT_DEBUG 243 | Serial.print(F("Wrote page "));Serial.print(i);Serial.print(F(" - ")); 244 | nfc->PrintHex(data, ULTRALIGHT_PAGE_SIZE); 245 | #endif 246 | if (!nfc->mifareultralight_WritePage(i, data)) { 247 | return false; 248 | } 249 | } 250 | return true; 251 | } 252 | -------------------------------------------------------------------------------- /NDEF/MifareUltralight.h: -------------------------------------------------------------------------------- 1 | #ifndef MifareUltralight_h 2 | #define MifareUltralight_h 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class MifareUltralight 9 | { 10 | public: 11 | MifareUltralight(PN532& nfcShield); 12 | ~MifareUltralight(); 13 | NfcTag read(byte *uid, unsigned int uidLength); 14 | boolean write(NdefMessage& ndefMessage, byte *uid, unsigned int uidLength); 15 | boolean clean(); 16 | private: 17 | PN532* nfc; 18 | unsigned int tagCapacity; 19 | unsigned int messageLength; 20 | unsigned int bufferSize; 21 | unsigned int ndefStartIndex; 22 | boolean isUnformatted(); 23 | void readCapabilityContainer(); 24 | void findNdefMessage(); 25 | void calculateBufferSize(); 26 | }; 27 | 28 | #endif 29 | -------------------------------------------------------------------------------- /NDEF/Ndef.cpp: -------------------------------------------------------------------------------- 1 | #include "Ndef.h" 2 | 3 | // Borrowed from Adafruit_NFCShield_I2C 4 | void PrintHex(const byte * data, const long numBytes) 5 | { 6 | uint32_t szPos; 7 | for (szPos=0; szPos < numBytes; szPos++) 8 | { 9 | Serial.print("0x"); 10 | // Append leading 0 for small values 11 | if (data[szPos] <= 0xF) 12 | Serial.print("0"); 13 | Serial.print(data[szPos]&0xff, HEX); 14 | if ((numBytes > 1) && (szPos != numBytes - 1)) 15 | { 16 | Serial.print(" "); 17 | } 18 | } 19 | Serial.println(""); 20 | } 21 | 22 | // Borrowed from Adafruit_NFCShield_I2C 23 | void PrintHexChar(const byte * data, const long numBytes) 24 | { 25 | uint32_t szPos; 26 | for (szPos=0; szPos < numBytes; szPos++) 27 | { 28 | // Append leading 0 for small values 29 | if (data[szPos] <= 0xF) 30 | Serial.print("0"); 31 | Serial.print(data[szPos], HEX); 32 | if ((numBytes > 1) && (szPos != numBytes - 1)) 33 | { 34 | Serial.print(" "); 35 | } 36 | } 37 | Serial.print(" "); 38 | for (szPos=0; szPos < numBytes; szPos++) 39 | { 40 | if (data[szPos] <= 0x1F) 41 | Serial.print("."); 42 | else 43 | Serial.print((char)data[szPos]); 44 | } 45 | Serial.println(""); 46 | } 47 | 48 | // Note if buffer % blockSize != 0, last block will not be written 49 | void DumpHex(const byte * data, const long numBytes, const unsigned int blockSize) 50 | { 51 | int i; 52 | for (i = 0; i < (numBytes / blockSize); i++) 53 | { 54 | PrintHexChar(data, blockSize); 55 | data += blockSize; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /NDEF/Ndef.h: -------------------------------------------------------------------------------- 1 | #ifndef Ndef_h 2 | #define Ndef_h 3 | 4 | /* NOTE: To use the Ndef library in your code, don't include Ndef.h 5 | See README.md for details on which files to include in your sketch. 6 | */ 7 | 8 | #include 9 | 10 | #define NULL (void *)0 11 | 12 | void PrintHex(const byte *data, const long numBytes); 13 | void PrintHexChar(const byte *data, const long numBytes); 14 | void DumpHex(const byte *data, const long numBytes, const int blockSize); 15 | 16 | #endif -------------------------------------------------------------------------------- /NDEF/NdefMessage.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | NdefMessage::NdefMessage(void) 4 | { 5 | _recordCount = 0; 6 | } 7 | 8 | NdefMessage::NdefMessage(const byte * data, const int numBytes) 9 | { 10 | #ifdef NDEF_DEBUG 11 | Serial.print(F("Decoding "));Serial.print(numBytes);Serial.println(F(" bytes")); 12 | PrintHexChar(data, numBytes); 13 | //DumpHex(data, numBytes, 16); 14 | #endif 15 | 16 | _recordCount = 0; 17 | 18 | int index = 0; 19 | 20 | while (index <= numBytes) 21 | { 22 | 23 | // decode tnf - first byte is tnf with bit flags 24 | // see the NFDEF spec for more info 25 | byte tnf_byte = data[index]; 26 | bool mb = (tnf_byte & 0x80) != 0; 27 | bool me = (tnf_byte & 0x40) != 0; 28 | bool cf = (tnf_byte & 0x20) != 0; 29 | bool sr = (tnf_byte & 0x10) != 0; 30 | bool il = (tnf_byte & 0x8) != 0; 31 | byte tnf = (tnf_byte & 0x7); 32 | 33 | NdefRecord record = NdefRecord(); 34 | record.setTnf(tnf); 35 | 36 | index++; 37 | int typeLength = data[index]; 38 | 39 | int payloadLength = 0; 40 | if (sr) 41 | { 42 | index++; 43 | payloadLength = data[index]; 44 | } 45 | else 46 | { 47 | payloadLength = 48 | ((0xFF & data[++index]) << 24) 49 | | ((0xFF & data[++index]) << 16) 50 | | ((0xFF & data[++index]) << 8) 51 | | (0xFF & data[++index]); 52 | } 53 | 54 | int idLength = 0; 55 | if (il) 56 | { 57 | index++; 58 | idLength = data[index]; 59 | } 60 | 61 | index++; 62 | record.setType(&data[index], typeLength); 63 | index += typeLength; 64 | 65 | if (il) 66 | { 67 | record.setId(&data[index], idLength); 68 | index += idLength; 69 | } 70 | 71 | record.setPayload(&data[index], payloadLength); 72 | index += payloadLength; 73 | 74 | addRecord(record); 75 | 76 | if (me) break; // last message 77 | } 78 | 79 | } 80 | 81 | NdefMessage::NdefMessage(const NdefMessage& rhs) 82 | { 83 | 84 | _recordCount = rhs._recordCount; 85 | for (int i = 0; i < _recordCount; i++) 86 | { 87 | _records[i] = rhs._records[i]; 88 | } 89 | 90 | } 91 | 92 | NdefMessage::~NdefMessage() 93 | { 94 | } 95 | 96 | NdefMessage& NdefMessage::operator=(const NdefMessage& rhs) 97 | { 98 | 99 | if (this != &rhs) 100 | { 101 | 102 | // delete existing records 103 | for (int i = 0; i < _recordCount; i++) 104 | { 105 | // TODO Dave: is this the right way to delete existing records? 106 | _records[i] = NdefRecord(); 107 | } 108 | 109 | _recordCount = rhs._recordCount; 110 | for (int i = 0; i < _recordCount; i++) 111 | { 112 | _records[i] = rhs._records[i]; 113 | } 114 | } 115 | return *this; 116 | } 117 | 118 | unsigned int NdefMessage::getRecordCount() 119 | { 120 | return _recordCount; 121 | } 122 | 123 | int NdefMessage::getEncodedSize() 124 | { 125 | int size = 0; 126 | for (int i = 0; i < _recordCount; i++) 127 | { 128 | size += _records[i].getEncodedSize(); 129 | } 130 | return size; 131 | } 132 | 133 | // TODO change this to return uint8_t* 134 | void NdefMessage::encode(uint8_t* data) 135 | { 136 | // assert sizeof(data) >= getEncodedSize() 137 | uint8_t* data_ptr = &data[0]; 138 | 139 | for (int i = 0; i < _recordCount; i++) 140 | { 141 | _records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount); 142 | // TODO can NdefRecord.encode return the record size? 143 | data_ptr += _records[i].getEncodedSize(); 144 | } 145 | 146 | } 147 | 148 | boolean NdefMessage::addRecord(NdefRecord& record) 149 | { 150 | 151 | if (_recordCount < MAX_NDEF_RECORDS) 152 | { 153 | _records[_recordCount] = record; 154 | _recordCount++; 155 | return true; 156 | } 157 | else 158 | { 159 | Serial.println(F("WARNING: Too many records. Increase MAX_NDEF_RECORDS.")); 160 | return false; 161 | } 162 | } 163 | 164 | void NdefMessage::addMimeMediaRecord(String mimeType, String payload) 165 | { 166 | 167 | byte payloadBytes[payload.length() + 1]; 168 | payload.getBytes(payloadBytes, sizeof(payloadBytes)); 169 | 170 | addMimeMediaRecord(mimeType, payloadBytes, payload.length()); 171 | } 172 | 173 | void NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength) 174 | { 175 | NdefRecord r = NdefRecord(); 176 | r.setTnf(TNF_MIME_MEDIA); 177 | 178 | byte type[mimeType.length() + 1]; 179 | mimeType.getBytes(type, sizeof(type)); 180 | r.setType(type, mimeType.length()); 181 | 182 | r.setPayload(payload, payloadLength); 183 | 184 | addRecord(r); 185 | } 186 | 187 | void NdefMessage::addTextRecord(String text) 188 | { 189 | addTextRecord(text, "en"); 190 | } 191 | 192 | void NdefMessage::addTextRecord(String text, String encoding) 193 | { 194 | NdefRecord r = NdefRecord(); 195 | r.setTnf(TNF_WELL_KNOWN); 196 | 197 | uint8_t RTD_TEXT[1] = { 0x54 }; // TODO this should be a constant or preprocessor 198 | r.setType(RTD_TEXT, sizeof(RTD_TEXT)); 199 | 200 | // X is a placeholder for encoding length 201 | // TODO is it more efficient to build w/o string concatenation? 202 | String payloadString = "X" + encoding + text; 203 | 204 | byte payload[payloadString.length() + 1]; 205 | payloadString.getBytes(payload, sizeof(payload)); 206 | 207 | // replace X with the real encoding length 208 | payload[0] = encoding.length(); 209 | 210 | r.setPayload(payload, payloadString.length()); 211 | 212 | addRecord(r); 213 | } 214 | 215 | void NdefMessage::addUriRecord(String uri) 216 | { 217 | NdefRecord* r = new NdefRecord(); 218 | r->setTnf(TNF_WELL_KNOWN); 219 | 220 | uint8_t RTD_URI[1] = { 0x55 }; // TODO this should be a constant or preprocessor 221 | r->setType(RTD_URI, sizeof(RTD_URI)); 222 | 223 | // X is a placeholder for identifier code 224 | String payloadString = "X" + uri; 225 | 226 | byte payload[payloadString.length() + 1]; 227 | payloadString.getBytes(payload, sizeof(payload)); 228 | 229 | // add identifier code 0x0, meaning no prefix substitution 230 | payload[0] = 0x0; 231 | 232 | r->setPayload(payload, payloadString.length()); 233 | 234 | addRecord(*r); 235 | delete(r); 236 | } 237 | 238 | void NdefMessage::addEmptyRecord() 239 | { 240 | NdefRecord* r = new NdefRecord(); 241 | r->setTnf(TNF_EMPTY); 242 | addRecord(*r); 243 | delete(r); 244 | } 245 | 246 | NdefRecord NdefMessage::getRecord(int index) 247 | { 248 | if (index > -1 && index < _recordCount) 249 | { 250 | return _records[index]; 251 | } 252 | else 253 | { 254 | return NdefRecord(); // would rather return NULL 255 | } 256 | } 257 | 258 | NdefRecord NdefMessage::operator[](int index) 259 | { 260 | return getRecord(index); 261 | } 262 | 263 | void NdefMessage::print() 264 | { 265 | Serial.print(F("\nNDEF Message "));Serial.print(_recordCount);Serial.print(F(" record")); 266 | _recordCount == 1 ? Serial.print(", ") : Serial.print("s, "); 267 | Serial.print(getEncodedSize());Serial.println(F(" bytes")); 268 | 269 | int i; 270 | for (i = 0; i < _recordCount; i++) 271 | { 272 | _records[i].print(); 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /NDEF/NdefMessage.h: -------------------------------------------------------------------------------- 1 | #ifndef NdefMessage_h 2 | #define NdefMessage_h 3 | 4 | #include 5 | #include 6 | 7 | #define MAX_NDEF_RECORDS 4 8 | 9 | class NdefMessage 10 | { 11 | public: 12 | NdefMessage(void); 13 | NdefMessage(const byte *data, const int numBytes); 14 | NdefMessage(const NdefMessage& rhs); 15 | ~NdefMessage(); 16 | NdefMessage& operator=(const NdefMessage& rhs); 17 | 18 | int getEncodedSize(); // need so we can pass array to encode 19 | void encode(byte *data); 20 | 21 | boolean addRecord(NdefRecord& record); 22 | void addMimeMediaRecord(String mimeType, String payload); 23 | void addMimeMediaRecord(String mimeType, byte *payload, int payloadLength); 24 | void addTextRecord(String text); 25 | void addTextRecord(String text, String encoding); 26 | void addUriRecord(String uri); 27 | void addEmptyRecord(); 28 | 29 | unsigned int getRecordCount(); 30 | NdefRecord getRecord(int index); 31 | NdefRecord operator[](int index); 32 | 33 | void print(); 34 | private: 35 | NdefRecord _records[MAX_NDEF_RECORDS]; 36 | unsigned int _recordCount; 37 | }; 38 | 39 | #endif -------------------------------------------------------------------------------- /NDEF/NdefRecord.cpp: -------------------------------------------------------------------------------- 1 | #include "NdefRecord.h" 2 | 3 | NdefRecord::NdefRecord() 4 | { 5 | //Serial.println("NdefRecord Constructor 1"); 6 | _tnf = 0; 7 | _typeLength = 0; 8 | _payloadLength = 0; 9 | _idLength = 0; 10 | _type = (byte *)NULL; 11 | _payload = (byte *)NULL; 12 | _id = (byte *)NULL; 13 | } 14 | 15 | NdefRecord::NdefRecord(const NdefRecord& rhs) 16 | { 17 | //Serial.println("NdefRecord Constructor 2 (copy)"); 18 | 19 | _tnf = rhs._tnf; 20 | _typeLength = rhs._typeLength; 21 | _payloadLength = rhs._payloadLength; 22 | _idLength = rhs._idLength; 23 | _type = (byte *)NULL; 24 | _payload = (byte *)NULL; 25 | _id = (byte *)NULL; 26 | 27 | if (_typeLength) 28 | { 29 | _type = (byte*)malloc(_typeLength); 30 | memcpy(_type, rhs._type, _typeLength); 31 | } 32 | 33 | if (_payloadLength) 34 | { 35 | _payload = (byte*)malloc(_payloadLength); 36 | memcpy(_payload, rhs._payload, _payloadLength); 37 | } 38 | 39 | if (_idLength) 40 | { 41 | _id = (byte*)malloc(_idLength); 42 | memcpy(_id, rhs._id, _idLength); 43 | } 44 | 45 | } 46 | 47 | // TODO NdefRecord::NdefRecord(tnf, type, payload, id) 48 | 49 | NdefRecord::~NdefRecord() 50 | { 51 | //Serial.println("NdefRecord Destructor"); 52 | if (_typeLength) 53 | { 54 | free(_type); 55 | } 56 | 57 | if (_payloadLength) 58 | { 59 | free(_payload); 60 | } 61 | 62 | if (_idLength) 63 | { 64 | free(_id); 65 | } 66 | } 67 | 68 | NdefRecord& NdefRecord::operator=(const NdefRecord& rhs) 69 | { 70 | //Serial.println("NdefRecord ASSIGN"); 71 | 72 | if (this != &rhs) 73 | { 74 | // free existing 75 | if (_typeLength) 76 | { 77 | free(_type); 78 | } 79 | 80 | if (_payloadLength) 81 | { 82 | free(_payload); 83 | } 84 | 85 | if (_idLength) 86 | { 87 | free(_id); 88 | } 89 | 90 | _tnf = rhs._tnf; 91 | _typeLength = rhs._typeLength; 92 | _payloadLength = rhs._payloadLength; 93 | _idLength = rhs._idLength; 94 | 95 | if (_typeLength) 96 | { 97 | _type = (byte*)malloc(_typeLength); 98 | memcpy(_type, rhs._type, _typeLength); 99 | } 100 | 101 | if (_payloadLength) 102 | { 103 | _payload = (byte*)malloc(_payloadLength); 104 | memcpy(_payload, rhs._payload, _payloadLength); 105 | } 106 | 107 | if (_idLength) 108 | { 109 | _id = (byte*)malloc(_idLength); 110 | memcpy(_id, rhs._id, _idLength); 111 | } 112 | } 113 | return *this; 114 | } 115 | 116 | // size of records in bytes 117 | int NdefRecord::getEncodedSize() 118 | { 119 | int size = 2; // tnf + typeLength 120 | if (_payloadLength > 0xFF) 121 | { 122 | size += 4; 123 | } 124 | else 125 | { 126 | size += 1; 127 | } 128 | 129 | if (_idLength) 130 | { 131 | size += 1; 132 | } 133 | 134 | size += (_typeLength + _payloadLength + _idLength); 135 | 136 | return size; 137 | } 138 | 139 | void NdefRecord::encode(byte *data, bool firstRecord, bool lastRecord) 140 | { 141 | // assert data > getEncodedSize() 142 | 143 | uint8_t* data_ptr = &data[0]; 144 | 145 | *data_ptr = getTnfByte(firstRecord, lastRecord); 146 | data_ptr += 1; 147 | 148 | *data_ptr = _typeLength; 149 | data_ptr += 1; 150 | 151 | if (_payloadLength <= 0xFF) { // short record 152 | *data_ptr = _payloadLength; 153 | data_ptr += 1; 154 | } else { // long format 155 | // 4 bytes but we store length as an int 156 | data_ptr[0] = 0x0; // (_payloadLength >> 24) & 0xFF; 157 | data_ptr[1] = 0x0; // (_payloadLength >> 16) & 0xFF; 158 | data_ptr[2] = (_payloadLength >> 8) & 0xFF; 159 | data_ptr[3] = _payloadLength & 0xFF; 160 | data_ptr += 4; 161 | } 162 | 163 | if (_idLength) 164 | { 165 | *data_ptr = _idLength; 166 | data_ptr += 1; 167 | } 168 | 169 | //Serial.println(2); 170 | memcpy(data_ptr, _type, _typeLength); 171 | data_ptr += _typeLength; 172 | 173 | memcpy(data_ptr, _payload, _payloadLength); 174 | data_ptr += _payloadLength; 175 | 176 | if (_idLength) 177 | { 178 | memcpy(data_ptr, _id, _idLength); 179 | data_ptr += _idLength; 180 | } 181 | } 182 | 183 | byte NdefRecord::getTnfByte(bool firstRecord, bool lastRecord) 184 | { 185 | int value = _tnf; 186 | 187 | if (firstRecord) { // mb 188 | value = value | 0x80; 189 | } 190 | 191 | if (lastRecord) { // 192 | value = value | 0x40; 193 | } 194 | 195 | // chunked flag is always false for now 196 | // if (cf) { 197 | // value = value | 0x20; 198 | // } 199 | 200 | if (_payloadLength <= 0xFF) { 201 | value = value | 0x10; 202 | } 203 | 204 | if (_idLength) { 205 | value = value | 0x8; 206 | } 207 | 208 | return value; 209 | } 210 | 211 | byte NdefRecord::getTnf() 212 | { 213 | return _tnf; 214 | } 215 | 216 | void NdefRecord::setTnf(byte tnf) 217 | { 218 | _tnf = tnf; 219 | } 220 | 221 | unsigned int NdefRecord::getTypeLength() 222 | { 223 | return _typeLength; 224 | } 225 | 226 | int NdefRecord::getPayloadLength() 227 | { 228 | return _payloadLength; 229 | } 230 | 231 | unsigned int NdefRecord::getIdLength() 232 | { 233 | return _idLength; 234 | } 235 | 236 | String NdefRecord::getType() 237 | { 238 | char type[_typeLength + 1]; 239 | memcpy(type, _type, _typeLength); 240 | type[_typeLength] = '\0'; // null terminate 241 | return String(type); 242 | } 243 | 244 | // this assumes the caller created type correctly 245 | void NdefRecord::getType(uint8_t* type) 246 | { 247 | memcpy(type, _type, _typeLength); 248 | } 249 | 250 | void NdefRecord::setType(const byte * type, const unsigned int numBytes) 251 | { 252 | if(_typeLength) 253 | { 254 | free(_type); 255 | } 256 | 257 | _type = (uint8_t*)malloc(numBytes); 258 | memcpy(_type, type, numBytes); 259 | _typeLength = numBytes; 260 | } 261 | 262 | // assumes the caller sized payload properly 263 | void NdefRecord::getPayload(byte *payload) 264 | { 265 | memcpy(payload, _payload, _payloadLength); 266 | } 267 | 268 | void NdefRecord::setPayload(const byte * payload, const int numBytes) 269 | { 270 | if (_payloadLength) 271 | { 272 | free(_payload); 273 | } 274 | 275 | _payload = (byte*)malloc(numBytes); 276 | memcpy(_payload, payload, numBytes); 277 | _payloadLength = numBytes; 278 | } 279 | 280 | String NdefRecord::getId() 281 | { 282 | char id[_idLength + 1]; 283 | memcpy(id, _id, _idLength); 284 | id[_idLength] = '\0'; // null terminate 285 | return String(id); 286 | } 287 | 288 | void NdefRecord::getId(byte *id) 289 | { 290 | memcpy(id, _id, _idLength); 291 | } 292 | 293 | void NdefRecord::setId(const byte * id, const unsigned int numBytes) 294 | { 295 | if (_idLength) 296 | { 297 | free(_id); 298 | } 299 | 300 | _id = (byte*)malloc(numBytes); 301 | memcpy(_id, id, numBytes); 302 | _idLength = numBytes; 303 | } 304 | 305 | void NdefRecord::print() 306 | { 307 | Serial.println(F(" NDEF Record")); 308 | Serial.print(F(" TNF 0x"));Serial.print(_tnf, HEX);Serial.print(" "); 309 | switch (_tnf) { 310 | case TNF_EMPTY: 311 | Serial.println(F("Empty")); 312 | break; 313 | case TNF_WELL_KNOWN: 314 | Serial.println(F("Well Known")); 315 | break; 316 | case TNF_MIME_MEDIA: 317 | Serial.println(F("Mime Media")); 318 | break; 319 | case TNF_ABSOLUTE_URI: 320 | Serial.println(F("Absolute URI")); 321 | break; 322 | case TNF_EXTERNAL_TYPE: 323 | Serial.println(F("External")); 324 | break; 325 | case TNF_UNKNOWN: 326 | Serial.println(F("Unknown")); 327 | break; 328 | case TNF_UNCHANGED: 329 | Serial.println(F("Unchanged")); 330 | break; 331 | case TNF_RESERVED: 332 | Serial.println(F("Reserved")); 333 | break; 334 | default: 335 | Serial.println(); 336 | } 337 | Serial.print(F(" Type Length 0x"));Serial.print(_typeLength, HEX);Serial.print(" ");Serial.println(_typeLength); 338 | Serial.print(F(" Payload Length 0x"));Serial.print(_payloadLength, HEX);;Serial.print(" ");Serial.println(_payloadLength); 339 | if (_idLength) 340 | { 341 | Serial.print(F(" Id Length 0x"));Serial.println(_idLength, HEX); 342 | } 343 | Serial.print(F(" Type "));PrintHexChar(_type, _typeLength); 344 | // TODO chunk large payloads so this is readable 345 | Serial.print(F(" Payload "));PrintHexChar(_payload, _payloadLength); 346 | if (_idLength) 347 | { 348 | Serial.print(F(" Id "));PrintHexChar(_id, _idLength); 349 | } 350 | Serial.print(F(" Record is "));Serial.print(getEncodedSize());Serial.println(" bytes"); 351 | 352 | } -------------------------------------------------------------------------------- /NDEF/NdefRecord.h: -------------------------------------------------------------------------------- 1 | #ifndef NdefRecord_h 2 | #define NdefRecord_h 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #define TNF_EMPTY 0x0 9 | #define TNF_WELL_KNOWN 0x01 10 | #define TNF_MIME_MEDIA 0x02 11 | #define TNF_ABSOLUTE_URI 0x03 12 | #define TNF_EXTERNAL_TYPE 0x04 13 | #define TNF_UNKNOWN 0x05 14 | #define TNF_UNCHANGED 0x06 15 | #define TNF_RESERVED 0x07 16 | 17 | class NdefRecord 18 | { 19 | public: 20 | NdefRecord(); 21 | NdefRecord(const NdefRecord& rhs); 22 | ~NdefRecord(); 23 | NdefRecord& operator=(const NdefRecord& rhs); 24 | 25 | int getEncodedSize(); 26 | void encode(byte *data, bool firstRecord, bool lastRecord); 27 | 28 | unsigned int getTypeLength(); 29 | int getPayloadLength(); 30 | unsigned int getIdLength(); 31 | 32 | byte getTnf(); 33 | void getType(byte *type); 34 | void getPayload(byte *payload); 35 | void getId(byte *id); 36 | 37 | // convenience methods 38 | String getType(); 39 | String getId(); 40 | 41 | void setTnf(byte tnf); 42 | void setType(const byte *type, const unsigned int numBytes); 43 | void setPayload(const byte *payload, const int numBytes); 44 | void setId(const byte *id, const unsigned int numBytes); 45 | 46 | void print(); 47 | private: 48 | byte getTnfByte(bool firstRecord, bool lastRecord); 49 | byte _tnf; // 3 bit 50 | unsigned int _typeLength; 51 | int _payloadLength; 52 | unsigned int _idLength; 53 | byte *_type; 54 | byte *_payload; 55 | byte *_id; 56 | }; 57 | 58 | #endif -------------------------------------------------------------------------------- /NDEF/NfcAdapter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | NfcAdapter::NfcAdapter(PN532Interface &interface) 4 | { 5 | shield = new PN532(interface); 6 | } 7 | 8 | NfcAdapter::~NfcAdapter(void) 9 | { 10 | delete shield; 11 | } 12 | 13 | void NfcAdapter::begin(boolean verbose) 14 | { 15 | shield->begin(); 16 | 17 | uint32_t versiondata = shield->getFirmwareVersion(); 18 | 19 | if (! versiondata) 20 | { 21 | Serial.print(F("Didn't find PN53x board")); 22 | while (1); // halt 23 | } 24 | 25 | if (verbose) 26 | { 27 | Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX); 28 | Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC); 29 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 30 | } 31 | // configure board to read RFID tags 32 | shield->SAMConfig(); 33 | } 34 | 35 | boolean NfcAdapter::tagPresent(unsigned long timeout) 36 | { 37 | uint8_t success; 38 | uidLength = 0; 39 | 40 | if (timeout == 0) 41 | { 42 | success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength); 43 | } 44 | else 45 | { 46 | success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength, timeout); 47 | } 48 | return success; 49 | } 50 | 51 | boolean NfcAdapter::erase() 52 | { 53 | boolean success; 54 | NdefMessage message = NdefMessage(); 55 | message.addEmptyRecord(); 56 | return write(message); 57 | } 58 | 59 | boolean NfcAdapter::format() 60 | { 61 | boolean success; 62 | if (uidLength == 4) 63 | { 64 | MifareClassic mifareClassic = MifareClassic(*shield); 65 | success = mifareClassic.formatNDEF(uid, uidLength); 66 | } 67 | else 68 | { 69 | Serial.print(F("Unsupported Tag.")); 70 | success = false; 71 | } 72 | return success; 73 | } 74 | 75 | boolean NfcAdapter::clean() 76 | { 77 | uint8_t type = guessTagType(); 78 | 79 | if (type == TAG_TYPE_MIFARE_CLASSIC) 80 | { 81 | #ifdef NDEF_DEBUG 82 | Serial.println(F("Cleaning Mifare Classic")); 83 | #endif 84 | MifareClassic mifareClassic = MifareClassic(*shield); 85 | return mifareClassic.formatMifare(uid, uidLength); 86 | } 87 | else if (type == TAG_TYPE_2) 88 | { 89 | #ifdef NDEF_DEBUG 90 | Serial.println(F("Cleaning Mifare Ultralight")); 91 | #endif 92 | MifareUltralight ultralight = MifareUltralight(*shield); 93 | return ultralight.clean(); 94 | } 95 | else 96 | { 97 | Serial.print(F("No driver for card type "));Serial.println(type); 98 | return false; 99 | } 100 | 101 | } 102 | 103 | 104 | NfcTag NfcAdapter::read() 105 | { 106 | uint8_t type = guessTagType(); 107 | 108 | if (type == TAG_TYPE_MIFARE_CLASSIC) 109 | { 110 | #ifdef NDEF_DEBUG 111 | Serial.println(F("Reading Mifare Classic")); 112 | #endif 113 | MifareClassic mifareClassic = MifareClassic(*shield); 114 | return mifareClassic.read(uid, uidLength); 115 | } 116 | else if (type == TAG_TYPE_2) 117 | { 118 | #ifdef NDEF_DEBUG 119 | Serial.println(F("Reading Mifare Ultralight")); 120 | #endif 121 | MifareUltralight ultralight = MifareUltralight(*shield); 122 | return ultralight.read(uid, uidLength); 123 | } 124 | else if (type == TAG_TYPE_UNKNOWN) 125 | { 126 | Serial.print(F("Can not determine tag type")); 127 | return NfcTag(uid, uidLength); 128 | } 129 | else 130 | { 131 | Serial.print(F("No driver for card type "));Serial.println(type); 132 | // TODO should set type here 133 | return NfcTag(uid, uidLength); 134 | } 135 | 136 | } 137 | 138 | boolean NfcAdapter::write(NdefMessage& ndefMessage) 139 | { 140 | boolean success; 141 | uint8_t type = guessTagType(); 142 | 143 | if (type == TAG_TYPE_MIFARE_CLASSIC) 144 | { 145 | #ifdef NDEF_DEBUG 146 | Serial.println(F("Writing Mifare Classic")); 147 | #endif 148 | MifareClassic mifareClassic = MifareClassic(*shield); 149 | success = mifareClassic.write(ndefMessage, uid, uidLength); 150 | } 151 | else if (type == TAG_TYPE_2) 152 | { 153 | #ifdef NDEF_DEBUG 154 | Serial.println(F("Writing Mifare Ultralight")); 155 | #endif 156 | MifareUltralight mifareUltralight = MifareUltralight(*shield); 157 | success = mifareUltralight.write(ndefMessage, uid, uidLength); 158 | } 159 | else if (type == TAG_TYPE_UNKNOWN) 160 | { 161 | Serial.print(F("Can not determine tag type")); 162 | success = false; 163 | } 164 | else 165 | { 166 | Serial.print(F("No driver for card type "));Serial.println(type); 167 | success = false; 168 | } 169 | 170 | return success; 171 | } 172 | 173 | // TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown 174 | // Guess Tag Type by looking at the ATQA and SAK values 175 | // Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ??? 176 | unsigned int NfcAdapter::guessTagType() 177 | { 178 | 179 | // 4 byte id - Mifare Classic 180 | // - ATQA 0x4 && SAK 0x8 181 | // 7 byte id 182 | // - ATQA 0x44 && SAK 0x8 - Mifare Classic 183 | // - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2 184 | // - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4 185 | 186 | if (uidLength == 4) 187 | { 188 | return TAG_TYPE_MIFARE_CLASSIC; 189 | } 190 | else 191 | { 192 | return TAG_TYPE_2; 193 | } 194 | } 195 | -------------------------------------------------------------------------------- /NDEF/NfcAdapter.h: -------------------------------------------------------------------------------- 1 | #ifndef NfcAdapter_h 2 | #define NfcAdapter_h 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | // Drivers 10 | #include 11 | #include 12 | 13 | #define TAG_TYPE_MIFARE_CLASSIC (0) 14 | #define TAG_TYPE_1 (1) 15 | #define TAG_TYPE_2 (2) 16 | #define TAG_TYPE_3 (3) 17 | #define TAG_TYPE_4 (4) 18 | #define TAG_TYPE_UNKNOWN (99) 19 | 20 | #define IRQ (2) 21 | #define RESET (3) // Not connected by default on the NFC Shield 22 | 23 | class NfcAdapter { 24 | public: 25 | NfcAdapter(PN532Interface &interface); 26 | 27 | ~NfcAdapter(void); 28 | void begin(boolean verbose=true); 29 | boolean tagPresent(unsigned long timeout=0); // tagAvailable 30 | NfcTag read(); 31 | boolean write(NdefMessage& ndefMessage); 32 | // erase tag by writing an empty NDEF record 33 | boolean erase(); 34 | // format a tag as NDEF 35 | boolean format(); 36 | // reset tag back to factory state 37 | boolean clean(); 38 | private: 39 | PN532* shield; 40 | byte uid[7]; // Buffer to store the returned UID 41 | unsigned int uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 42 | unsigned int guessTagType(); 43 | }; 44 | 45 | #endif 46 | -------------------------------------------------------------------------------- /NDEF/NfcDriver.h: -------------------------------------------------------------------------------- 1 | // eventually the NFC drivers should extend this class 2 | class NfcDriver 3 | { 4 | public: 5 | virtual NfcTag read(uint8_t * uid, int uidLength) = 0; 6 | virtual boolean write(NdefMessage& message, uint8_t * uid, int uidLength) = 0; 7 | // erase() 8 | // format() 9 | } -------------------------------------------------------------------------------- /NDEF/NfcTag.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | NfcTag::NfcTag() 4 | { 5 | _uid = 0; 6 | _uidLength = 0; 7 | _tagType = "Unknown"; 8 | _ndefMessage = (NdefMessage*)NULL; 9 | } 10 | 11 | NfcTag::NfcTag(byte *uid, unsigned int uidLength) 12 | { 13 | _uid = uid; 14 | _uidLength = uidLength; 15 | _tagType = "Unknown"; 16 | _ndefMessage = (NdefMessage*)NULL; 17 | } 18 | 19 | NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType) 20 | { 21 | _uid = uid; 22 | _uidLength = uidLength; 23 | _tagType = tagType; 24 | _ndefMessage = (NdefMessage*)NULL; 25 | } 26 | 27 | NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, NdefMessage& ndefMessage) 28 | { 29 | _uid = uid; 30 | _uidLength = uidLength; 31 | _tagType = tagType; 32 | _ndefMessage = new NdefMessage(ndefMessage); 33 | } 34 | 35 | // I don't like this version, but it will use less memory 36 | NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength) 37 | { 38 | _uid = uid; 39 | _uidLength = uidLength; 40 | _tagType = tagType; 41 | _ndefMessage = new NdefMessage(ndefData, ndefDataLength); 42 | } 43 | 44 | NfcTag::~NfcTag() 45 | { 46 | delete _ndefMessage; 47 | } 48 | 49 | NfcTag& NfcTag::operator=(const NfcTag& rhs) 50 | { 51 | if (this != &rhs) 52 | { 53 | delete _ndefMessage; 54 | _uid = rhs._uid; 55 | _uidLength = rhs._uidLength; 56 | _tagType = rhs._tagType; 57 | // TODO do I need a copy here? 58 | _ndefMessage = rhs._ndefMessage; 59 | } 60 | return *this; 61 | } 62 | 63 | uint8_t NfcTag::getUidLength() 64 | { 65 | return _uidLength; 66 | } 67 | 68 | void NfcTag::getUid(byte *uid, unsigned int uidLength) 69 | { 70 | memcpy(uid, _uid, _uidLength < uidLength ? _uidLength : uidLength); 71 | } 72 | 73 | String NfcTag::getUidString() 74 | { 75 | String uidString = ""; 76 | for (int i = 0; i < _uidLength; i++) 77 | { 78 | if (i > 0) 79 | { 80 | uidString += " "; 81 | } 82 | 83 | if (_uid[i] < 0xF) 84 | { 85 | uidString += "0"; 86 | } 87 | 88 | uidString += String((unsigned int)_uid[i], (unsigned char)HEX); 89 | } 90 | uidString.toUpperCase(); 91 | return uidString; 92 | } 93 | 94 | String NfcTag::getTagType() 95 | { 96 | return _tagType; 97 | } 98 | 99 | boolean NfcTag::hasNdefMessage() 100 | { 101 | return (_ndefMessage != NULL); 102 | } 103 | 104 | NdefMessage NfcTag::getNdefMessage() 105 | { 106 | return *_ndefMessage; 107 | } 108 | 109 | void NfcTag::print() 110 | { 111 | Serial.print(F("NFC Tag - "));Serial.println(_tagType); 112 | Serial.print(F("UID "));Serial.println(getUidString()); 113 | if (_ndefMessage == NULL) 114 | { 115 | Serial.println(F("\nNo NDEF Message")); 116 | } 117 | else 118 | { 119 | _ndefMessage->print(); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /NDEF/NfcTag.h: -------------------------------------------------------------------------------- 1 | #ifndef NfcTag_h 2 | #define NfcTag_h 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | class NfcTag 9 | { 10 | public: 11 | NfcTag(); 12 | NfcTag(byte *uid, unsigned int uidLength); 13 | NfcTag(byte *uid, unsigned int uidLength, String tagType); 14 | NfcTag(byte *uid, unsigned int uidLength, String tagType, NdefMessage& ndefMessage); 15 | NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength); 16 | ~NfcTag(void); 17 | NfcTag& operator=(const NfcTag& rhs); 18 | uint8_t getUidLength(); 19 | void getUid(byte *uid, unsigned int uidLength); 20 | String getUidString(); 21 | String getTagType(); 22 | boolean hasNdefMessage(); 23 | NdefMessage getNdefMessage(); 24 | void print(); 25 | private: 26 | byte *_uid; 27 | unsigned int _uidLength; 28 | String _tagType; // Mifare Classic, NFC Forum Type {1,2,3,4}, Unknown 29 | NdefMessage* _ndefMessage; 30 | // TODO capacity 31 | // TODO isFormatted 32 | }; 33 | 34 | #endif -------------------------------------------------------------------------------- /NDEF/README.md: -------------------------------------------------------------------------------- 1 | # NDEF Library for Arduino 2 | 3 | Read and Write NDEF messages on NFC Tags with Arduino. 4 | 5 | NFC Data Exchange Format (NDEF) is a common data format that operates across all NFC devices, regardless of the underlying tag or device technology. 6 | 7 | This code works with the [Adafruit NFC Shield](https://www.adafruit.com/products/789), [Seeed Studio NFC Shield v2.0](http://www.seeedstudio.com/depot/nfc-shield-v20-p-1370.html) and the [Seeed Studio NFC Shield](http://www.seeedstudio.com/depot/nfc-shield-p-916.html?cPath=73). The library supports I2C for the Adafruit shield and SPI with the Seeed shields. The Adafruit Shield can also be modified to use SPI. It should also work with the [Adafruit NFC Breakout Board](https://www.adafruit.com/products/364). 8 | 9 | ### Supports 10 | - Reading from Mifare Classic Tags with 4 byte UIDs. 11 | - Writing to Mifare Classic Tags with 4 byte UIDs. 12 | - Reading from Mifare Ultralight tags. 13 | - Writing to Mifare Ultralight tags. 14 | - Peer to Peer with the Seeed Studio shield 15 | 16 | ### Requires 17 | 18 | [Yihui Xiong's PN532 Library](https://github.com/Seeed-Studio/PN532) 19 | 20 | ## Getting Started 21 | 22 | To use the Ndef library in your code, include the following in your sketch 23 | 24 | For the Adafruit Shield using I2C 25 | 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | PN532_I2C pn532_i2c(Wire); 32 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 33 | 34 | For the Seeed Shield using SPI 35 | 36 | #include 37 | #include 38 | #include 39 | #include 40 | 41 | PN532_SPI pn532spi(SPI, 10); 42 | NfcAdapter nfc = NfcAdapter(pn532spi); 43 | 44 | ### NfcAdapter 45 | 46 | The user interacts with the NfcAdapter to read and write NFC tags using the NFC shield. 47 | 48 | Read a message from a tag 49 | 50 | if (nfc.tagPresent()) { 51 | NfcTag tag = nfc.read(); 52 | tag.print(); 53 | } 54 | 55 | Write a message to a tag 56 | 57 | if (nfc.tagPresent()) { 58 | NdefMessage message = NdefMessage(); 59 | message.addTextRecord("Hello, Arduino!"); 60 | success = nfc.write(message); 61 | } 62 | 63 | Erase a tag. Tags are erased by writing an empty NDEF message. Tags are not zeroed out the old data may still be read off a tag using an application like [NXP's TagInfo](https://play.google.com/store/apps/details?id=com.nxp.taginfolite&hl=en). 64 | 65 | if (nfc.tagPresent()) { 66 | success = nfc.erase(); 67 | } 68 | 69 | 70 | Format a Mifare Classic tag as NDEF. 71 | 72 | if (nfc.tagPresent()) { 73 | success = nfc.format(); 74 | } 75 | 76 | 77 | Clean a tag. Cleaning resets a tag back to a factory-like state. For Mifare Classic, tag is zeroed and reformatted as Mifare Classic (non-NDEF). For Mifare Ultralight, the tag is zeroed and left empty. 78 | 79 | if (nfc.tagPresent()) { 80 | success = nfc.clean(); 81 | } 82 | 83 | 84 | ### NfcTag 85 | 86 | Reading a tag with the shield, returns a NfcTag object. The NfcTag object contains meta data about the tag UID, technology, size. When an NDEF tag is read, the NfcTag object contains a NdefMessage. 87 | 88 | ### NdefMessage 89 | 90 | A NdefMessage consist of one or more NdefRecords. 91 | 92 | The NdefMessage object has helper methods for adding records. 93 | 94 | ndefMessage.addTextRecord("hello, world"); 95 | ndefMessage.addUriRecord("http://arduino.cc"); 96 | 97 | The NdefMessage object is responsible for encoding NdefMessage into bytes so it can be written to a tag. The NdefMessage also decodes bytes read from a tag back into a NdefMessage object. 98 | 99 | ### NdefRecord 100 | 101 | A NdefRecord carries a payload and info about the payload within a NdefMessage. 102 | 103 | ### Peer to Peer 104 | 105 | Peer to Peer is provided by the LLCP and SNEP support in the [Seeed Studio library](https://github.com/Seeed-Studio/PN532). P2P requires SPI and has only been tested with the Seeed Studio shield. Peer to Peer was tested between Arduino and Android or BlackBerry 10. (Unfortunately Windows Phone 8 did not work.) See [P2P_Send](examples/P2P_Send/P2P_Send.ino) and [P2P_Receive](examples/P2P_Receive/P2P_Receive.ino) for more info. 106 | 107 | ### Specifications 108 | 109 | This code is based on the "NFC Data Exchange Format (NDEF) Technical Specification" and the "Record Type Definition Technical Specifications" that can be downloaded from the [NFC Forum](http://www.nfc-forum.org/specs/spec_license). 110 | 111 | ### Tests 112 | 113 | To run the tests, you'll need [ArduinoUnit](https://github.com/mmurdoch/arduinounit). To "install", I clone the repo to my home directory and symlink the source into ~/Documents/Arduino/libraries/ArduinoUnit. 114 | 115 | $ cd ~ 116 | $ git clone git@github.com:mmurdoch/arduinounit.git 117 | $ cd ~/Documents/Arduino/libraries/ 118 | $ ln -s ~/arduinounit/src ArduinoUnit 119 | 120 | Tests can be run on an Uno without a NFC shield, since the NDEF logic is what is being tested. 121 | 122 | ## Warning 123 | 124 | This software is in development. It works for the happy path. Error handling could use improvement. It runs out of memory, especially on the Uno board. Use small messages with the Uno. The Due board can write larger messages. Please submit patches. 125 | 126 | ## Book 127 | Need more info? Check out my book [Beginning NFC: Near Field Communication with Arduino, Android, and PhoneGap](http://shop.oreilly.com/product/0636920021193.do) 128 | 129 | ![Beginning NFC](http://akamaicovers.oreilly.com/images/0636920021193/cat.gif) 130 | 131 | ## License 132 | 133 | [BSD License](https://github.com/don/Ndef/blob/master/LICENSE.txt) (c) 2013-2014, Don Coleman 134 | -------------------------------------------------------------------------------- /NDEF/examples/CleanTag/CleanTag.ino: -------------------------------------------------------------------------------- 1 | // Clean resets a tag back to factory-like state 2 | // For Mifare Classic, tag is zero'd and reformatted as Mifare Classic 3 | // For Mifare Ultralight, tags is zero'd and left empty 4 | 5 | #if 0 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | PN532_SPI pn532spi(SPI, 10); 12 | NfcAdapter nfc = NfcAdapter(pn532spi); 13 | #else 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | PN532_I2C pn532_i2c(Wire); 21 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 22 | #endif 23 | 24 | void setup(void) { 25 | Serial.begin(9600); 26 | Serial.println("NFC Tag Cleaner"); 27 | nfc.begin(); 28 | } 29 | 30 | void loop(void) { 31 | 32 | Serial.println("\nPlace a tag on the NFC reader to clean."); 33 | 34 | if (nfc.tagPresent()) { 35 | 36 | bool success = nfc.clean(); 37 | if (success) { 38 | Serial.println("\nSuccess, tag restored to factory state."); 39 | } else { 40 | Serial.println("\nError, unable to clean tag."); 41 | } 42 | 43 | } 44 | delay(5000); 45 | } 46 | -------------------------------------------------------------------------------- /NDEF/examples/EraseTag/EraseTag.ino: -------------------------------------------------------------------------------- 1 | // Erases a NFC tag by writing an empty NDEF message 2 | 3 | #if 0 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | PN532_SPI pn532spi(SPI, 10); 10 | NfcAdapter nfc = NfcAdapter(pn532spi); 11 | #else 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | PN532_I2C pn532_i2c(Wire); 19 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 20 | #endif 21 | 22 | void setup(void) { 23 | Serial.begin(9600); 24 | Serial.println("NFC Tag Eraser"); 25 | nfc.begin(); 26 | } 27 | 28 | void loop(void) { 29 | Serial.println("\nPlace a tag on the NFC reader to erase."); 30 | 31 | if (nfc.tagPresent()) { 32 | 33 | bool success = nfc.erase(); 34 | if (success) { 35 | Serial.println("\nSuccess, tag contains an empty record."); 36 | } else { 37 | Serial.println("\nUnable to erase tag."); 38 | } 39 | 40 | } 41 | delay(5000); 42 | } 43 | -------------------------------------------------------------------------------- /NDEF/examples/FormatTag/FormatTag.ino: -------------------------------------------------------------------------------- 1 | // Formats a Mifare Classic tags as an NDEF tag 2 | // This will fail if the tag is already formatted NDEF 3 | // nfc.clean will turn a NDEF formatted Mifare Classic tag back to the Mifare Classic format 4 | 5 | #if 0 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | PN532_SPI pn532spi(SPI, 10); 12 | NfcAdapter nfc = NfcAdapter(pn532spi); 13 | #else 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | 20 | PN532_I2C pn532_i2c(Wire); 21 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 22 | #endif 23 | 24 | void setup(void) { 25 | Serial.begin(9600); 26 | Serial.println("NDEF Formatter"); 27 | nfc.begin(); 28 | } 29 | 30 | void loop(void) { 31 | 32 | Serial.println("\nPlace an unformatted Mifare Classic tag on the reader."); 33 | if (nfc.tagPresent()) { 34 | 35 | bool success = nfc.format(); 36 | if (success) { 37 | Serial.println("\nSuccess, tag formatted as NDEF."); 38 | } else { 39 | Serial.println("\nFormat failed."); 40 | } 41 | 42 | } 43 | delay(5000); 44 | } 45 | -------------------------------------------------------------------------------- /NDEF/examples/P2P_Receive/P2P_Receive.ino: -------------------------------------------------------------------------------- 1 | // Receive a NDEF message from a Peer 2 | // Requires SPI. Tested with Seeed Studio NFC Shield v2 3 | 4 | #include "SPI.h" 5 | #include "PN532_SPI.h" 6 | #include "snep.h" 7 | #include "NdefMessage.h" 8 | 9 | PN532_SPI pn532spi(SPI, 10); 10 | SNEP nfc(pn532spi); 11 | uint8_t ndefBuf[128]; 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | Serial.println("NFC Peer to Peer Example - Receive Message"); 16 | } 17 | 18 | void loop() { 19 | Serial.println("Waiting for message from Peer"); 20 | int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf)); 21 | if (msgSize > 0) { 22 | NdefMessage msg = NdefMessage(ndefBuf, msgSize); 23 | msg.print(); 24 | Serial.println("\nSuccess"); 25 | } else { 26 | Serial.println("Failed"); 27 | } 28 | delay(3000); 29 | } 30 | 31 | -------------------------------------------------------------------------------- /NDEF/examples/P2P_Receive_LCD/P2P_Receive_LCD.ino: -------------------------------------------------------------------------------- 1 | // Receive a NDEF message from a Peer and 2 | // display the payload of the first record on a LCD 3 | // 4 | // SeeedStudio NFC shield http://www.seeedstudio.com/depot/NFC-Shield-V20-p-1370.html 5 | // LCD using the Adafruit backpack http://adafru.it/292 6 | // Adafruit Liquid Crystal library https://github.com/adafruit/LiquidCrystal 7 | // Use a Android of BlackBerry phone to send a message to the NFC shield 8 | 9 | #include "SPI.h" 10 | #include "PN532_SPI.h" 11 | #include "snep.h" 12 | #include "NdefMessage.h" 13 | 14 | #include "Wire.h" 15 | #include "LiquidCrystal.h" 16 | 17 | PN532_SPI pn532spi(SPI, 10); 18 | SNEP nfc(pn532spi); 19 | uint8_t ndefBuf[128]; 20 | 21 | // Connect via i2c, default address #0 (A0-A2 not jumpered) 22 | LiquidCrystal lcd(0); 23 | 24 | void setup() { 25 | Serial.begin(9600); 26 | // set up the LCD's number of rows and columns: 27 | lcd.begin(16, 2); 28 | Serial.println("NFC Peer to Peer Example - Receive Message"); 29 | } 30 | 31 | void loop() { 32 | Serial.println("Waiting for message from a peer"); 33 | int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf)); 34 | if (msgSize > 0) { 35 | NdefMessage msg = NdefMessage(ndefBuf, msgSize); 36 | msg.print(); 37 | 38 | NdefRecord record = msg.getRecord(0); 39 | 40 | int payloadLength = record.getPayloadLength(); 41 | byte payload[payloadLength]; 42 | record.getPayload(payload); 43 | 44 | // The TNF and Type are used to determine how your application processes the payload 45 | // There's no generic processing for the payload, it's returned as a byte[] 46 | int startChar = 0; 47 | if (record.getTnf() == TNF_WELL_KNOWN && record.getType() == "T") { // text message 48 | // skip the language code 49 | startChar = payload[0] + 1; 50 | } else if (record.getTnf() == TNF_WELL_KNOWN && record.getType() == "U") { // URI 51 | // skip the url prefix (future versions should decode) 52 | startChar = 1; 53 | } 54 | 55 | // Force the data into a String (might fail for some content) 56 | // Real code should use smarter processing 57 | String payloadAsString = ""; 58 | for (int c = startChar; c < payloadLength; c++) { 59 | payloadAsString += (char)payload[c]; 60 | } 61 | 62 | // print on the LCD display 63 | lcd.setCursor(0, 0); 64 | lcd.print(payloadAsString); 65 | 66 | Serial.println("\nSuccess"); 67 | } else { 68 | Serial.println("Failed"); 69 | } 70 | delay(3000); 71 | } 72 | -------------------------------------------------------------------------------- /NDEF/examples/P2P_Send/P2P_Send.ino: -------------------------------------------------------------------------------- 1 | // Sends a NDEF Message to a Peer 2 | // Requires SPI. Tested with Seeed Studio NFC Shield v2 3 | 4 | #include "SPI.h" 5 | #include "PN532_SPI.h" 6 | #include "snep.h" 7 | #include "NdefMessage.h" 8 | 9 | PN532_SPI pn532spi(SPI, 10); 10 | SNEP nfc(pn532spi); 11 | uint8_t ndefBuf[128]; 12 | 13 | void setup() { 14 | Serial.begin(9600); 15 | Serial.println("NFC Peer to Peer Example - Send Message"); 16 | } 17 | 18 | void loop() { 19 | Serial.println("Send a message to Peer"); 20 | 21 | NdefMessage message = NdefMessage(); 22 | message.addUriRecord("http://shop.oreilly.com/product/mobile/0636920021193.do"); 23 | //message.addUriRecord("http://arduino.cc"); 24 | //message.addUriRecord("https://github.com/don/NDEF"); 25 | 26 | 27 | int messageSize = message.getEncodedSize(); 28 | if (messageSize > sizeof(ndefBuf)) { 29 | Serial.println("ndefBuf is too small"); 30 | while (1) { 31 | } 32 | } 33 | 34 | message.encode(ndefBuf); 35 | if (0 >= nfc.write(ndefBuf, messageSize)) { 36 | Serial.println("Failed"); 37 | } else { 38 | Serial.println("Success"); 39 | } 40 | 41 | delay(3000); 42 | } 43 | -------------------------------------------------------------------------------- /NDEF/examples/ReadTag/ReadTag.ino: -------------------------------------------------------------------------------- 1 | 2 | #if 0 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | PN532_SPI pn532spi(SPI, 10); 9 | NfcAdapter nfc = NfcAdapter(pn532spi); 10 | #else 11 | 12 | #include 13 | #include 14 | #include 15 | #include 16 | 17 | PN532_I2C pn532_i2c(Wire); 18 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 19 | #endif 20 | 21 | void setup(void) { 22 | Serial.begin(9600); 23 | Serial.println("NDEF Reader"); 24 | nfc.begin(); 25 | } 26 | 27 | void loop(void) { 28 | Serial.println("\nScan a NFC tag\n"); 29 | if (nfc.tagPresent()) 30 | { 31 | NfcTag tag = nfc.read(); 32 | tag.print(); 33 | } 34 | delay(5000); 35 | } -------------------------------------------------------------------------------- /NDEF/examples/ReadTagExtended/ReadTagExtended.ino: -------------------------------------------------------------------------------- 1 | #if 0 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | PN532_SPI pn532spi(SPI, 10); 8 | NfcAdapter nfc = NfcAdapter(pn532spi); 9 | #else 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | PN532_I2C pn532_i2c(Wire); 17 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 18 | #endif 19 | 20 | void setup(void) { 21 | Serial.begin(9600); 22 | Serial.println("NDEF Reader"); 23 | nfc.begin(); 24 | } 25 | 26 | void loop(void) { 27 | Serial.println("\nScan a NFC tag\n"); 28 | 29 | if (nfc.tagPresent()) 30 | { 31 | NfcTag tag = nfc.read(); 32 | Serial.println(tag.getTagType()); 33 | Serial.print("UID: ");Serial.println(tag.getUidString()); 34 | 35 | if (tag.hasNdefMessage()) // every tag won't have a message 36 | { 37 | 38 | NdefMessage message = tag.getNdefMessage(); 39 | Serial.print("\nThis NFC Tag contains an NDEF Message with "); 40 | Serial.print(message.getRecordCount()); 41 | Serial.print(" NDEF Record"); 42 | if (message.getRecordCount() != 1) { 43 | Serial.print("s"); 44 | } 45 | Serial.println("."); 46 | 47 | // cycle through the records, printing some info from each 48 | int recordCount = message.getRecordCount(); 49 | for (int i = 0; i < recordCount; i++) 50 | { 51 | Serial.print("\nNDEF Record ");Serial.println(i+1); 52 | NdefRecord record = message.getRecord(i); 53 | // NdefRecord record = message[i]; // alternate syntax 54 | 55 | Serial.print(" TNF: ");Serial.println(record.getTnf()); 56 | Serial.print(" Type: ");Serial.println(record.getType()); // will be "" for TNF_EMPTY 57 | 58 | // The TNF and Type should be used to determine how your application processes the payload 59 | // There's no generic processing for the payload, it's returned as a byte[] 60 | int payloadLength = record.getPayloadLength(); 61 | byte payload[payloadLength]; 62 | record.getPayload(payload); 63 | 64 | // Print the Hex and Printable Characters 65 | Serial.print(" Payload (HEX): "); 66 | PrintHexChar(payload, payloadLength); 67 | 68 | // Force the data into a String (might work depending on the content) 69 | // Real code should use smarter processing 70 | String payloadAsString = ""; 71 | for (int c = 0; c < payloadLength; c++) { 72 | payloadAsString += (char)payload[c]; 73 | } 74 | Serial.print(" Payload (as String): "); 75 | Serial.println(payloadAsString); 76 | 77 | // id is probably blank and will return "" 78 | String uid = record.getId(); 79 | if (uid != "") { 80 | Serial.print(" ID: ");Serial.println(uid); 81 | } 82 | } 83 | } 84 | } 85 | delay(3000); 86 | } 87 | -------------------------------------------------------------------------------- /NDEF/examples/WriteTag/WriteTag.ino: -------------------------------------------------------------------------------- 1 | #if 0 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | PN532_SPI pn532spi(SPI, 10); 8 | NfcAdapter nfc = NfcAdapter(pn532spi); 9 | #else 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | PN532_I2C pn532_i2c(Wire); 17 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 18 | #endif 19 | 20 | void setup() { 21 | Serial.begin(9600); 22 | Serial.println("NDEF Writer"); 23 | nfc.begin(); 24 | } 25 | 26 | void loop() { 27 | Serial.println("\nPlace a formatted Mifare Classic NFC tag on the reader."); 28 | if (nfc.tagPresent()) { 29 | NdefMessage message = NdefMessage(); 30 | message.addUriRecord("http://arduino.cc"); 31 | 32 | bool success = nfc.write(message); 33 | if (success) { 34 | Serial.println("Success. Try reading this tag with your phone."); 35 | } else { 36 | Serial.println("Write failed."); 37 | } 38 | } 39 | delay(5000); 40 | } -------------------------------------------------------------------------------- /NDEF/examples/WriteTagMultipleRecords/WriteTagMultipleRecords.ino: -------------------------------------------------------------------------------- 1 | #if 0 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | PN532_SPI pn532spi(SPI, 10); 8 | NfcAdapter nfc = NfcAdapter(pn532spi); 9 | #else 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | PN532_I2C pn532_i2c(Wire); 17 | NfcAdapter nfc = NfcAdapter(pn532_i2c); 18 | #endif 19 | 20 | void setup() { 21 | Serial.begin(9600); 22 | Serial.println("NDEF Writer"); 23 | nfc.begin(); 24 | } 25 | 26 | void loop() { 27 | Serial.println("\nPlace a formatted Mifare Classic NFC tag on the reader."); 28 | if (nfc.tagPresent()) { 29 | NdefMessage message = NdefMessage(); 30 | message.addTextRecord("Hello, Arduino!"); 31 | message.addUriRecord("http://arduino.cc"); 32 | message.addTextRecord("Goodbye, Arduino!"); 33 | boolean success = nfc.write(message); 34 | if (success) { 35 | Serial.println("Success. Try reading this tag with your phone."); 36 | } else { 37 | Serial.println("Write failed"); 38 | } 39 | } 40 | delay(3000); 41 | } 42 | -------------------------------------------------------------------------------- /NDEF/keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For Ndef 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | MifareClassic KEYWORD1 10 | MifareUltralight KEYWORD1 11 | NdefMessage KEYWORD1 12 | NdefRecord KEYWORD1 13 | NfcAdapter KEYWORD1 14 | NfcDriver KEYWORD1 15 | NfcTag KEYWORD1 16 | 17 | ####################################### 18 | # Methods and Functions (KEYWORD2) 19 | ####################################### 20 | 21 | addEmptyRecord KEYWORD2 22 | addMimeMediaRecord KEYWORD2 23 | addRecord KEYWORD2 24 | addTextRecord KEYWORD2 25 | addUriRecord KEYWORD2 26 | begin KEYWORD2 27 | encode KEYWORD2 28 | erase KEYWORD2 29 | format KEYWORD2 30 | getEncodedSize KEYWORD2 31 | getId KEYWORD2 32 | getIdLength KEYWORD2 33 | getNdefMessage KEYWORD2 34 | getPayload KEYWORD2 35 | getPayloadLength KEYWORD2 36 | getRecord KEYWORD2 37 | getRecordCount KEYWORD2 38 | getTagType KEYWORD2 39 | getTnf KEYWORD2 40 | getType KEYWORD2 41 | getTypeLength KEYWORD2 42 | getUid KEYWORD2 43 | getUidLength KEYWORD2 44 | getUidString KEYWORD2 45 | hasNdefMessage KEYWORD2 46 | print KEYWORD2 47 | read KEYWORD2 48 | setId KEYWORD2 49 | setPayload KEYWORD2 50 | setTnf KEYWORD2 51 | setType KEYWORD2 52 | share KEYWORD2 53 | tagPresent KEYWORD2 54 | unshare KEYWORD2 55 | write KEYWORD2 56 | -------------------------------------------------------------------------------- /NDEF/tests/NdefMemoryTest/NdefMemoryTest.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | void leakCheck(void (*callback)()) 8 | { 9 | int start = freeMemory(); 10 | (*callback)(); 11 | int end = freeMemory(); 12 | Serial.println((end - start), DEC); 13 | } 14 | 15 | // Custom Assertion 16 | void assertNoLeak(void (*callback)()) 17 | { 18 | int start = freeMemory(); 19 | (*callback)(); 20 | int end = freeMemory(); 21 | assertEqual(0, (start - end)); 22 | } 23 | 24 | void record() 25 | { 26 | NdefRecord* r = new NdefRecord(); 27 | delete r; 28 | } 29 | 30 | void emptyRecord() 31 | { 32 | NdefRecord* r = new NdefRecord(); 33 | r->print(); 34 | delete r; 35 | } 36 | 37 | void textRecord() 38 | { 39 | NdefRecord* r = new NdefRecord(); 40 | r->setTnf(0x1); 41 | uint8_t type[] = { 0x54 }; 42 | r->setType(type, sizeof(type)); 43 | uint8_t payload[] = { 0x1A, 0x1B, 0x1C }; 44 | r->setPayload(payload, sizeof(payload)); 45 | r->print(); 46 | delete r; 47 | } 48 | 49 | void recordMallocZero() 50 | { 51 | NdefRecord r = NdefRecord(); 52 | String type = r.getType(); 53 | String id = r.getId(); 54 | byte payload[r.getPayloadLength()]; 55 | r.getPayload(payload); 56 | } 57 | 58 | // this is OK 59 | void emptyMessage() 60 | { 61 | NdefMessage* m = new NdefMessage(); 62 | delete m; 63 | } 64 | 65 | // this is OK 66 | void printEmptyMessage() 67 | { 68 | NdefMessage* m = new NdefMessage(); 69 | m->print(); 70 | delete m; 71 | } 72 | 73 | // this is OK 74 | void printEmptyMessageNoNew() 75 | { 76 | NdefMessage m = NdefMessage(); 77 | m.print(); 78 | } 79 | 80 | void messageWithTextRecord() 81 | { 82 | NdefMessage m = NdefMessage(); 83 | m.addTextRecord("foo"); 84 | m.print(); 85 | } 86 | 87 | void messageWithEmptyRecord() 88 | { 89 | NdefMessage m = NdefMessage(); 90 | NdefRecord r = NdefRecord(); 91 | m.addRecord(r); 92 | m.print(); 93 | } 94 | 95 | void messageWithoutHelper() 96 | { 97 | NdefMessage m = NdefMessage(); 98 | NdefRecord r = NdefRecord(); 99 | r.setTnf(1); 100 | uint8_t type[] = { 0x54 }; 101 | r.setType(type, sizeof(type)); 102 | uint8_t payload[] = { 0x02, 0x65, 0x6E, 0x66, 0x6F, 0x6F }; 103 | r.setPayload(payload, sizeof(payload)); 104 | m.addRecord(r); 105 | m.print(); 106 | } 107 | 108 | void messageWithId() 109 | { 110 | NdefMessage m = NdefMessage(); 111 | NdefRecord r = NdefRecord(); 112 | r.setTnf(1); 113 | uint8_t type[] = { 0x54 }; 114 | r.setType(type, sizeof(type)); 115 | uint8_t payload[] = { 0x02, 0x65, 0x6E, 0x66, 0x6F, 0x6F }; 116 | r.setPayload(payload, sizeof(payload)); 117 | uint8_t id[] = { 0x0, 0x0, 0x0 }; 118 | r.setId(id, sizeof(id)); 119 | m.addRecord(r); 120 | m.print(); 121 | } 122 | 123 | void message80() 124 | { 125 | NdefMessage message = NdefMessage(); 126 | message.addTextRecord("This record is 80 characters.X01234567890123456789012345678901234567890123456789"); 127 | //message.print(); 128 | } 129 | 130 | void message100() 131 | { 132 | NdefMessage message = NdefMessage(); 133 | message.addTextRecord("This record is 100 characters.0123456789012345678901234567890123456789012345678901234567890123456789"); 134 | //message.print(); 135 | } 136 | 137 | void message120() 138 | { 139 | NdefMessage message = NdefMessage(); 140 | message.addTextRecord("This record is 120 characters.012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"); 141 | //message.print(); 142 | } 143 | 144 | void setup() { 145 | Serial.begin(9600); 146 | Serial.println("\n"); 147 | Serial.println(F("=========")); 148 | Serial.println(freeMemory()); 149 | Serial.println(F("=========")); 150 | } 151 | 152 | test(memoryKludgeEnd) 153 | { 154 | // TODO ensure the output matches start 155 | Serial.println(F("=========")); 156 | Serial.print("End ");Serial.println(freeMemory()); 157 | Serial.println(F("=========")); 158 | } 159 | 160 | test(recordLeaks) 161 | { 162 | assertNoLeak(&record); 163 | assertNoLeak(&emptyRecord); 164 | assertNoLeak(&textRecord); 165 | } 166 | 167 | test(recordAccessorLeaks) 168 | { 169 | assertNoLeak(&recordMallocZero); 170 | } 171 | 172 | test(messageLeaks) 173 | { 174 | assertNoLeak(&emptyMessage); 175 | assertNoLeak(&printEmptyMessage); 176 | assertNoLeak(&printEmptyMessageNoNew); 177 | assertNoLeak(&messageWithTextRecord); 178 | assertNoLeak(&messageWithEmptyRecord); 179 | assertNoLeak(&messageWithoutHelper); 180 | assertNoLeak(&messageWithId); 181 | } 182 | 183 | test(messageOneBigRecord) 184 | { 185 | assertNoLeak(&message80); 186 | // The next 2 fail. Maybe out of memory? Look into helper methods 187 | //assertNoLeak(&message100); 188 | //assertNoLeak(&message120); 189 | } 190 | 191 | test(memoryKludgeStart) 192 | { 193 | Serial.println(F("---------")); 194 | Serial.print("Start ");Serial.println(freeMemory()); 195 | Serial.println(F("---------")); 196 | } 197 | 198 | void loop() { 199 | Test::run(); 200 | } 201 | -------------------------------------------------------------------------------- /NDEF/tests/NdefMessageTest/NdefMessageTest.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Custom Assertion 8 | void assertNoLeak(void (*callback)()) 9 | { 10 | int start = freeMemory(); 11 | (*callback)(); 12 | int end = freeMemory(); 13 | assertEqual(0, (start - end)); 14 | } 15 | 16 | void assertBytesEqual(const uint8_t* expected, const uint8_t* actual, int size) { 17 | for (int i = 0; i < size; i++) { 18 | // Serial.print("> ");Serial.print(expected[i]);Serial.print(" ");Serial.println(actual[i]); 19 | assertEqual(expected[i], actual[i]); 20 | } 21 | } 22 | 23 | void setup() { 24 | Serial.begin(9600); 25 | } 26 | 27 | test(messageDelete) 28 | { 29 | int start = freeMemory(); 30 | 31 | NdefMessage* m1 = new NdefMessage(); 32 | m1->addTextRecord("Foo"); 33 | delete m1; 34 | 35 | int end = freeMemory(); 36 | // Serial.print("Start ");Serial.println(start); 37 | // Serial.print("End ");Serial.println(end); 38 | assertEqual(0, (start-end)); 39 | } 40 | 41 | 42 | test(assign) 43 | { 44 | int start = freeMemory(); 45 | 46 | if (true) // bogus block so automatic storage duration objects are deleted 47 | { 48 | NdefMessage* m1 = new NdefMessage(); 49 | m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union..."); 50 | 51 | NdefMessage* m2 = new NdefMessage(); 52 | 53 | *m2 = *m1; 54 | 55 | NdefRecord r1 = m1->getRecord(0); 56 | NdefRecord r2 = m2->getRecord(0); 57 | 58 | assertEqual(r1.getTnf(), r2.getTnf()); 59 | assertEqual(r1.getTypeLength(), r2.getTypeLength()); 60 | assertEqual(r1.getPayloadLength(), r2.getPayloadLength()); 61 | assertEqual(r1.getIdLength(), r2.getIdLength()); 62 | 63 | byte p1[r1.getPayloadLength()]; 64 | byte p2[r2.getPayloadLength()]; 65 | r1.getPayload(p1); 66 | r2.getPayload(p2); 67 | 68 | int size = r1.getPayloadLength(); 69 | assertBytesEqual(p1, p2, size); 70 | 71 | delete m2; 72 | delete m1; 73 | } 74 | 75 | int end = freeMemory(); 76 | assertEqual(0, (start-end)); 77 | } 78 | 79 | test(assign2) 80 | { 81 | int start = freeMemory(); 82 | 83 | if (true) // bogus block so automatic storage duration objects are deleted 84 | { 85 | NdefMessage m1 = NdefMessage(); 86 | m1.addTextRecord("We the People of the United States, in Order to form a more perfect Union..."); 87 | 88 | NdefMessage m2 = NdefMessage(); 89 | 90 | m2 = m1; 91 | 92 | NdefRecord r1 = m1.getRecord(0); 93 | NdefRecord r2 = m2.getRecord(0); 94 | 95 | assertEqual(r1.getTnf(), r2.getTnf()); 96 | assertEqual(r1.getTypeLength(), r2.getTypeLength()); 97 | assertEqual(r1.getPayloadLength(), r2.getPayloadLength()); 98 | assertEqual(r1.getIdLength(), r2.getIdLength()); 99 | 100 | // TODO check type 101 | 102 | byte p1[r1.getPayloadLength()]; 103 | byte p2[r2.getPayloadLength()]; 104 | r1.getPayload(p1); 105 | r2.getPayload(p2); 106 | 107 | int size = r1.getPayloadLength(); 108 | assertBytesEqual(p1, p2, size); 109 | } 110 | 111 | int end = freeMemory(); 112 | assertEqual(0, (start-end)); 113 | } 114 | 115 | test(assign3) 116 | { 117 | int start = freeMemory(); 118 | 119 | if (true) // bogus block so automatic storage duration objects are deleted 120 | { 121 | 122 | NdefMessage* m1 = new NdefMessage(); 123 | m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union..."); 124 | 125 | NdefMessage* m2 = new NdefMessage(); 126 | 127 | *m2 = *m1; 128 | 129 | delete m1; 130 | 131 | NdefRecord r = m2->getRecord(0); 132 | 133 | assertEqual(TNF_WELL_KNOWN, r.getTnf()); 134 | assertEqual(1, r.getTypeLength()); 135 | assertEqual(79, r.getPayloadLength()); 136 | assertEqual(0, r.getIdLength()); 137 | 138 | ::String s = "We the People of the United States, in Order to form a more perfect Union..."; 139 | byte payload[s.length() + 1]; 140 | s.getBytes(payload, sizeof(payload)); 141 | 142 | byte p[r.getPayloadLength()]; 143 | r.getPayload(p); 144 | assertBytesEqual(payload, p+3, s.length()); 145 | 146 | delete m2; 147 | } 148 | 149 | int end = freeMemory(); 150 | assertEqual(0, (start-end)); 151 | } 152 | 153 | test(assign4) 154 | { 155 | int start = freeMemory(); 156 | 157 | if (true) // bogus block so automatic storage duration objects are deleted 158 | { 159 | 160 | NdefMessage* m1 = new NdefMessage(); 161 | m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union..."); 162 | 163 | NdefMessage* m2 = new NdefMessage(); 164 | m2->addTextRecord("Record 1"); 165 | m2->addTextRecord("RECORD 2"); 166 | m2->addTextRecord("Record 3"); 167 | 168 | assertEqual(3, m2->getRecordCount()); 169 | *m2 = *m1; 170 | assertEqual(1, m2->getRecordCount()); 171 | 172 | // NdefRecord ghost = m2->getRecord(1); 173 | // ghost.print(); 174 | // 175 | // NdefRecord ghost2 = m2->getRecord(3); 176 | // ghost2.print(); 177 | 178 | // 179 | // delete m1; 180 | // 181 | // NdefRecord r = m2->getRecord(0); 182 | // 183 | // assertEqual(TNF_WELL_KNOWN, r.getTnf()); 184 | // assertEqual(1, r.getTypeLength()); 185 | // assertEqual(79, r.getPayloadLength()); 186 | // assertEqual(0, r.getIdLength()); 187 | // 188 | // String s = "We the People of the United States, in Order to form a more perfect Union..."; 189 | // byte payload[s.length() + 1]; 190 | // s.getBytes(payload, sizeof(payload)); 191 | // 192 | // uint8_t* p = r.getPayload(); 193 | // int size = r.getPayloadLength(); 194 | // assertBytesEqual(payload, p+3, s.length()); 195 | // free(p); 196 | 197 | delete m1; 198 | delete m2; 199 | } 200 | 201 | int end = freeMemory(); 202 | assertEqual(0, (start-end)); 203 | } 204 | 205 | // really a record test 206 | test(doublePayload) 207 | { 208 | int start = freeMemory(); 209 | 210 | NdefRecord* r = new NdefRecord(); 211 | uint8_t p1[] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 }; 212 | r->setPayload(p1, sizeof(p1)); 213 | r->setPayload(p1, sizeof(p1)); 214 | 215 | delete r; 216 | 217 | int end = freeMemory(); 218 | assertEqual(0, (start-end)); 219 | } 220 | 221 | test(aaa_printFreeMemoryAtStart) // warning: relies on fact tests are run in alphabetical order 222 | { 223 | Serial.println(F("---------------------")); 224 | Serial.print("Free Memory Start ");Serial.println(freeMemory()); 225 | Serial.println(F("---------------------")); 226 | } 227 | 228 | test(zzz_printFreeMemoryAtEnd) // warning: relies on fact tests are run in alphabetical order 229 | { 230 | // unfortunately the user needs to manually check this matches the start value 231 | Serial.println(F("=====================")); 232 | Serial.print("Free Memory End ");Serial.println(freeMemory()); 233 | Serial.println(F("=====================")); 234 | } 235 | 236 | void loop() { 237 | Test::run(); 238 | } -------------------------------------------------------------------------------- /NDEF/tests/NdefUnitTest/NdefUnitTest.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void assertBytesEqual(const uint8_t* expected, const uint8_t* actual, uint8_t size) { 7 | for (int i = 0; i < size; i++) { 8 | assertEqual(expected[i], actual[i]); 9 | } 10 | } 11 | 12 | void setup() { 13 | Serial.begin(9600); 14 | } 15 | 16 | test(accessors) { 17 | NdefRecord record = NdefRecord(); 18 | record.setTnf(TNF_WELL_KNOWN); 19 | uint8_t recordType[] = { 0x54 }; // "T" Text Record 20 | assertEqual(0x54, recordType[0]); 21 | record.setType(recordType, sizeof(recordType)); 22 | // 2 + "en" + "Unit Test" 23 | uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 }; 24 | record.setPayload(payload, sizeof(payload)); 25 | 26 | assertEqual(TNF_WELL_KNOWN, record.getTnf()); 27 | assertEqual(sizeof(recordType), record.getTypeLength()); 28 | assertEqual(1, record.getTypeLength()); 29 | assertEqual(sizeof(payload), record.getPayloadLength()); 30 | assertEqual(12, record.getPayloadLength()); 31 | 32 | uint8_t typeCheck[record.getTypeLength()]; 33 | record.getType(typeCheck); 34 | 35 | assertEqual(0x54, typeCheck[0]); 36 | assertBytesEqual(recordType, typeCheck, sizeof(recordType)); 37 | 38 | uint8_t payloadCheck[record.getPayloadLength()]; 39 | record.getPayload(&payloadCheck[0]); 40 | assertBytesEqual(payload, payloadCheck, sizeof(payload)); 41 | } 42 | 43 | test(newaccessors) { 44 | NdefRecord record = NdefRecord(); 45 | record.setTnf(TNF_WELL_KNOWN); 46 | uint8_t recordType[] = { 0x54 }; // "T" Text Record 47 | assertEqual(0x54, recordType[0]); 48 | record.setType(recordType, sizeof(recordType)); 49 | // 2 + "en" + "Unit Test" 50 | uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 }; 51 | record.setPayload(payload, sizeof(payload)); 52 | 53 | assertEqual(TNF_WELL_KNOWN, record.getTnf()); 54 | assertEqual(sizeof(recordType), record.getTypeLength()); 55 | assertEqual(1, record.getTypeLength()); 56 | assertEqual(sizeof(payload), record.getPayloadLength()); 57 | assertEqual(12, record.getPayloadLength()); 58 | 59 | ::String typeCheck = record.getType(); 60 | assertTrue(typeCheck.equals("T")); 61 | 62 | byte payloadCheck[record.getPayloadLength()]; 63 | record.getPayload(payloadCheck); 64 | assertBytesEqual(payload, payloadCheck, sizeof(payload)); 65 | } 66 | 67 | test(assignment) 68 | { 69 | NdefRecord record = NdefRecord(); 70 | record.setTnf(TNF_WELL_KNOWN); 71 | uint8_t recordType[] = { 0x54 }; // "T" Text Record 72 | assertEqual(0x54, recordType[0]); 73 | record.setType(recordType, sizeof(recordType)); 74 | // 2 + "en" + "Unit Test" 75 | uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 }; 76 | record.setPayload(payload, sizeof(payload)); 77 | 78 | NdefRecord record2 = NdefRecord(); 79 | record2 = record; 80 | 81 | assertEqual(TNF_WELL_KNOWN, record.getTnf()); 82 | assertEqual(sizeof(recordType), record2.getTypeLength()); 83 | assertEqual(sizeof(payload), record2.getPayloadLength()); 84 | 85 | ::String typeCheck = record.getType(); 86 | assertTrue(typeCheck.equals("T")); 87 | 88 | byte payload2[record2.getPayloadLength()]; 89 | record2.getPayload(payload2); 90 | assertBytesEqual(payload, payload2, sizeof(payload)); 91 | } 92 | 93 | test(getEmptyPayload) 94 | { 95 | NdefRecord r = NdefRecord(); 96 | assertEqual(TNF_EMPTY, r.getTnf()); 97 | assertEqual(0, r.getPayloadLength()); 98 | 99 | byte payload[r.getPayloadLength()]; 100 | r.getPayload(payload); 101 | 102 | byte empty[0]; 103 | assertBytesEqual(empty, payload, sizeof(payload)); 104 | } 105 | 106 | void loop() { 107 | Test::run(); 108 | } 109 | -------------------------------------------------------------------------------- /NDEF/tests/NfcTagTest/NfcTagTest.ino: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void setup() { 7 | Serial.begin(9600); 8 | } 9 | 10 | // Test for pull requests #14 and #16 11 | test(getUid) 12 | { 13 | byte uid[4] = { 0x00, 0xFF, 0xAA, 0x17 }; 14 | byte uidFromTag[sizeof(uid)]; 15 | 16 | NfcTag tag = NfcTag(uid, sizeof(uid)); 17 | 18 | assertEqual(sizeof(uid), tag.getUidLength()); 19 | 20 | tag.getUid(uidFromTag, sizeof(uidFromTag)); 21 | 22 | // make sure the 2 uids are the same 23 | for (int i = 0; i < sizeof(uid); i++) { 24 | assertEqual(uid[i], uidFromTag[i]); 25 | } 26 | 27 | // check contents, to ensure the original uid wasn't overwritten 28 | assertEqual(0x00, uid[0]); 29 | assertEqual(0xFF, uid[1]); 30 | assertEqual(0xAA, uid[2]); 31 | assertEqual(0x17, uid[3]); 32 | } 33 | 34 | void loop() { 35 | Test::run(); 36 | } 37 | 38 | -------------------------------------------------------------------------------- /PN532/PN532.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | @file PN532.h 4 | @author Adafruit Industries & Seeed Studio 5 | @license BSD 6 | */ 7 | /**************************************************************************/ 8 | 9 | #ifndef __PN532_H__ 10 | #define __PN532_H__ 11 | 12 | #include 13 | #include "PN532Interface.h" 14 | 15 | // PN532 Commands 16 | #define PN532_COMMAND_DIAGNOSE (0x00) 17 | #define PN532_COMMAND_GETFIRMWAREVERSION (0x02) 18 | #define PN532_COMMAND_GETGENERALSTATUS (0x04) 19 | #define PN532_COMMAND_READREGISTER (0x06) 20 | #define PN532_COMMAND_WRITEREGISTER (0x08) 21 | #define PN532_COMMAND_READGPIO (0x0C) 22 | #define PN532_COMMAND_WRITEGPIO (0x0E) 23 | #define PN532_COMMAND_SETSERIALBAUDRATE (0x10) 24 | #define PN532_COMMAND_SETPARAMETERS (0x12) 25 | #define PN532_COMMAND_SAMCONFIGURATION (0x14) 26 | #define PN532_COMMAND_POWERDOWN (0x16) 27 | #define PN532_COMMAND_RFCONFIGURATION (0x32) 28 | #define PN532_COMMAND_RFREGULATIONTEST (0x58) 29 | #define PN532_COMMAND_INJUMPFORDEP (0x56) 30 | #define PN532_COMMAND_INJUMPFORPSL (0x46) 31 | #define PN532_COMMAND_INLISTPASSIVETARGET (0x4A) 32 | #define PN532_COMMAND_INATR (0x50) 33 | #define PN532_COMMAND_INPSL (0x4E) 34 | #define PN532_COMMAND_INDATAEXCHANGE (0x40) 35 | #define PN532_COMMAND_INCOMMUNICATETHRU (0x42) 36 | #define PN532_COMMAND_INDESELECT (0x44) 37 | #define PN532_COMMAND_INRELEASE (0x52) 38 | #define PN532_COMMAND_INSELECT (0x54) 39 | #define PN532_COMMAND_INAUTOPOLL (0x60) 40 | #define PN532_COMMAND_TGINITASTARGET (0x8C) 41 | #define PN532_COMMAND_TGSETGENERALBYTES (0x92) 42 | #define PN532_COMMAND_TGGETDATA (0x86) 43 | #define PN532_COMMAND_TGSETDATA (0x8E) 44 | #define PN532_COMMAND_TGSETMETADATA (0x94) 45 | #define PN532_COMMAND_TGGETINITIATORCOMMAND (0x88) 46 | #define PN532_COMMAND_TGRESPONSETOINITIATOR (0x90) 47 | #define PN532_COMMAND_TGGETTARGETSTATUS (0x8A) 48 | 49 | #define PN532_RESPONSE_INDATAEXCHANGE (0x41) 50 | #define PN532_RESPONSE_INLISTPASSIVETARGET (0x4B) 51 | 52 | 53 | #define PN532_MIFARE_ISO14443A (0x00) 54 | 55 | // Mifare Commands 56 | #define MIFARE_CMD_AUTH_A (0x60) 57 | #define MIFARE_CMD_AUTH_B (0x61) 58 | #define MIFARE_CMD_READ (0x30) 59 | #define MIFARE_CMD_WRITE (0xA0) 60 | #define MIFARE_CMD_WRITE_ULTRALIGHT (0xA2) 61 | #define MIFARE_CMD_TRANSFER (0xB0) 62 | #define MIFARE_CMD_DECREMENT (0xC0) 63 | #define MIFARE_CMD_INCREMENT (0xC1) 64 | #define MIFARE_CMD_STORE (0xC2) 65 | 66 | // FeliCa Commands 67 | #define FELICA_CMD_POLLING (0x00) 68 | #define FELICA_CMD_REQUEST_SERVICE (0x02) 69 | #define FELICA_CMD_REQUEST_RESPONSE (0x04) 70 | #define FELICA_CMD_READ_WITHOUT_ENCRYPTION (0x06) 71 | #define FELICA_CMD_WRITE_WITHOUT_ENCRYPTION (0x08) 72 | #define FELICA_CMD_REQUEST_SYSTEM_CODE (0x0C) 73 | 74 | // Prefixes for NDEF Records (to identify record type) 75 | #define NDEF_URIPREFIX_NONE (0x00) 76 | #define NDEF_URIPREFIX_HTTP_WWWDOT (0x01) 77 | #define NDEF_URIPREFIX_HTTPS_WWWDOT (0x02) 78 | #define NDEF_URIPREFIX_HTTP (0x03) 79 | #define NDEF_URIPREFIX_HTTPS (0x04) 80 | #define NDEF_URIPREFIX_TEL (0x05) 81 | #define NDEF_URIPREFIX_MAILTO (0x06) 82 | #define NDEF_URIPREFIX_FTP_ANONAT (0x07) 83 | #define NDEF_URIPREFIX_FTP_FTPDOT (0x08) 84 | #define NDEF_URIPREFIX_FTPS (0x09) 85 | #define NDEF_URIPREFIX_SFTP (0x0A) 86 | #define NDEF_URIPREFIX_SMB (0x0B) 87 | #define NDEF_URIPREFIX_NFS (0x0C) 88 | #define NDEF_URIPREFIX_FTP (0x0D) 89 | #define NDEF_URIPREFIX_DAV (0x0E) 90 | #define NDEF_URIPREFIX_NEWS (0x0F) 91 | #define NDEF_URIPREFIX_TELNET (0x10) 92 | #define NDEF_URIPREFIX_IMAP (0x11) 93 | #define NDEF_URIPREFIX_RTSP (0x12) 94 | #define NDEF_URIPREFIX_URN (0x13) 95 | #define NDEF_URIPREFIX_POP (0x14) 96 | #define NDEF_URIPREFIX_SIP (0x15) 97 | #define NDEF_URIPREFIX_SIPS (0x16) 98 | #define NDEF_URIPREFIX_TFTP (0x17) 99 | #define NDEF_URIPREFIX_BTSPP (0x18) 100 | #define NDEF_URIPREFIX_BTL2CAP (0x19) 101 | #define NDEF_URIPREFIX_BTGOEP (0x1A) 102 | #define NDEF_URIPREFIX_TCPOBEX (0x1B) 103 | #define NDEF_URIPREFIX_IRDAOBEX (0x1C) 104 | #define NDEF_URIPREFIX_FILE (0x1D) 105 | #define NDEF_URIPREFIX_URN_EPC_ID (0x1E) 106 | #define NDEF_URIPREFIX_URN_EPC_TAG (0x1F) 107 | #define NDEF_URIPREFIX_URN_EPC_PAT (0x20) 108 | #define NDEF_URIPREFIX_URN_EPC_RAW (0x21) 109 | #define NDEF_URIPREFIX_URN_EPC (0x22) 110 | #define NDEF_URIPREFIX_URN_NFC (0x23) 111 | 112 | #define PN532_GPIO_VALIDATIONBIT (0x80) 113 | #define PN532_GPIO_P30 (0) 114 | #define PN532_GPIO_P31 (1) 115 | #define PN532_GPIO_P32 (2) 116 | #define PN532_GPIO_P33 (3) 117 | #define PN532_GPIO_P34 (4) 118 | #define PN532_GPIO_P35 (5) 119 | 120 | // FeliCa consts 121 | #define FELICA_READ_MAX_SERVICE_NUM 16 122 | #define FELICA_READ_MAX_BLOCK_NUM 12 // for typical FeliCa card 123 | #define FELICA_WRITE_MAX_SERVICE_NUM 16 124 | #define FELICA_WRITE_MAX_BLOCK_NUM 10 // for typical FeliCa card 125 | #define FELICA_REQ_SERVICE_MAX_NODE_NUM 32 126 | 127 | class PN532 128 | { 129 | public: 130 | PN532(PN532Interface &interface); 131 | 132 | void begin(void); 133 | 134 | // Generic PN532 functions 135 | bool SAMConfig(void); 136 | uint32_t getFirmwareVersion(void); 137 | uint32_t readRegister(uint16_t reg); 138 | uint32_t writeRegister(uint16_t reg, uint8_t val); 139 | bool writeGPIO(uint8_t pinstate); 140 | uint8_t readGPIO(void); 141 | bool setPassiveActivationRetries(uint8_t maxRetries); 142 | bool setRFField(uint8_t autoRFCA, uint8_t rFOnOff); 143 | 144 | /** 145 | * @brief Init PN532 as a target 146 | * @param timeout max time to wait, 0 means no timeout 147 | * @return > 0 success 148 | * = 0 timeout 149 | * < 0 failed 150 | */ 151 | int8_t tgInitAsTarget(uint16_t timeout = 0); 152 | int8_t tgInitAsTarget(const uint8_t* command, const uint8_t len, const uint16_t timeout = 0); 153 | 154 | int16_t tgGetData(uint8_t *buf, uint8_t len); 155 | bool tgSetData(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 156 | 157 | int16_t inRelease(const uint8_t relevantTarget = 0); 158 | 159 | // ISO14443A functions 160 | bool inListPassiveTarget(); 161 | bool readPassiveTargetID(uint8_t cardbaudrate, uint8_t *uid, uint8_t *uidLength, uint16_t timeout = 1000); 162 | bool inDataExchange(uint8_t *send, uint8_t sendLength, uint8_t *response, uint8_t *responseLength); 163 | 164 | // Mifare Classic functions 165 | bool mifareclassic_IsFirstBlock (uint32_t uiBlock); 166 | bool mifareclassic_IsTrailerBlock (uint32_t uiBlock); 167 | uint8_t mifareclassic_AuthenticateBlock (uint8_t *uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t *keyData); 168 | uint8_t mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t *data); 169 | uint8_t mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t *data); 170 | uint8_t mifareclassic_FormatNDEF (void); 171 | uint8_t mifareclassic_WriteNDEFURI (uint8_t sectorNumber, uint8_t uriIdentifier, const char *url); 172 | 173 | // Mifare Ultralight functions 174 | uint8_t mifareultralight_ReadPage (uint8_t page, uint8_t *buffer); 175 | uint8_t mifareultralight_WritePage (uint8_t page, uint8_t *buffer); 176 | 177 | // FeliCa Functions 178 | int8_t felica_Polling(uint16_t systemCode, uint8_t requestCode, uint8_t *idm, uint8_t *pmm, uint16_t *systemCodeResponse, uint16_t timeout=1000); 179 | int8_t felica_SendCommand (const uint8_t * command, uint8_t commandlength, uint8_t * response, uint8_t * responseLength); 180 | int8_t felica_RequestService(uint8_t numNode, uint16_t *nodeCodeList, uint16_t *keyVersions) ; 181 | int8_t felica_RequestResponse(uint8_t *mode); 182 | int8_t felica_ReadWithoutEncryption (uint8_t numService, const uint16_t *serviceCodeList, uint8_t numBlock, const uint16_t *blockList, uint8_t blockData[][16]); 183 | int8_t felica_WriteWithoutEncryption (uint8_t numService, const uint16_t *serviceCodeList, uint8_t numBlock, const uint16_t *blockList, uint8_t blockData[][16]); 184 | int8_t felica_RequestSystemCode(uint8_t *numSystemCode, uint16_t *systemCodeList); 185 | int8_t felica_Release(); 186 | 187 | // Help functions to display formatted text 188 | static void PrintHex(const uint8_t *data, const uint32_t numBytes); 189 | static void PrintHexChar(const uint8_t *pbtData, const uint32_t numBytes); 190 | 191 | uint8_t *getBuffer(uint8_t *len) { 192 | *len = sizeof(pn532_packetbuffer) - 4; 193 | return pn532_packetbuffer; 194 | }; 195 | 196 | private: 197 | uint8_t _uid[7]; // ISO14443A uid 198 | uint8_t _uidLen; // uid len 199 | uint8_t _key[6]; // Mifare Classic key 200 | uint8_t inListedTag; // Tg number of inlisted tag. 201 | uint8_t _felicaIDm[8]; // FeliCa IDm (NFCID2) 202 | uint8_t _felicaPMm[8]; // FeliCa PMm (PAD) 203 | 204 | uint8_t pn532_packetbuffer[64]; 205 | 206 | PN532Interface *_interface; 207 | }; 208 | 209 | #endif 210 | -------------------------------------------------------------------------------- /PN532/PN532Interface.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #ifndef __PN532_INTERFACE_H__ 4 | #define __PN532_INTERFACE_H__ 5 | 6 | #include 7 | 8 | #define PN532_PREAMBLE (0x00) 9 | #define PN532_STARTCODE1 (0x00) 10 | #define PN532_STARTCODE2 (0xFF) 11 | #define PN532_POSTAMBLE (0x00) 12 | 13 | #define PN532_HOSTTOPN532 (0xD4) 14 | #define PN532_PN532TOHOST (0xD5) 15 | 16 | #define PN532_ACK_WAIT_TIME (10) // ms, timeout of waiting for ACK 17 | 18 | #define PN532_INVALID_ACK (-1) 19 | #define PN532_TIMEOUT (-2) 20 | #define PN532_INVALID_FRAME (-3) 21 | #define PN532_NO_SPACE (-4) 22 | 23 | #define REVERSE_BITS_ORDER(b) b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; \ 24 | b = (b & 0xCC) >> 2 | (b & 0x33) << 2; \ 25 | b = (b & 0xAA) >> 1 | (b & 0x55) << 1 26 | 27 | class PN532Interface 28 | { 29 | public: 30 | virtual void begin() = 0; 31 | virtual void wakeup() = 0; 32 | 33 | /** 34 | * @brief write a command and check ack 35 | * @param header packet header 36 | * @param hlen length of header 37 | * @param body packet body 38 | * @param blen length of body 39 | * @return 0 success 40 | * not 0 failed 41 | */ 42 | virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0) = 0; 43 | 44 | /** 45 | * @brief read the response of a command, strip prefix and suffix 46 | * @param buf to contain the response data 47 | * @param len lenght to read 48 | * @param timeout max time to wait, 0 means no timeout 49 | * @return >=0 length of response without prefix and suffix 50 | * <0 failed to read response 51 | */ 52 | virtual int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout = 1000) = 0; 53 | }; 54 | 55 | #endif 56 | 57 | -------------------------------------------------------------------------------- /PN532/PN532_debug.h: -------------------------------------------------------------------------------- 1 | #ifndef __DEBUG_H__ 2 | #define __DEBUG_H__ 3 | 4 | //#define DEBUG 5 | 6 | #include "Arduino.h" 7 | 8 | #ifdef DEBUG 9 | #define DMSG(args...) Serial.print(args) 10 | #define DMSG_STR(str) Serial.println(str) 11 | #define DMSG_HEX(num) Serial.print(' '); Serial.print((num>>4)&0x0F, HEX); Serial.print(num&0x0F, HEX) 12 | #define DMSG_INT(num) Serial.print(' '); Serial.print(num) 13 | #else 14 | #define DMSG(args...) 15 | #define DMSG_STR(str) 16 | #define DMSG_HEX(num) 17 | #define DMSG_INT(num) 18 | #endif 19 | 20 | #endif 21 | -------------------------------------------------------------------------------- /PN532/README.md: -------------------------------------------------------------------------------- 1 | ## NFC library for Arduino 2 | 3 | This is an Arduino library for PN532 to use NFC technology. 4 | It works with 5 | 6 | + [NFC Shield](http://goo.gl/Cac2OH) 7 | + [Xadow NFC](http://goo.gl/qBZMt0) 8 | + [PN532 NFC/RFID controller breakout board](http://goo.gl/tby9Sw) 9 | 10 | ### Features 11 | + Support I2C, SPI and HSU of PN532 12 | + Read/write Mifare Classic Card 13 | + Works with [Don's NDEF Library](http://goo.gl/jDjsXl) 14 | + Support Peer to Peer communication(exchange data with android 4.0+) 15 | + Support [mbed platform](http://goo.gl/kGPovZ) 16 | 17 | ### Getting Started 18 | 1. Download [zip file](http://goo.gl/F6beRM) and 19 | extract the 4 folders(PN532, PN532_SPI, PN532_I2C and PN532_HSU) into Arduino's libraries. 20 | 2. Downlaod [Don's NDEF library](http://goo.gl/ewxeAe) and extract it intro Arduino's libraries. 21 | 3. Follow the examples of the two libraries. 22 | 23 | ### To do 24 | + Card emulation 25 | 26 | ### Contribution 27 | It's based on [Adafruit_NFCShield_I2C](http://goo.gl/pk3FdB). 28 | [Seeed Studio](http://goo.gl/zh1iQh) adds SPI interface and peer to peer communication support. 29 | @Don writes the [NDEF library](http://goo.gl/jDjsXl) to make it more easy to use. 30 | @JiapengLi adds HSU interface. 31 | -------------------------------------------------------------------------------- /PN532/emulatetag.cpp: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | @file emulatetag.cpp 4 | @author Armin Wieser 5 | @license BSD 6 | */ 7 | /**************************************************************************/ 8 | 9 | #include "emulatetag.h" 10 | #include "PN532_debug.h" 11 | 12 | #include 13 | 14 | #define MAX_TGREAD 15 | 16 | 17 | // Command APDU 18 | #define C_APDU_CLA 0 19 | #define C_APDU_INS 1 // instruction 20 | #define C_APDU_P1 2 // parameter 1 21 | #define C_APDU_P2 3 // parameter 2 22 | #define C_APDU_LC 4 // length command 23 | #define C_APDU_DATA 5 // data 24 | 25 | #define C_APDU_P1_SELECT_BY_ID 0x00 26 | #define C_APDU_P1_SELECT_BY_NAME 0x04 27 | 28 | // Response APDU 29 | #define R_APDU_SW1_COMMAND_COMPLETE 0x90 30 | #define R_APDU_SW2_COMMAND_COMPLETE 0x00 31 | 32 | #define R_APDU_SW1_NDEF_TAG_NOT_FOUND 0x6a 33 | #define R_APDU_SW2_NDEF_TAG_NOT_FOUND 0x82 34 | 35 | #define R_APDU_SW1_FUNCTION_NOT_SUPPORTED 0x6A 36 | #define R_APDU_SW2_FUNCTION_NOT_SUPPORTED 0x81 37 | 38 | #define R_APDU_SW1_MEMORY_FAILURE 0x65 39 | #define R_APDU_SW2_MEMORY_FAILURE 0x81 40 | 41 | #define R_APDU_SW1_END_OF_FILE_BEFORE_REACHED_LE_BYTES 0x62 42 | #define R_APDU_SW2_END_OF_FILE_BEFORE_REACHED_LE_BYTES 0x82 43 | 44 | // ISO7816-4 commands 45 | #define ISO7816_SELECT_FILE 0xA4 46 | #define ISO7816_READ_BINARY 0xB0 47 | #define ISO7816_UPDATE_BINARY 0xD6 48 | 49 | typedef enum { NONE, CC, NDEF } tag_file; // CC ... Compatibility Container 50 | 51 | bool EmulateTag::init(){ 52 | pn532.begin(); 53 | return pn532.SAMConfig(); 54 | } 55 | 56 | void EmulateTag::setNdefFile(const uint8_t* ndef, const int16_t ndefLength){ 57 | if(ndefLength > (NDEF_MAX_LENGTH -2)){ 58 | DMSG("ndef file too large (> NDEF_MAX_LENGHT -2) - aborting"); 59 | return; 60 | } 61 | 62 | ndef_file[0] = ndefLength >> 8; 63 | ndef_file[1] = ndefLength & 0xFF; 64 | memcpy(ndef_file+2, ndef, ndefLength); 65 | } 66 | 67 | void EmulateTag::setUid(uint8_t* uid){ 68 | uidPtr = uid; 69 | } 70 | 71 | bool EmulateTag::emulate(const uint16_t tgInitAsTargetTimeout){ 72 | 73 | uint8_t command[] = { 74 | PN532_COMMAND_TGINITASTARGET, 75 | 5, // MODE: PICC only, Passive only 76 | 77 | 0x04, 0x00, // SENS_RES 78 | 0x00, 0x00, 0x00, // NFCID1 79 | 0x20, // SEL_RES 80 | 81 | 0,0,0,0,0,0,0,0, 82 | 0,0,0,0,0,0,0,0, // FeliCaParams 83 | 0,0, 84 | 85 | 0,0,0,0,0,0,0,0,0,0, // NFCID3t 86 | 87 | 0, // length of general bytes 88 | 0 // length of historical bytes 89 | }; 90 | 91 | if(uidPtr != 0){ // if uid is set copy 3 bytes to nfcid1 92 | memcpy(command + 4, uidPtr, 3); 93 | } 94 | 95 | if(1 != pn532.tgInitAsTarget(command,sizeof(command), tgInitAsTargetTimeout)){ 96 | DMSG("tgInitAsTarget failed or timed out!"); 97 | return false; 98 | } 99 | 100 | uint8_t compatibility_container[] = { 101 | 0, 0x0F, 102 | 0x20, 103 | 0, 0x54, 104 | 0, 0xFF, 105 | 0x04, // T 106 | 0x06, // L 107 | 0xE1, 0x04, // File identifier 108 | ((NDEF_MAX_LENGTH & 0xFF00) >> 8), (NDEF_MAX_LENGTH & 0xFF), // maximum NDEF file size 109 | 0x00, // read access 0x0 = granted 110 | 0x00 // write access 0x0 = granted | 0xFF = deny 111 | }; 112 | 113 | if(tagWriteable == false){ 114 | compatibility_container[14] = 0xFF; 115 | } 116 | 117 | tagWrittenByInitiator = false; 118 | 119 | uint8_t rwbuf[128]; 120 | uint8_t sendlen; 121 | int16_t status; 122 | tag_file currentFile = NONE; 123 | uint16_t cc_size = sizeof(compatibility_container); 124 | bool runLoop = true; 125 | 126 | while(runLoop){ 127 | status = pn532.tgGetData(rwbuf, sizeof(rwbuf)); 128 | if(status < 0){ 129 | DMSG("tgGetData failed!\n"); 130 | pn532.inRelease(); 131 | return true; 132 | } 133 | 134 | uint8_t p1 = rwbuf[C_APDU_P1]; 135 | uint8_t p2 = rwbuf[C_APDU_P2]; 136 | uint8_t lc = rwbuf[C_APDU_LC]; 137 | uint16_t p1p2_length = ((int16_t) p1 << 8) + p2; 138 | 139 | switch(rwbuf[C_APDU_INS]){ 140 | case ISO7816_SELECT_FILE: 141 | switch(p1){ 142 | case C_APDU_P1_SELECT_BY_ID: 143 | if(p2 != 0x0c){ 144 | DMSG("C_APDU_P2 != 0x0c\n"); 145 | setResponse(COMMAND_COMPLETE, rwbuf, &sendlen); 146 | } else if(lc == 2 && rwbuf[C_APDU_DATA] == 0xE1 && (rwbuf[C_APDU_DATA+1] == 0x03 || rwbuf[C_APDU_DATA+1] == 0x04)){ 147 | setResponse(COMMAND_COMPLETE, rwbuf, &sendlen); 148 | if(rwbuf[C_APDU_DATA+1] == 0x03){ 149 | currentFile = CC; 150 | } else if(rwbuf[C_APDU_DATA+1] == 0x04){ 151 | currentFile = NDEF; 152 | } 153 | } else { 154 | setResponse(TAG_NOT_FOUND, rwbuf, &sendlen); 155 | } 156 | break; 157 | case C_APDU_P1_SELECT_BY_NAME: 158 | const uint8_t ndef_tag_application_name_v2[] = {0, 0x7, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 }; 159 | if(0 == memcmp(ndef_tag_application_name_v2, rwbuf + C_APDU_P2, sizeof(ndef_tag_application_name_v2))){ 160 | setResponse(COMMAND_COMPLETE, rwbuf, &sendlen); 161 | } else{ 162 | DMSG("function not supported\n"); 163 | setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen); 164 | } 165 | break; 166 | } 167 | break; 168 | case ISO7816_READ_BINARY: 169 | switch(currentFile){ 170 | case NONE: 171 | setResponse(TAG_NOT_FOUND, rwbuf, &sendlen); 172 | break; 173 | case CC: 174 | if( p1p2_length > NDEF_MAX_LENGTH){ 175 | setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen); 176 | }else { 177 | memcpy(rwbuf,compatibility_container + p1p2_length, lc); 178 | setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc); 179 | } 180 | break; 181 | case NDEF: 182 | if( p1p2_length > NDEF_MAX_LENGTH){ 183 | setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen); 184 | }else { 185 | memcpy(rwbuf, ndef_file + p1p2_length, lc); 186 | setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc); 187 | } 188 | break; 189 | } 190 | break; 191 | case ISO7816_UPDATE_BINARY: 192 | if(!tagWriteable){ 193 | setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen); 194 | } else{ 195 | if( p1p2_length > NDEF_MAX_LENGTH){ 196 | setResponse(MEMORY_FAILURE, rwbuf, &sendlen); 197 | } 198 | else{ 199 | memcpy(ndef_file + p1p2_length, rwbuf + C_APDU_DATA, lc); 200 | setResponse(COMMAND_COMPLETE, rwbuf, &sendlen); 201 | tagWrittenByInitiator = true; 202 | 203 | uint16_t ndef_length = (ndef_file[0] << 8) + ndef_file[1]; 204 | if ((ndef_length > 0) && (updateNdefCallback != 0)) { 205 | updateNdefCallback(ndef_file + 2, ndef_length); 206 | } 207 | } 208 | } 209 | break; 210 | default: 211 | DMSG("Command not supported!"); 212 | DMSG_HEX(rwbuf[C_APDU_INS]); 213 | DMSG("\n"); 214 | setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen); 215 | } 216 | status = pn532.tgSetData(rwbuf, sendlen); 217 | if(status < 0){ 218 | DMSG("tgSetData failed\n!"); 219 | pn532.inRelease(); 220 | return true; 221 | } 222 | } 223 | pn532.inRelease(); 224 | return true; 225 | } 226 | 227 | void EmulateTag::setResponse(responseCommand cmd, uint8_t* buf, uint8_t* sendlen, uint8_t sendlenOffset){ 228 | switch(cmd){ 229 | case COMMAND_COMPLETE: 230 | buf[0] = R_APDU_SW1_COMMAND_COMPLETE; 231 | buf[1] = R_APDU_SW2_COMMAND_COMPLETE; 232 | *sendlen = 2 + sendlenOffset; 233 | break; 234 | case TAG_NOT_FOUND: 235 | buf[0] = R_APDU_SW1_NDEF_TAG_NOT_FOUND; 236 | buf[1] = R_APDU_SW2_NDEF_TAG_NOT_FOUND; 237 | *sendlen = 2; 238 | break; 239 | case FUNCTION_NOT_SUPPORTED: 240 | buf[0] = R_APDU_SW1_FUNCTION_NOT_SUPPORTED; 241 | buf[1] = R_APDU_SW2_FUNCTION_NOT_SUPPORTED; 242 | *sendlen = 2; 243 | break; 244 | case MEMORY_FAILURE: 245 | buf[0] = R_APDU_SW1_MEMORY_FAILURE; 246 | buf[1] = R_APDU_SW2_MEMORY_FAILURE; 247 | *sendlen = 2; 248 | break; 249 | case END_OF_FILE_BEFORE_REACHED_LE_BYTES: 250 | buf[0] = R_APDU_SW1_END_OF_FILE_BEFORE_REACHED_LE_BYTES; 251 | buf[1] = R_APDU_SW2_END_OF_FILE_BEFORE_REACHED_LE_BYTES; 252 | *sendlen= 2; 253 | break; 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /PN532/emulatetag.h: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | @file emulatetag.h 4 | @author Armin Wieser 5 | @license BSD 6 | 7 | Implemented using NFC forum documents & library of libnfc 8 | */ 9 | /**************************************************************************/ 10 | 11 | #ifndef __EMULATETAG_H__ 12 | #define __EMULATETAG_H__ 13 | 14 | #include "PN532.h" 15 | 16 | #define NDEF_MAX_LENGTH 128 // altough ndef can handle up to 0xfffe in size, arduino cannot. 17 | typedef enum {COMMAND_COMPLETE, TAG_NOT_FOUND, FUNCTION_NOT_SUPPORTED, MEMORY_FAILURE, END_OF_FILE_BEFORE_REACHED_LE_BYTES} responseCommand; 18 | 19 | class EmulateTag{ 20 | 21 | public: 22 | EmulateTag(PN532Interface &interface) : pn532(interface), uidPtr(0), tagWrittenByInitiator(false), tagWriteable(true), updateNdefCallback(0) { } 23 | 24 | bool init(); 25 | 26 | bool emulate(const uint16_t tgInitAsTargetTimeout = 0); 27 | 28 | /* 29 | * @param uid pointer to byte array of length 3 (uid is 4 bytes - first byte is fixed) or zero for uid 30 | */ 31 | void setUid(uint8_t* uid = 0); 32 | 33 | void setNdefFile(const uint8_t* ndef, const int16_t ndefLength); 34 | 35 | void getContent(uint8_t** buf, uint16_t* length){ 36 | *buf = ndef_file + 2; // first 2 bytes = length 37 | *length = (ndef_file[0] << 8) + ndef_file[1]; 38 | } 39 | 40 | bool writeOccured(){ 41 | return tagWrittenByInitiator; 42 | } 43 | 44 | void setTagWriteable(bool setWriteable){ 45 | tagWriteable = setWriteable; 46 | } 47 | 48 | uint8_t* getNdefFilePtr(){ 49 | return ndef_file; 50 | } 51 | 52 | uint8_t getNdefMaxLength(){ 53 | return NDEF_MAX_LENGTH; 54 | } 55 | 56 | void attach(void (*func)(uint8_t *buf, uint16_t length)) { 57 | updateNdefCallback = func; 58 | }; 59 | 60 | private: 61 | PN532 pn532; 62 | uint8_t ndef_file[NDEF_MAX_LENGTH]; 63 | uint8_t* uidPtr; 64 | bool tagWrittenByInitiator; 65 | bool tagWriteable; 66 | void (*updateNdefCallback)(uint8_t *ndef, uint16_t length); 67 | 68 | void setResponse(responseCommand cmd, uint8_t* buf, uint8_t* sendlen, uint8_t sendlenOffset = 0); 69 | }; 70 | 71 | #endif 72 | -------------------------------------------------------------------------------- /PN532/examples/FeliCa_card_detection/FeliCa_card_detection.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example will attempt to connect to an FeliCa 4 | card or tag and retrieve some basic information about it 5 | that can be used to determine what type of card it is. 6 | 7 | Note that you need the baud rate to be 115200 because we need to print 8 | out the data and read from the card at the same time! 9 | 10 | To enable debug message, define DEBUG in PN532/PN532_debug.h 11 | 12 | */ 13 | /**************************************************************************/ 14 | #include 15 | 16 | #if 1 17 | #include 18 | #include 19 | #include 20 | 21 | PN532_SPI pn532spi(SPI, 10); 22 | PN532 nfc(pn532spi); 23 | #elif 0 24 | #include 25 | #include 26 | 27 | PN532_HSU pn532hsu(Serial1); 28 | PN532 nfc(pn532hsu); 29 | #else 30 | #include 31 | #include 32 | #include 33 | 34 | PN532_I2C pn532i2c(Wire); 35 | PN532 nfc(pn532i2c); 36 | #endif 37 | 38 | #include 39 | 40 | uint8_t _prevIDm[8]; 41 | unsigned long _prevTime; 42 | 43 | void setup(void) 44 | { 45 | Serial.begin(115200); 46 | Serial.println("Hello!"); 47 | 48 | nfc.begin(); 49 | 50 | uint32_t versiondata = nfc.getFirmwareVersion(); 51 | if (!versiondata) 52 | { 53 | Serial.print("Didn't find PN53x board"); 54 | while (1) {delay(10);}; // halt 55 | } 56 | 57 | // Got ok data, print it out! 58 | Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX); 59 | Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC); 60 | Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC); 61 | 62 | // Set the max number of retry attempts to read from a card 63 | // This prevents us from waiting forever for a card, which is 64 | // the default behaviour of the PN532. 65 | nfc.setPassiveActivationRetries(0xFF); 66 | nfc.SAMConfig(); 67 | 68 | memset(_prevIDm, 0, 8); 69 | } 70 | 71 | void loop(void) 72 | { 73 | uint8_t ret; 74 | uint16_t systemCode = 0xFFFF; 75 | uint8_t requestCode = 0x01; // System Code request 76 | uint8_t idm[8]; 77 | uint8_t pmm[8]; 78 | uint16_t systemCodeResponse; 79 | 80 | // Wait for an FeliCa type cards. 81 | // When one is found, some basic information such as IDm, PMm, and System Code are retrieved. 82 | Serial.print("Waiting for an FeliCa card... "); 83 | ret = nfc.felica_Polling(systemCode, requestCode, idm, pmm, &systemCodeResponse, 5000); 84 | 85 | if (ret != 1) 86 | { 87 | Serial.println("Could not find a card"); 88 | delay(500); 89 | return; 90 | } 91 | 92 | if ( memcmp(idm, _prevIDm, 8) == 0 ) { 93 | if ( (millis() - _prevTime) < 3000 ) { 94 | Serial.println("Same card"); 95 | delay(500); 96 | return; 97 | } 98 | } 99 | 100 | Serial.println("Found a card!"); 101 | Serial.print(" IDm: "); 102 | nfc.PrintHex(idm, 8); 103 | Serial.print(" PMm: "); 104 | nfc.PrintHex(pmm, 8); 105 | Serial.print(" System Code: "); 106 | Serial.print(systemCodeResponse, HEX); 107 | Serial.print("\n"); 108 | 109 | memcpy(_prevIDm, idm, 8); 110 | _prevTime = millis(); 111 | 112 | // Wait 1 second before continuing 113 | Serial.println("Card access completed!\n"); 114 | delay(1000); 115 | } 116 | -------------------------------------------------------------------------------- /PN532/examples/FeliCa_card_read/FeliCa_card_read.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example will attempt to connect to an FeliCa 4 | card or tag and retrieve some basic information about it 5 | that can be used to determine what type of card it is. 6 | 7 | Note that you need the baud rate to be 115200 because we need to print 8 | out the data and read from the card at the same time! 9 | 10 | To enable debug message, define DEBUG in PN532/PN532_debug.h 11 | 12 | */ 13 | /**************************************************************************/ 14 | #include 15 | 16 | #if 1 17 | #include 18 | #include 19 | #include 20 | 21 | PN532_SPI pn532spi(SPI, 10); 22 | PN532 nfc(pn532spi); 23 | #elif 0 24 | #include 25 | #include 26 | 27 | PN532_HSU pn532hsu(Serial1); 28 | PN532 nfc(pn532hsu); 29 | #else 30 | #include 31 | #include 32 | #include 33 | 34 | PN532_I2C pn532i2c(Wire); 35 | PN532 nfc(pn532i2c); 36 | #endif 37 | 38 | #include 39 | 40 | uint8_t _prevIDm[8]; 41 | unsigned long _prevTime; 42 | 43 | void PrintHex8(const uint8_t d) { 44 | Serial.print(" "); 45 | Serial.print( (d >> 4) & 0x0F, HEX); 46 | Serial.print( d & 0x0F, HEX); 47 | } 48 | 49 | void setup(void) 50 | { 51 | Serial.begin(115200); 52 | Serial.println("Hello!"); 53 | 54 | nfc.begin(); 55 | 56 | uint32_t versiondata = nfc.getFirmwareVersion(); 57 | if (!versiondata) 58 | { 59 | Serial.print("Didn't find PN53x board"); 60 | while (1) {delay(10);}; // halt 61 | } 62 | 63 | // Got ok data, print it out! 64 | Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX); 65 | Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC); 66 | Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC); 67 | 68 | // Set the max number of retry attempts to read from a card 69 | // This prevents us from waiting forever for a card, which is 70 | // the default behaviour of the PN532. 71 | nfc.setPassiveActivationRetries(0xFF); 72 | nfc.SAMConfig(); 73 | 74 | memset(_prevIDm, 0, 8); 75 | } 76 | 77 | void loop(void) 78 | { 79 | uint8_t ret; 80 | uint16_t systemCode = 0xFFFF; 81 | uint8_t requestCode = 0x01; // System Code request 82 | uint8_t idm[8]; 83 | uint8_t pmm[8]; 84 | uint16_t systemCodeResponse; 85 | 86 | // Wait for an FeliCa type cards. 87 | // When one is found, some basic information such as IDm, PMm, and System Code are retrieved. 88 | Serial.print("Waiting for an FeliCa card... "); 89 | ret = nfc.felica_Polling(systemCode, requestCode, idm, pmm, &systemCodeResponse, 5000); 90 | 91 | if (ret != 1) 92 | { 93 | Serial.println("Could not find a card"); 94 | delay(500); 95 | return; 96 | } 97 | 98 | if ( memcmp(idm, _prevIDm, 8) == 0 ) { 99 | if ( (millis() - _prevTime) < 3000 ) { 100 | Serial.println("Same card"); 101 | delay(500); 102 | return; 103 | } 104 | } 105 | 106 | Serial.println("Found a card!"); 107 | Serial.print(" IDm: "); 108 | nfc.PrintHex(idm, 8); 109 | Serial.print(" PMm: "); 110 | nfc.PrintHex(pmm, 8); 111 | Serial.print(" System Code: "); 112 | Serial.print(systemCodeResponse, HEX); 113 | Serial.print("\n"); 114 | 115 | memcpy(_prevIDm, idm, 8); 116 | _prevTime = millis(); 117 | 118 | uint8_t blockData[3][16]; 119 | uint16_t serviceCodeList[1]; 120 | uint16_t blockList[3]; 121 | 122 | Serial.println("Write Without Encryption command "); 123 | serviceCodeList[0] = 0x0009; 124 | blockList[0] = 0x8000; 125 | unsigned long now = millis(); 126 | blockData[0][3] = now & 0xFF; 127 | blockData[0][2] = (now >>= 8) & 0xFF; 128 | blockData[0][1] = (now >>= 8) & 0xFF; 129 | blockData[0][0] = (now >>= 8) & 0xFF; 130 | Serial.print(" Writing current millis ("); 131 | PrintHex8(blockData[0][0]); 132 | PrintHex8(blockData[0][1]); 133 | PrintHex8(blockData[0][2]); 134 | PrintHex8(blockData[0][3]); 135 | Serial.print(" ) to Block 0 -> "); 136 | ret = nfc.felica_WriteWithoutEncryption(1, serviceCodeList, 1, blockList, blockData); 137 | if (ret != 1) 138 | { 139 | Serial.println("error"); 140 | } else { 141 | Serial.println("OK!"); 142 | } 143 | memset(blockData[0], 0, 16); 144 | 145 | Serial.print("Read Without Encryption command -> "); 146 | serviceCodeList[0] = 0x000B; 147 | blockList[0] = 0x8000; 148 | blockList[1] = 0x8001; 149 | blockList[2] = 0x8002; 150 | ret = nfc.felica_ReadWithoutEncryption(1, serviceCodeList, 3, blockList, blockData); 151 | if (ret != 1) 152 | { 153 | Serial.println("error"); 154 | } else { 155 | Serial.println("OK!"); 156 | for(int i=0; i<3; i++ ) { 157 | Serial.print(" Block no. "); Serial.print(i, DEC); Serial.print(": "); 158 | nfc.PrintHex(blockData[i], 16); 159 | } 160 | } 161 | 162 | // Wait 1 second before continuing 163 | Serial.println("Card access completed!\n"); 164 | delay(1000); 165 | } 166 | -------------------------------------------------------------------------------- /PN532/examples/android_hce/android_hce.ino: -------------------------------------------------------------------------------- 1 | #if 0 2 | #include 3 | #include 4 | #include "PN532.h" 5 | 6 | PN532_SPI pn532spi(SPI, 10); 7 | PN532 nfc(pn532spi); 8 | #elif 1 9 | #include 10 | #include 11 | 12 | PN532_HSU pn532hsu(Serial1); 13 | PN532 nfc(pn532hsu); 14 | #else 15 | #include 16 | #include 17 | #include 18 | #endif 19 | 20 | void setup() 21 | { 22 | Serial.begin(115200); 23 | Serial.println("-------Peer to Peer HCE--------"); 24 | 25 | nfc.begin(); 26 | 27 | uint32_t versiondata = nfc.getFirmwareVersion(); 28 | if (! versiondata) { 29 | Serial.print("Didn't find PN53x board"); 30 | while (1); // halt 31 | } 32 | 33 | // Got ok data, print it out! 34 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 35 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 36 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 37 | 38 | // Set the max number of retry attempts to read from a card 39 | // This prevents us from waiting forever for a card, which is 40 | // the default behaviour of the PN532. 41 | //nfc.setPassiveActivationRetries(0xFF); 42 | 43 | // configure board to read RFID tags 44 | nfc.SAMConfig(); 45 | } 46 | 47 | void loop() 48 | { 49 | bool success; 50 | 51 | uint8_t responseLength = 32; 52 | 53 | Serial.println("Waiting for an ISO14443A card"); 54 | 55 | // set shield to inListPassiveTarget 56 | success = nfc.inListPassiveTarget(); 57 | 58 | if(success) { 59 | 60 | Serial.println("Found something!"); 61 | 62 | uint8_t selectApdu[] = { 0x00, /* CLA */ 63 | 0xA4, /* INS */ 64 | 0x04, /* P1 */ 65 | 0x00, /* P2 */ 66 | 0x07, /* Length of AID */ 67 | 0xF0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* AID defined on Android App */ 68 | 0x00 /* Le */ }; 69 | 70 | uint8_t response[32]; 71 | 72 | success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength); 73 | 74 | if(success) { 75 | 76 | Serial.print("responseLength: "); Serial.println(responseLength); 77 | 78 | nfc.PrintHexChar(response, responseLength); 79 | 80 | do { 81 | uint8_t apdu[] = "Hello from Arduino"; 82 | uint8_t back[32]; 83 | uint8_t length = 32; 84 | 85 | success = nfc.inDataExchange(apdu, sizeof(apdu), back, &length); 86 | 87 | if(success) { 88 | 89 | Serial.print("responseLength: "); Serial.println(length); 90 | 91 | nfc.PrintHexChar(back, length); 92 | } 93 | else { 94 | 95 | Serial.println("Broken connection?"); 96 | } 97 | } 98 | while(success); 99 | } 100 | else { 101 | 102 | Serial.println("Failed sending SELECT AID"); 103 | } 104 | } 105 | else { 106 | 107 | Serial.println("Didn't find anything!"); 108 | } 109 | 110 | delay(1000); 111 | } 112 | 113 | void printResponse(uint8_t *response, uint8_t responseLength) { 114 | 115 | String respBuffer; 116 | 117 | for (int i = 0; i < responseLength; i++) { 118 | 119 | if (response[i] < 0x10) 120 | respBuffer = respBuffer + "0"; //Adds leading zeros if hex value is smaller than 0x10 121 | 122 | respBuffer = respBuffer + String(response[i], HEX) + " "; 123 | } 124 | 125 | Serial.print("response: "); Serial.println(respBuffer); 126 | } 127 | 128 | void setupNFC() { 129 | 130 | nfc.begin(); 131 | 132 | uint32_t versiondata = nfc.getFirmwareVersion(); 133 | if (! versiondata) { 134 | Serial.print("Didn't find PN53x board"); 135 | while (1); // halt 136 | } 137 | 138 | // Got ok data, print it out! 139 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 140 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 141 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 142 | 143 | // configure board to read RFID tags 144 | nfc.SAMConfig(); 145 | } 146 | -------------------------------------------------------------------------------- /PN532/examples/emulate_tag_ndef/emulate_tag_ndef.ino: -------------------------------------------------------------------------------- 1 | #include "emulatetag.h" 2 | #include "NdefMessage.h" 3 | 4 | #if 0 5 | #include 6 | #include 7 | #include "PN532.h" 8 | 9 | PN532_SPI pn532spi(SPI, 10); 10 | EmulateTag nfc(pn532spi); 11 | #elif 1 12 | #include 13 | #include 14 | 15 | PN532_HSU pn532hsu(Serial1); 16 | EmulateTag nfc(pn532hsu); 17 | #endif 18 | 19 | 20 | 21 | 22 | 23 | uint8_t ndefBuf[120]; 24 | NdefMessage message; 25 | int messageSize; 26 | 27 | uint8_t uid[3] = { 0x12, 0x34, 0x56 }; 28 | 29 | void setup() 30 | { 31 | Serial.begin(115200); 32 | Serial.println("------- Emulate Tag --------"); 33 | 34 | message = NdefMessage(); 35 | message.addUriRecord("http://www.elechouse.com"); 36 | messageSize = message.getEncodedSize(); 37 | if (messageSize > sizeof(ndefBuf)) { 38 | Serial.println("ndefBuf is too small"); 39 | while (1) { } 40 | } 41 | 42 | Serial.print("Ndef encoded message size: "); 43 | Serial.println(messageSize); 44 | 45 | message.encode(ndefBuf); 46 | 47 | // comment out this command for no ndef message 48 | nfc.setNdefFile(ndefBuf, messageSize); 49 | 50 | // uid must be 3 bytes! 51 | nfc.setUid(uid); 52 | 53 | nfc.init(); 54 | } 55 | 56 | void loop(){ 57 | // uncomment for overriding ndef in case a write to this tag occured 58 | //nfc.setNdefFile(ndefBuf, messageSize); 59 | 60 | // start emulation (blocks) 61 | nfc.emulate(); 62 | 63 | // or start emulation with timeout 64 | /*if(!nfc.emulate(1000)){ // timeout 1 second 65 | Serial.println("timed out"); 66 | }*/ 67 | 68 | // deny writing to the tag 69 | // nfc.setTagWriteable(false); 70 | 71 | if(nfc.writeOccured()){ 72 | Serial.println("\nWrite occured !"); 73 | uint8_t* tag_buf; 74 | uint16_t length; 75 | 76 | nfc.getContent(&tag_buf, &length); 77 | NdefMessage msg = NdefMessage(tag_buf, length); 78 | msg.print(); 79 | } 80 | 81 | delay(1000); 82 | } 83 | -------------------------------------------------------------------------------- /PN532/examples/iso14443a_uid/iso14443a_uid.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example will attempt to connect to an ISO14443A 4 | card or tag and retrieve some basic information about it 5 | that can be used to determine what type of card it is. 6 | 7 | Note that you need the baud rate to be 115200 because we need to print 8 | out the data and read from the card at the same time! 9 | 10 | To enable debug message, define DEBUG in PN532/PN532_debug.h 11 | 12 | */ 13 | /**************************************************************************/ 14 | 15 | 16 | /* When the number after #if set as 1, it will be switch to SPI Mode*/ 17 | #if 0 18 | #include 19 | #include 20 | #include "PN532.h" 21 | 22 | PN532_SPI pn532spi(SPI, 10); 23 | PN532 nfc(pn532spi); 24 | 25 | /* When the number after #elif set as 1, it will be switch to HSU Mode*/ 26 | #elif 0 27 | #include 28 | #include 29 | 30 | PN532_HSU pn532hsu(Serial1); 31 | PN532 nfc(pn532hsu); 32 | 33 | /* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/ 34 | #else 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | PN532_I2C pn532i2c(Wire); 41 | PN532 nfc(pn532i2c); 42 | #endif 43 | 44 | void setup(void) { 45 | Serial.begin(115200); 46 | Serial.println("Hello!"); 47 | 48 | nfc.begin(); 49 | 50 | uint32_t versiondata = nfc.getFirmwareVersion(); 51 | if (! versiondata) { 52 | Serial.print("Didn't find PN53x board"); 53 | while (1); // halt 54 | } 55 | 56 | // Got ok data, print it out! 57 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 58 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 59 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 60 | 61 | // Set the max number of retry attempts to read from a card 62 | // This prevents us from waiting forever for a card, which is 63 | // the default behaviour of the PN532. 64 | nfc.setPassiveActivationRetries(0xFF); 65 | 66 | // configure board to read RFID tags 67 | nfc.SAMConfig(); 68 | 69 | Serial.println("Waiting for an ISO14443A card"); 70 | } 71 | 72 | void loop(void) { 73 | boolean success; 74 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 75 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 76 | 77 | // Wait for an ISO14443A type cards (Mifare, etc.). When one is found 78 | // 'uid' will be populated with the UID, and uidLength will indicate 79 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 80 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength); 81 | 82 | if (success) { 83 | Serial.println("Found a card!"); 84 | Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 85 | Serial.print("UID Value: "); 86 | for (uint8_t i=0; i < uidLength; i++) 87 | { 88 | Serial.print(" 0x");Serial.print(uid[i], HEX); 89 | } 90 | Serial.println(""); 91 | // Wait 1 second before continuing 92 | delay(1000); 93 | } 94 | else 95 | { 96 | // PN532 probably timed out waiting for a card 97 | Serial.println("Timed out waiting for a card"); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /PN532/examples/mifareclassic_formatndef/mifareclassic_formatndef.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example attempts to format a clean Mifare Classic 1K card as 4 | an NFC Forum tag (to store NDEF messages that can be read by any 5 | NFC enabled Android phone, etc.) 6 | 7 | Note that you need the baud rate to be 115200 because we need to print 8 | out the data and read from the card at the same time! 9 | 10 | To enable debug message, define DEBUG in PN532/PN532_debug.h 11 | */ 12 | /**************************************************************************/ 13 | 14 | #if 0 15 | #include 16 | #include 17 | #include "PN532.h" 18 | 19 | PN532_SPI pn532spi(SPI, 10); 20 | PN532 nfc(pn532spi); 21 | #elif 1 22 | #include 23 | #include 24 | 25 | PN532_HSU pn532hsu(Serial1); 26 | PN532 nfc(pn532hsu); 27 | #else 28 | #include 29 | #include 30 | #include 31 | #endif 32 | /* 33 | We can encode many different kinds of pointers to the card, 34 | from a URL, to an Email address, to a phone number, and many more 35 | check the library header .h file to see the large # of supported 36 | prefixes! 37 | */ 38 | // For a http://www. url: 39 | const char * url = "elechouse.com"; 40 | uint8_t ndefprefix = NDEF_URIPREFIX_HTTP_WWWDOT; 41 | 42 | // for an email address 43 | //const char * url = "mail@example.com"; 44 | //uint8_t ndefprefix = NDEF_URIPREFIX_MAILTO; 45 | 46 | // for a phone number 47 | //const char * url = "+1 212 555 1212"; 48 | //uint8_t ndefprefix = NDEF_URIPREFIX_TEL; 49 | 50 | 51 | void setup(void) { 52 | Serial.begin(115200); 53 | Serial.println("Looking for PN532..."); 54 | 55 | nfc.begin(); 56 | 57 | uint32_t versiondata = nfc.getFirmwareVersion(); 58 | if (! versiondata) { 59 | Serial.print("Didn't find PN53x board"); 60 | while (1); // halt 61 | } 62 | 63 | // Got ok data, print it out! 64 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 65 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 66 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 67 | 68 | // configure board to read RFID tags 69 | nfc.SAMConfig(); 70 | } 71 | 72 | void loop(void) { 73 | uint8_t success; // Flag to check if there was an error with the PN532 74 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 75 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 76 | bool authenticated = false; // Flag to indicate if the sector is authenticated 77 | 78 | // Use the default key 79 | uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; 80 | 81 | Serial.println(""); 82 | Serial.println("PLEASE NOTE: Formatting your card for NDEF records will change the"); 83 | Serial.println("authentication keys. To reformat your NDEF tag as a clean Mifare"); 84 | Serial.println("Classic tag, use the mifareclassic_ndeftoclassic example!"); 85 | Serial.println(""); 86 | Serial.println("Place your Mifare Classic card on the reader to format with NDEF"); 87 | Serial.println("and press any key to continue ..."); 88 | // Wait for user input before proceeding 89 | while (!Serial.available()); 90 | // a key was pressed1 91 | while (Serial.available()) Serial.read(); 92 | 93 | // Wait for an ISO14443A type card (Mifare, etc.). When one is found 94 | // 'uid' will be populated with the UID, and uidLength will indicate 95 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 96 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 97 | 98 | if (success) 99 | { 100 | // Display some basic information about the card 101 | Serial.println("Found an ISO14443A card"); 102 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 103 | Serial.print(" UID Value: "); 104 | nfc.PrintHex(uid, uidLength); 105 | for (uint8_t i = 0; i < uidLength; i++) { 106 | Serial.print(uid[i], HEX); 107 | Serial.print(' '); 108 | } 109 | Serial.println(""); 110 | 111 | // Make sure this is a Mifare Classic card 112 | if (uidLength != 4) 113 | { 114 | Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!"); 115 | return; 116 | } 117 | 118 | // We probably have a Mifare Classic card ... 119 | Serial.println("Seems to be a Mifare Classic card (4 byte UID)"); 120 | 121 | // Try to format the card for NDEF data 122 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 0, 0, keya); 123 | if (!success) 124 | { 125 | Serial.println("Unable to authenticate block 0 to enable card formatting!"); 126 | return; 127 | } 128 | success = nfc.mifareclassic_FormatNDEF(); 129 | if (!success) 130 | { 131 | Serial.println("Unable to format the card for NDEF"); 132 | return; 133 | } 134 | 135 | Serial.println("Card has been formatted for NDEF data using MAD1"); 136 | 137 | // Try to authenticate block 4 (first block of sector 1) using our key 138 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 4, 0, keya); 139 | 140 | // Make sure the authentification process didn't fail 141 | if (!success) 142 | { 143 | Serial.println("Authentication failed."); 144 | return; 145 | } 146 | 147 | // Try to write a URL 148 | Serial.println("Writing URI to sector 1 as an NDEF Message"); 149 | 150 | // Authenticated seems to have worked 151 | // Try to write an NDEF record to sector 1 152 | // Use 0x01 for the URI Identifier Code to prepend "http://www." 153 | // to the url (and save some space). For information on URI ID Codes 154 | // see http://www.ladyada.net/wiki/private/articlestaging/nfc/ndef 155 | if (strlen(url) > 38) 156 | { 157 | // The length is also checked in the WriteNDEFURI function, but lets 158 | // warn users here just in case they change the value and it's bigger 159 | // than it should be 160 | Serial.println("URI is too long ... must be less than 38 characters long"); 161 | return; 162 | } 163 | 164 | // URI is within size limits ... write it to the card and report success/failure 165 | success = nfc.mifareclassic_WriteNDEFURI(1, ndefprefix, url); 166 | if (success) 167 | { 168 | Serial.println("NDEF URI Record written to sector 1"); 169 | } 170 | else 171 | { 172 | Serial.println("NDEF Record creation failed! :("); 173 | } 174 | } 175 | 176 | // Wait a bit before trying again 177 | Serial.println("\n\nDone!"); 178 | delay(1000); 179 | Serial.flush(); 180 | while(Serial.available()) Serial.read(); 181 | } -------------------------------------------------------------------------------- /PN532/examples/mifareclassic_memdump/mifareclassic_memdump.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example attempts to dump the contents of a Mifare Classic 1K card 4 | 5 | Note that you need the baud rate to be 115200 because we need to print 6 | out the data and read from the card at the same time! 7 | 8 | To enable debug message, define DEBUG in PN532/PN532_debug.h 9 | */ 10 | /**************************************************************************/ 11 | 12 | #if 0 13 | #include 14 | #include 15 | #include "PN532.h" 16 | 17 | PN532_SPI pn532spi(SPI, 10); 18 | PN532 nfc(pn532spi); 19 | #elif 1 20 | #include 21 | #include 22 | 23 | PN532_HSU pn532hsu(Serial1); 24 | PN532 nfc(pn532hsu); 25 | #else 26 | #include 27 | #include 28 | #include 29 | #endif 30 | 31 | void setup(void) { 32 | // has to be fast to dump the entire memory contents! 33 | Serial.begin(115200); 34 | Serial.println("Looking for PN532..."); 35 | 36 | nfc.begin(); 37 | 38 | uint32_t versiondata = nfc.getFirmwareVersion(); 39 | if (! versiondata) { 40 | Serial.print("Didn't find PN53x board"); 41 | while (1); // halt 42 | } 43 | // Got ok data, print it out! 44 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 45 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 46 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 47 | 48 | // configure board to read RFID tags 49 | nfc.SAMConfig(); 50 | 51 | Serial.println("Waiting for an ISO14443A Card ..."); 52 | } 53 | 54 | 55 | void loop(void) { 56 | uint8_t success; // Flag to check if there was an error with the PN532 57 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 58 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 59 | uint8_t currentblock; // Counter to keep track of which block we're on 60 | bool authenticated = false; // Flag to indicate if the sector is authenticated 61 | uint8_t data[16]; // Array to store block data during reads 62 | 63 | // Keyb on NDEF and Mifare Classic should be the same 64 | uint8_t keyuniversal[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; 65 | 66 | // Wait for an ISO14443A type cards (Mifare, etc.). When one is found 67 | // 'uid' will be populated with the UID, and uidLength will indicate 68 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 69 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 70 | 71 | if (success) { 72 | // Display some basic information about the card 73 | Serial.println("Found an ISO14443A card"); 74 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 75 | Serial.print(" UID Value: "); 76 | for (uint8_t i = 0; i < uidLength; i++) { 77 | Serial.print(uid[i], HEX); 78 | Serial.print(' '); 79 | } 80 | Serial.println(""); 81 | 82 | if (uidLength == 4) 83 | { 84 | // We probably have a Mifare Classic card ... 85 | Serial.println("Seems to be a Mifare Classic card (4 byte UID)"); 86 | 87 | // Now we try to go through all 16 sectors (each having 4 blocks) 88 | // authenticating each sector, and then dumping the blocks 89 | for (currentblock = 0; currentblock < 64; currentblock++) 90 | { 91 | // Check if this is a new block so that we can reauthenticate 92 | if (nfc.mifareclassic_IsFirstBlock(currentblock)) authenticated = false; 93 | 94 | // If the sector hasn't been authenticated, do so first 95 | if (!authenticated) 96 | { 97 | // Starting of a new sector ... try to to authenticate 98 | Serial.print("------------------------Sector ");Serial.print(currentblock/4, DEC);Serial.println("-------------------------"); 99 | if (currentblock == 0) 100 | { 101 | // This will be 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF for Mifare Classic (non-NDEF!) 102 | // or 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 for NDEF formatted cards using key a, 103 | // but keyb should be the same for both (0xFF 0xFF 0xFF 0xFF 0xFF 0xFF) 104 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, currentblock, 1, keyuniversal); 105 | } 106 | else 107 | { 108 | // This will be 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF for Mifare Classic (non-NDEF!) 109 | // or 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 for NDEF formatted cards using key a, 110 | // but keyb should be the same for both (0xFF 0xFF 0xFF 0xFF 0xFF 0xFF) 111 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, currentblock, 1, keyuniversal); 112 | } 113 | if (success) 114 | { 115 | authenticated = true; 116 | } 117 | else 118 | { 119 | Serial.println("Authentication error"); 120 | } 121 | } 122 | // If we're still not authenticated just skip the block 123 | if (!authenticated) 124 | { 125 | Serial.print("Block ");Serial.print(currentblock, DEC);Serial.println(" unable to authenticate"); 126 | } 127 | else 128 | { 129 | // Authenticated ... we should be able to read the block now 130 | // Dump the data into the 'data' array 131 | success = nfc.mifareclassic_ReadDataBlock(currentblock, data); 132 | if (success) 133 | { 134 | // Read successful 135 | Serial.print("Block ");Serial.print(currentblock, DEC); 136 | if (currentblock < 10) 137 | { 138 | Serial.print(" "); 139 | } 140 | else 141 | { 142 | Serial.print(" "); 143 | } 144 | // Dump the raw data 145 | nfc.PrintHexChar(data, 16); 146 | } 147 | else 148 | { 149 | // Oops ... something happened 150 | Serial.print("Block ");Serial.print(currentblock, DEC); 151 | Serial.println(" unable to read this block"); 152 | } 153 | } 154 | } 155 | } 156 | else 157 | { 158 | Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!"); 159 | } 160 | } 161 | // Wait a bit before trying again 162 | Serial.println("\n\nSend a character to run the mem dumper again!"); 163 | Serial.flush(); 164 | while (!Serial.available()); 165 | while (Serial.available()) { 166 | Serial.read(); 167 | } 168 | Serial.flush(); 169 | } -------------------------------------------------------------------------------- /PN532/examples/mifareclassic_ndeftoclassic/mifareclassic_ndeftoclassic.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This examples attempts to take a Mifare Classic 1K card that has been 4 | formatted for NDEF messages using mifareclassic_formatndef, and resets 5 | the authentication keys back to the Mifare Classic defaults 6 | 7 | To enable debug message, define DEBUG in PN532/PN532_debug.h 8 | */ 9 | /**************************************************************************/ 10 | 11 | #if 0 12 | #include 13 | #include 14 | #include "PN532.h" 15 | 16 | PN532_SPI pn532spi(SPI, 10); 17 | PN532 nfc(pn532spi); 18 | #elif 1 19 | #include 20 | #include 21 | 22 | PN532_HSU pn532hsu(Serial1); 23 | PN532 nfc(pn532hsu); 24 | #else 25 | #include 26 | #include 27 | #include 28 | #endif 29 | 30 | #define NR_SHORTSECTOR (32) // Number of short sectors on Mifare 1K/4K 31 | #define NR_LONGSECTOR (8) // Number of long sectors on Mifare 4K 32 | #define NR_BLOCK_OF_SHORTSECTOR (4) // Number of blocks in a short sector 33 | #define NR_BLOCK_OF_LONGSECTOR (16) // Number of blocks in a long sector 34 | 35 | // Determine the sector trailer block based on sector number 36 | #define BLOCK_NUMBER_OF_SECTOR_TRAILER(sector) (((sector)>24) & 0xFF, HEX); 62 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 63 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 64 | 65 | // configure board to read RFID tags 66 | nfc.SAMConfig(); 67 | } 68 | 69 | void loop(void) { 70 | uint8_t success; // Flag to check if there was an error with the PN532 71 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 72 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 73 | bool authenticated = false; // Flag to indicate if the sector is authenticated 74 | uint8_t blockBuffer[16]; // Buffer to store block contents 75 | uint8_t blankAccessBits[3] = { 0xff, 0x07, 0x80 }; 76 | uint8_t idx = 0; 77 | uint8_t numOfSector = 16; // Assume Mifare Classic 1K for now (16 4-block sectors) 78 | 79 | Serial.println("Place your NDEF formatted Mifare Classic 1K card on the reader"); 80 | Serial.println("and press any key to continue ..."); 81 | 82 | // Wait for user input before proceeding 83 | while (!Serial.available()); 84 | while (Serial.available()) Serial.read(); 85 | 86 | // Wait for an ISO14443A type card (Mifare, etc.). When one is found 87 | // 'uid' will be populated with the UID, and uidLength will indicate 88 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 89 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 90 | 91 | if (success) 92 | { 93 | // We seem to have a tag ... 94 | // Display some basic information about it 95 | Serial.println("Found an ISO14443A card/tag"); 96 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 97 | Serial.print(" UID Value: "); 98 | nfc.PrintHex(uid, uidLength); 99 | Serial.println(""); 100 | 101 | // Make sure this is a Mifare Classic card 102 | if (uidLength != 4) 103 | { 104 | Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!"); 105 | return; 106 | } 107 | 108 | Serial.println("Seems to be a Mifare Classic card (4 byte UID)"); 109 | Serial.println(""); 110 | Serial.println("Reformatting card for Mifare Classic (please don't touch it!) ... "); 111 | 112 | // Now run through the card sector by sector 113 | for (idx = 0; idx < numOfSector; idx++) 114 | { 115 | // Step 1: Authenticate the current sector using key B 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 116 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, BLOCK_NUMBER_OF_SECTOR_TRAILER(idx), 1, (uint8_t *)KEY_DEFAULT_KEYAB); 117 | if (!success) 118 | { 119 | Serial.print("Authentication failed for sector "); Serial.println(numOfSector); 120 | return; 121 | } 122 | 123 | // Step 2: Write to the other blocks 124 | if (idx == 16) 125 | { 126 | memset(blockBuffer, 0, sizeof(blockBuffer)); 127 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer))) 128 | { 129 | Serial.print("Unable to write to sector "); Serial.println(numOfSector); 130 | return; 131 | } 132 | } 133 | if ((idx == 0) || (idx == 16)) 134 | { 135 | memset(blockBuffer, 0, sizeof(blockBuffer)); 136 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer))) 137 | { 138 | Serial.print("Unable to write to sector "); Serial.println(numOfSector); 139 | return; 140 | } 141 | } 142 | else 143 | { 144 | memset(blockBuffer, 0, sizeof(blockBuffer)); 145 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer))) 146 | { 147 | Serial.print("Unable to write to sector "); Serial.println(numOfSector); 148 | return; 149 | } 150 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer))) 151 | { 152 | Serial.print("Unable to write to sector "); Serial.println(numOfSector); 153 | return; 154 | } 155 | } 156 | memset(blockBuffer, 0, sizeof(blockBuffer)); 157 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 1, blockBuffer))) 158 | { 159 | Serial.print("Unable to write to sector "); Serial.println(numOfSector); 160 | return; 161 | } 162 | 163 | // Step 3: Reset both keys to 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 164 | memcpy(blockBuffer, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB)); 165 | memcpy(blockBuffer + 6, blankAccessBits, sizeof(blankAccessBits)); 166 | blockBuffer[9] = 0x69; 167 | memcpy(blockBuffer + 10, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB)); 168 | 169 | // Step 4: Write the trailer block 170 | if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)), blockBuffer))) 171 | { 172 | Serial.print("Unable to write trailer block of sector "); Serial.println(numOfSector); 173 | return; 174 | } 175 | } 176 | } 177 | 178 | // Wait a bit before trying again 179 | Serial.println("\n\nDone!"); 180 | delay(1000); 181 | Serial.flush(); 182 | while(Serial.available()) Serial.read(); 183 | } -------------------------------------------------------------------------------- /PN532/examples/mifareclassic_updatendef/mifareclassic_updatendef.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | Updates a sector that is already formatted for NDEF (using 4 | mifareclassic_formatndef.pde for example), inserting a new url 5 | 6 | To enable debug message, define DEBUG in PN532/PN532_debug.h 7 | */ 8 | /**************************************************************************/ 9 | 10 | #if 0 11 | #include 12 | #include 13 | #include "PN532.h" 14 | 15 | PN532_SPI pn532spi(SPI, 10); 16 | PN532 nfc(pn532spi); 17 | #elif 1 18 | #include 19 | #include 20 | 21 | PN532_HSU pn532hsu(Serial1); 22 | PN532 nfc(pn532hsu); 23 | #else 24 | #include 25 | #include 26 | #include 27 | #endif 28 | 29 | 30 | /* 31 | We can encode many different kinds of pointers to the card, 32 | from a URL, to an Email address, to a phone number, and many more 33 | check the library header .h file to see the large # of supported 34 | prefixes! 35 | */ 36 | // For a http://www. url: 37 | const char * url = "elechouse.com"; 38 | uint8_t ndefprefix = NDEF_URIPREFIX_HTTP_WWWDOT; 39 | 40 | // for an email address 41 | //const char * url = "mail@example.com"; 42 | //uint8_t ndefprefix = NDEF_URIPREFIX_MAILTO; 43 | 44 | // for a phone number 45 | //const char * url = "+1 212 555 1212"; 46 | //uint8_t ndefprefix = NDEF_URIPREFIX_TEL; 47 | 48 | 49 | void setup(void) { 50 | Serial.begin(115200); 51 | Serial.println("Looking for PN532..."); 52 | 53 | nfc.begin(); 54 | 55 | uint32_t versiondata = nfc.getFirmwareVersion(); 56 | if (! versiondata) { 57 | Serial.print("Didn't find PN53x board"); 58 | while (1); // halt 59 | } 60 | 61 | // Got ok data, print it out! 62 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 63 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 64 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 65 | 66 | // configure board to read RFID tags 67 | nfc.SAMConfig(); 68 | } 69 | 70 | void loop(void) { 71 | uint8_t success; // Flag to check if there was an error with the PN532 72 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 73 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 74 | bool authenticated = false; // Flag to indicate if the sector is authenticated 75 | 76 | // Use the default NDEF keys (these would have have set by mifareclassic_formatndef.pde!) 77 | uint8_t keya[6] = { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 }; 78 | uint8_t keyb[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; 79 | 80 | Serial.println("Place your NDEF formatted Mifare Classic card on the reader to update the"); 81 | Serial.println("NDEF record and press any key to continue ..."); 82 | // Wait for user input before proceeding 83 | while (!Serial.available()); 84 | // a key was pressed1 85 | while (Serial.available()) Serial.read(); 86 | 87 | // Wait for an ISO14443A type card (Mifare, etc.). When one is found 88 | // 'uid' will be populated with the UID, and uidLength will indicate 89 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 90 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 91 | 92 | if (success) 93 | { 94 | // Display some basic information about the card 95 | Serial.println("Found an ISO14443A card"); 96 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 97 | Serial.print(" UID Value: "); 98 | nfc.PrintHex(uid, uidLength); 99 | Serial.println(""); 100 | 101 | // Make sure this is a Mifare Classic card 102 | if (uidLength != 4) 103 | { 104 | Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!"); 105 | return; 106 | } 107 | 108 | // We probably have a Mifare Classic card ... 109 | Serial.println("Seems to be a Mifare Classic card (4 byte UID)"); 110 | 111 | // Check if this is an NDEF card (using first block of sector 1 from mifareclassic_formatndef.pde) 112 | // Must authenticate on the first key using 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 113 | success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 4, 0, keyb); 114 | if (!success) 115 | { 116 | Serial.println("Unable to authenticate block 4 ... is this card NDEF formatted?"); 117 | return; 118 | } 119 | 120 | Serial.println("Authentication succeeded (seems to be an NDEF/NFC Forum tag) ..."); 121 | 122 | // Authenticated seems to have worked 123 | // Try to write an NDEF record to sector 1 124 | // Use 0x01 for the URI Identifier Code to prepend "http://www." 125 | // to the url (and save some space). For information on URI ID Codes 126 | // see http://www.ladyada.net/wiki/private/articlestaging/nfc/ndef 127 | if (strlen(url) > 38) 128 | { 129 | // The length is also checked in the WriteNDEFURI function, but lets 130 | // warn users here just in case they change the value and it's bigger 131 | // than it should be 132 | Serial.println("URI is too long ... must be less than 38 characters!"); 133 | return; 134 | } 135 | 136 | Serial.println("Updating sector 1 with URI as NDEF Message"); 137 | 138 | // URI is within size limits ... write it to the card and report success/failure 139 | success = nfc.mifareclassic_WriteNDEFURI(1, ndefprefix, url); 140 | if (success) 141 | { 142 | Serial.println("NDEF URI Record written to sector 1"); 143 | Serial.println(""); 144 | } 145 | else 146 | { 147 | Serial.println("NDEF Record creation failed! :("); 148 | } 149 | } 150 | 151 | // Wait a bit before trying again 152 | Serial.println("\n\nDone!"); 153 | delay(1000); 154 | Serial.flush(); 155 | while(Serial.available()) Serial.read(); 156 | } 157 | -------------------------------------------------------------------------------- /PN532/examples/p2p_raw/p2p_raw.ino: -------------------------------------------------------------------------------- 1 | // snep_test.ino 2 | // send a SNEP message to adnroid and get a message from android 3 | 4 | #include "SPI.h" 5 | #include "PN532_SPI.h" 6 | #include "llcp.h" 7 | #include "snep.h" 8 | 9 | PN532_SPI pn532spi(SPI, 10); 10 | SNEP nfc(pn532spi); 11 | 12 | void setup() 13 | { 14 | Serial.begin(115200); 15 | Serial.println("-------Peer to Peer--------"); 16 | } 17 | 18 | uint8_t message[] = { 19 | 0xD2, 0xA, 0xB, 0x74,0x65, 0x78, 0x74, 0x2F, 0x70, 0x6C, 20 | 0x61, 0x69, 0x6E, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 21 | 0x6F, 0x72, 0x6C, 0x64}; 22 | 23 | uint8_t buf[128]; 24 | 25 | void loop() 26 | { 27 | 28 | nfc.write(message, sizeof(message)); 29 | delay(3000); 30 | 31 | int16_t len = nfc.read(buf, sizeof(buf)); 32 | if (len > 0) { 33 | Serial.println("get a SNEP message:"); 34 | for (uint8_t i = 0; i < len; i++) { 35 | Serial.print(buf[i], HEX); 36 | Serial.print(' '); 37 | } 38 | Serial.print('\n'); 39 | for (uint8_t i = 0; i < len; i++) { 40 | char c = buf[i]; 41 | if (c <= 0x1f || c > 0x7f) { 42 | Serial.print('.'); 43 | } else { 44 | Serial.print(c); 45 | } 46 | } 47 | Serial.print('\n'); 48 | } 49 | delay(3000); 50 | } -------------------------------------------------------------------------------- /PN532/examples/p2p_with_ndef_library/p2p_with_ndef_library.ino: -------------------------------------------------------------------------------- 1 | // send a NDEF message to adnroid or get a NDEF message 2 | // 3 | // note: [NDEF library](https://github.com/Don/NDEF) is needed. 4 | 5 | #include "SPI.h" 6 | #include "PN532_SPI.h" 7 | #include "snep.h" 8 | #include "NdefMessage.h" 9 | 10 | PN532_SPI pn532spi(SPI, 10); 11 | SNEP nfc(pn532spi); 12 | uint8_t ndefBuf[128]; 13 | 14 | void setup() 15 | { 16 | Serial.begin(115200); 17 | Serial.println("-------Peer to Peer--------"); 18 | } 19 | 20 | void loop() 21 | { 22 | #if 1 23 | Serial.println("Send a message to Android"); 24 | NdefMessage message = NdefMessage(); 25 | message.addUriRecord("http://www.seeedstudio.com"); 26 | int messageSize = message.getEncodedSize(); 27 | if (messageSize > sizeof(ndefBuf)) { 28 | Serial.println("ndefBuf is too small"); 29 | while (1) { 30 | } 31 | 32 | } 33 | 34 | message.encode(ndefBuf); 35 | if (0 >= nfc.write(ndefBuf, messageSize)) { 36 | Serial.println("Failed"); 37 | } else { 38 | Serial.println("Success"); 39 | } 40 | 41 | delay(3000); 42 | #else 43 | // it seems there are some issues to use NdefMessage to decode the received data from Android 44 | Serial.println("Get a message from Android"); 45 | int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf)); 46 | if (msgSize > 0) { 47 | NdefMessage msg = NdefMessage(ndefBuf, msgSize); 48 | msg.print(); 49 | Serial.println("\nSuccess"); 50 | } else { 51 | Serial.println("failed"); 52 | } 53 | delay(3000); 54 | #endif 55 | } 56 | -------------------------------------------------------------------------------- /PN532/examples/readMifare/readMifare.pde: -------------------------------------------------------------------------------- 1 | /**************************************************************************/ 2 | /*! 3 | This example will wait for any ISO14443A card or tag, and 4 | depending on the size of the UID will attempt to read from it. 5 | 6 | If the card has a 4-byte UID it is probably a Mifare 7 | Classic card, and the following steps are taken: 8 | 9 | - Authenticate block 4 (the first block of Sector 1) using 10 | the default KEYA of 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF 11 | - If authentication succeeds, we can then read any of the 12 | 4 blocks in that sector (though only block 4 is read here) 13 | 14 | If the card has a 7-byte UID it is probably a Mifare 15 | Ultralight card, and the 4 byte pages can be read directly. 16 | Page 4 is read by default since this is the first 'general- 17 | purpose' page on the tags. 18 | 19 | To enable debug message, define DEBUG in PN532/PN532_debug.h 20 | */ 21 | /**************************************************************************/ 22 | 23 | #if 0 24 | #include 25 | #include 26 | #include "PN532.h" 27 | 28 | PN532_SPI pn532spi(SPI, 10); 29 | PN532 nfc(pn532spi); 30 | #elif 1 31 | #include 32 | #include 33 | 34 | PN532_HSU pn532hsu(Serial1); 35 | PN532 nfc(pn532hsu); 36 | #else 37 | #include 38 | #include 39 | #include 40 | PN532_I2C pn532i2c(Wire); 41 | PN532 nfc(pn532i2c); 42 | #endif 43 | void setup(void) { 44 | Serial.begin(115200); 45 | Serial.println("Hello!"); 46 | 47 | nfc.begin(); 48 | 49 | uint32_t versiondata = nfc.getFirmwareVersion(); 50 | if (! versiondata) { 51 | Serial.print("Didn't find PN53x board"); 52 | while (1); // halt 53 | } 54 | // Got ok data, print it out! 55 | Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX); 56 | Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC); 57 | Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC); 58 | 59 | // configure board to read RFID tags 60 | nfc.SAMConfig(); 61 | 62 | Serial.println("Waiting for an ISO14443A Card ..."); 63 | } 64 | 65 | 66 | void loop(void) { 67 | uint8_t success; 68 | uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID 69 | uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type) 70 | 71 | // Wait for an ISO14443A type cards (Mifare, etc.). When one is found 72 | // 'uid' will be populated with the UID, and uidLength will indicate 73 | // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight) 74 | success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength); 75 | 76 | if (success) { 77 | // Display some basic information about the card 78 | Serial.println("Found an ISO14443A card"); 79 | Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes"); 80 | Serial.print(" UID Value: "); 81 | nfc.PrintHex(uid, uidLength); 82 | Serial.println(""); 83 | 84 | if (uidLength == 4) 85 | { 86 | // We probably have a Mifare Classic card ... 87 | Serial.println("Seems to be a Mifare Classic card (4 byte UID)"); 88 | 89 | // Now we need to try to authenticate it for read/write access 90 | // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 91 | Serial.println("Trying to authenticate block 4 with default KEYA value"); 92 | uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; 93 | 94 | // Start with block 4 (the first block of sector 1) since sector 0 95 | // contains the manufacturer data and it's probably better just 96 | // to leave it alone unless you know what you're doing 97 | success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya); 98 | 99 | if (success) 100 | { 101 | Serial.println("Sector 1 (Blocks 4..7) has been authenticated"); 102 | uint8_t data[16]; 103 | 104 | // If you want to write something to block 4 to test with, uncomment 105 | // the following line and this text should be read back in a minute 106 | // data = { 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0}; 107 | // success = nfc.mifareclassic_WriteDataBlock (4, data); 108 | 109 | // Try to read the contents of block 4 110 | success = nfc.mifareclassic_ReadDataBlock(4, data); 111 | 112 | if (success) 113 | { 114 | // Data seems to have been read ... spit it out 115 | Serial.println("Reading Block 4:"); 116 | nfc.PrintHexChar(data, 16); 117 | Serial.println(""); 118 | 119 | // Wait a bit before reading the card again 120 | delay(1000); 121 | } 122 | else 123 | { 124 | Serial.println("Ooops ... unable to read the requested block. Try another key?"); 125 | } 126 | } 127 | else 128 | { 129 | Serial.println("Ooops ... authentication failed: Try another key?"); 130 | } 131 | } 132 | 133 | if (uidLength == 7) 134 | { 135 | // We probably have a Mifare Ultralight card ... 136 | Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)"); 137 | 138 | // Try to read the first general-purpose user page (#4) 139 | Serial.println("Reading page 4"); 140 | uint8_t data[32]; 141 | success = nfc.mifareultralight_ReadPage (4, data); 142 | if (success) 143 | { 144 | // Data seems to have been read ... spit it out 145 | nfc.PrintHexChar(data, 4); 146 | Serial.println(""); 147 | 148 | // Wait a bit before reading the card again 149 | delay(1000); 150 | } 151 | else 152 | { 153 | Serial.println("Ooops ... unable to read the requested page!?"); 154 | } 155 | } 156 | } 157 | } 158 | 159 | -------------------------------------------------------------------------------- /PN532/license.txt: -------------------------------------------------------------------------------- 1 | Software License Agreement (BSD License) 2 | 3 | Copyright (c) 2012, Adafruit Industries 4 | Copyright (c) 2013, Seeed Technology Inc. 5 | All rights reserved. 6 | 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are met: 9 | 1. Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 2. Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in the 13 | documentation and/or other materials provided with the distribution. 14 | 3. Neither the name of the copyright holders nor the 15 | names of its contributors may be used to endorse or promote products 16 | derived from this software without specific prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY 19 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY 22 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 23 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 24 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 25 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 27 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /PN532/llcp.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "llcp.h" 3 | #include "PN532_debug.h" 4 | 5 | // LLCP PDU Type Values 6 | #define PDU_SYMM 0x00 7 | #define PDU_PAX 0x01 8 | #define PDU_CONNECT 0x04 9 | #define PDU_DISC 0x05 10 | #define PDU_CC 0x06 11 | #define PDU_DM 0x07 12 | #define PDU_I 0x0c 13 | #define PDU_RR 0x0d 14 | 15 | uint8_t LLCP::SYMM_PDU[2] = {0, 0}; 16 | 17 | inline uint8_t getPType(const uint8_t *buf) 18 | { 19 | return ((buf[0] & 0x3) << 2) + (buf[1] >> 6); 20 | } 21 | 22 | inline uint8_t getSSAP(const uint8_t *buf) 23 | { 24 | return buf[1] & 0x3f; 25 | } 26 | 27 | inline uint8_t getDSAP(const uint8_t *buf) 28 | { 29 | return buf[0] >> 2; 30 | } 31 | 32 | int8_t LLCP::activate(uint16_t timeout) 33 | { 34 | return link.activateAsTarget(timeout); 35 | } 36 | 37 | int8_t LLCP::waitForConnection(uint16_t timeout) 38 | { 39 | uint8_t type; 40 | 41 | mode = 1; 42 | ns = 0; 43 | nr = 0; 44 | 45 | // Get CONNECT PDU 46 | DMSG("wait for a CONNECT PDU\n"); 47 | do { 48 | if (2 > link.read(headerBuf, headerBufLen)) { 49 | return -1; 50 | } 51 | 52 | type = getPType(headerBuf); 53 | if (PDU_CONNECT == type) { 54 | break; 55 | } else if (PDU_SYMM == type) { 56 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 57 | return -2; 58 | } 59 | } else { 60 | return -3; 61 | } 62 | 63 | } while (1); 64 | 65 | // Put CC PDU 66 | DMSG("put a CC(Connection Complete) PDU to response the CONNECT PDU\n"); 67 | ssap = getDSAP(headerBuf); 68 | dsap = getSSAP(headerBuf); 69 | headerBuf[0] = (dsap << 2) + ((PDU_CC >> 2) & 0x3); 70 | headerBuf[1] = ((PDU_CC & 0x3) << 6) + ssap; 71 | if (!link.write(headerBuf, 2)) { 72 | return -2; 73 | } 74 | 75 | return 1; 76 | } 77 | 78 | int8_t LLCP::waitForDisconnection(uint16_t timeout) 79 | { 80 | uint8_t type; 81 | 82 | // Get DISC PDU 83 | DMSG("wait for a DISC PDU\n"); 84 | do { 85 | if (2 > link.read(headerBuf, headerBufLen)) { 86 | return -1; 87 | } 88 | 89 | type = getPType(headerBuf); 90 | if (PDU_DISC == type) { 91 | break; 92 | } else if (PDU_SYMM == type) { 93 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 94 | return -2; 95 | } 96 | } else { 97 | return -3; 98 | } 99 | 100 | } while (1); 101 | 102 | // Put DM PDU 103 | DMSG("put a DM(Disconnect Mode) PDU to response the DISC PDU\n"); 104 | // ssap = getDSAP(headerBuf); 105 | // dsap = getSSAP(headerBuf); 106 | headerBuf[0] = (dsap << 2) + (PDU_DM >> 2); 107 | headerBuf[1] = ((PDU_DM & 0x3) << 6) + ssap; 108 | if (!link.write(headerBuf, 2)) { 109 | return -2; 110 | } 111 | 112 | return 1; 113 | } 114 | 115 | int8_t LLCP::connect(uint16_t timeout) 116 | { 117 | uint8_t type; 118 | 119 | mode = 0; 120 | dsap = LLCP_DEFAULT_DSAP; 121 | ssap = LLCP_DEFAULT_SSAP; 122 | ns = 0; 123 | nr = 0; 124 | 125 | // try to get a SYMM PDU 126 | if (2 > link.read(headerBuf, headerBufLen)) { 127 | return -1; 128 | } 129 | type = getPType(headerBuf); 130 | if (PDU_SYMM != type) { 131 | return -1; 132 | } 133 | 134 | // put a CONNECT PDU 135 | headerBuf[0] = (LLCP_DEFAULT_DSAP << 2) + (PDU_CONNECT >> 2); 136 | headerBuf[1] = ((PDU_CONNECT & 0x03) << 6) + LLCP_DEFAULT_SSAP; 137 | uint8_t body[] = " urn:nfc:sn:snep"; 138 | body[0] = 0x06; 139 | body[1] = sizeof(body) - 2 - 1; 140 | if (!link.write(headerBuf, 2, body, sizeof(body) - 1)) { 141 | return -2; 142 | } 143 | 144 | // wait for a CC PDU 145 | DMSG("wait for a CC PDU\n"); 146 | do { 147 | if (2 > link.read(headerBuf, headerBufLen)) { 148 | return -1; 149 | } 150 | 151 | type = getPType(headerBuf); 152 | if (PDU_CC == type) { 153 | break; 154 | } else if (PDU_SYMM == type) { 155 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 156 | return -2; 157 | } 158 | } else { 159 | return -3; 160 | } 161 | 162 | } while (1); 163 | 164 | return 1; 165 | } 166 | 167 | int8_t LLCP::disconnect(uint16_t timeout) 168 | { 169 | uint8_t type; 170 | 171 | // try to get a SYMM PDU 172 | if (2 > link.read(headerBuf, headerBufLen)) { 173 | return -1; 174 | } 175 | type = getPType(headerBuf); 176 | if (PDU_SYMM != type) { 177 | return -1; 178 | } 179 | 180 | // put a DISC PDU 181 | headerBuf[0] = (LLCP_DEFAULT_DSAP << 2) + (PDU_DISC >> 2); 182 | headerBuf[1] = ((PDU_DISC & 0x03) << 6) + LLCP_DEFAULT_SSAP; 183 | if (!link.write(headerBuf, 2)) { 184 | return -2; 185 | } 186 | 187 | // wait for a DM PDU 188 | DMSG("wait for a DM PDU\n"); 189 | do { 190 | if (2 > link.read(headerBuf, headerBufLen)) { 191 | return -1; 192 | } 193 | 194 | type = getPType(headerBuf); 195 | if (PDU_CC == type) { 196 | break; 197 | } else if (PDU_DM == type) { 198 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 199 | return -2; 200 | } 201 | } else { 202 | return -3; 203 | } 204 | 205 | } while (1); 206 | 207 | return 1; 208 | } 209 | 210 | bool LLCP::write(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 211 | { 212 | uint8_t type; 213 | uint8_t buf[3]; 214 | 215 | if (mode) { 216 | // Get a SYMM PDU 217 | if (2 != link.read(buf, sizeof(buf))) { 218 | return false; 219 | } 220 | } 221 | 222 | if (headerBufLen < (hlen + 3)) { 223 | return false; 224 | } 225 | 226 | for (int8_t i = hlen - 1; i >= 0; i--) { 227 | headerBuf[i + 3] = header[i]; 228 | } 229 | 230 | headerBuf[0] = (dsap << 2) + (PDU_I >> 2); 231 | headerBuf[1] = ((PDU_I & 0x3) << 6) + ssap; 232 | headerBuf[2] = (ns << 4) + nr; 233 | if (!link.write(headerBuf, 3 + hlen, body, blen)) { 234 | return false; 235 | } 236 | 237 | ns++; 238 | 239 | // Get a RR PDU 240 | int16_t status; 241 | do { 242 | status = link.read(headerBuf, headerBufLen); 243 | if (2 > status) { 244 | return false; 245 | } 246 | 247 | type = getPType(headerBuf); 248 | if (PDU_RR == type) { 249 | break; 250 | } else if (PDU_SYMM == type) { 251 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 252 | return false; 253 | } 254 | } else { 255 | return false; 256 | } 257 | } while (1); 258 | 259 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 260 | return false; 261 | } 262 | 263 | return true; 264 | } 265 | 266 | int16_t LLCP::read(uint8_t *buf, uint8_t length) 267 | { 268 | uint8_t type; 269 | uint16_t status; 270 | 271 | // Get INFO PDU 272 | do { 273 | status = link.read(buf, length); 274 | if (2 > status) { 275 | return -1; 276 | } 277 | 278 | type = getPType(buf); 279 | if (PDU_I == type) { 280 | break; 281 | } else if (PDU_SYMM == type) { 282 | if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) { 283 | return -2; 284 | } 285 | } else { 286 | return -3; 287 | } 288 | 289 | } while (1); 290 | 291 | uint8_t len = status - 3; 292 | ssap = getDSAP(buf); 293 | dsap = getSSAP(buf); 294 | 295 | headerBuf[0] = (dsap << 2) + (PDU_RR >> 2); 296 | headerBuf[1] = ((PDU_RR & 0x3) << 6) + ssap; 297 | headerBuf[2] = (buf[2] >> 4) + 1; 298 | if (!link.write(headerBuf, 3)) { 299 | return -2; 300 | } 301 | 302 | for (uint8_t i = 0; i < len; i++) { 303 | buf[i] = buf[i + 3]; 304 | } 305 | 306 | nr++; 307 | 308 | return len; 309 | } 310 | -------------------------------------------------------------------------------- /PN532/llcp.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __LLCP_H__ 3 | #define __LLCP_H__ 4 | 5 | #include "mac_link.h" 6 | 7 | #define LLCP_DEFAULT_TIMEOUT 20000 8 | #define LLCP_DEFAULT_DSAP 0x04 9 | #define LLCP_DEFAULT_SSAP 0x20 10 | 11 | class LLCP { 12 | public: 13 | LLCP(PN532Interface &interface) : link(interface) { 14 | headerBuf = link.getHeaderBuffer(&headerBufLen); 15 | ns = 0; 16 | nr = 0; 17 | }; 18 | 19 | /** 20 | * @brief Actiave PN532 as a target 21 | * @param timeout max time to wait, 0 means no timeout 22 | * @return > 0 success 23 | * = 0 timeout 24 | * < 0 failed 25 | */ 26 | int8_t activate(uint16_t timeout = 0); 27 | 28 | int8_t waitForConnection(uint16_t timeout = LLCP_DEFAULT_TIMEOUT); 29 | 30 | int8_t waitForDisconnection(uint16_t timeout = LLCP_DEFAULT_TIMEOUT); 31 | 32 | int8_t connect(uint16_t timeout = LLCP_DEFAULT_TIMEOUT); 33 | 34 | int8_t disconnect(uint16_t timeout = LLCP_DEFAULT_TIMEOUT); 35 | 36 | /** 37 | * @brief write a packet, the packet should be less than (255 - 2) bytes 38 | * @param header packet header 39 | * @param hlen length of header 40 | * @param body packet body 41 | * @param blen length of body 42 | * @return true success 43 | * false failed 44 | */ 45 | bool write(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 46 | 47 | /** 48 | * @brief read a packet, the packet will be less than (255 - 2) bytes 49 | * @param buf the buffer to contain the packet 50 | * @param len lenght of the buffer 51 | * @return >=0 length of the packet 52 | * <0 failed 53 | */ 54 | int16_t read(uint8_t *buf, uint8_t len); 55 | 56 | uint8_t *getHeaderBuffer(uint8_t *len) { 57 | uint8_t *buf = link.getHeaderBuffer(len); 58 | len -= 3; // I PDU header has 3 bytes 59 | return buf; 60 | }; 61 | 62 | private: 63 | MACLink link; 64 | uint8_t mode; 65 | uint8_t ssap; 66 | uint8_t dsap; 67 | uint8_t *headerBuf; 68 | uint8_t headerBufLen; 69 | uint8_t ns; // Number of I PDU Sent 70 | uint8_t nr; // Number of I PDU Received 71 | 72 | static uint8_t SYMM_PDU[2]; 73 | }; 74 | 75 | #endif // __LLCP_H__ 76 | -------------------------------------------------------------------------------- /PN532/mac_link.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "mac_link.h" 3 | #include "PN532_debug.h" 4 | 5 | int8_t MACLink::activateAsTarget(uint16_t timeout) 6 | { 7 | pn532.begin(); 8 | pn532.SAMConfig(); 9 | return pn532.tgInitAsTarget(timeout); 10 | } 11 | 12 | bool MACLink::write(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 13 | { 14 | return pn532.tgSetData(header, hlen, body, blen); 15 | } 16 | 17 | int16_t MACLink::read(uint8_t *buf, uint8_t len) 18 | { 19 | return pn532.tgGetData(buf, len); 20 | } 21 | -------------------------------------------------------------------------------- /PN532/mac_link.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #ifndef __MAC_LINK_H__ 4 | #define __MAC_LINK_H__ 5 | 6 | #include "PN532.h" 7 | 8 | class MACLink { 9 | public: 10 | MACLink(PN532Interface &interface) : pn532(interface) { 11 | 12 | }; 13 | 14 | /** 15 | * @brief Activate PN532 as a target 16 | * @param timeout max time to wait, 0 means no timeout 17 | * @return > 0 success 18 | * = 0 timeout 19 | * < 0 failed 20 | */ 21 | int8_t activateAsTarget(uint16_t timeout = 0); 22 | 23 | /** 24 | * @brief write a PDU packet, the packet should be less than (255 - 2) bytes 25 | * @param header packet header 26 | * @param hlen length of header 27 | * @param body packet body 28 | * @param blen length of body 29 | * @return true success 30 | * false failed 31 | */ 32 | bool write(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 33 | 34 | /** 35 | * @brief read a PDU packet, the packet will be less than (255 - 2) bytes 36 | * @param buf the buffer to contain the PDU packet 37 | * @param len lenght of the buffer 38 | * @return >=0 length of the PDU packet 39 | * <0 failed 40 | */ 41 | int16_t read(uint8_t *buf, uint8_t len); 42 | 43 | uint8_t *getHeaderBuffer(uint8_t *len) { 44 | return pn532.getBuffer(len); 45 | }; 46 | 47 | private: 48 | PN532 pn532; 49 | }; 50 | 51 | #endif // __MAC_LINK_H__ 52 | -------------------------------------------------------------------------------- /PN532/snep.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "snep.h" 3 | #include "PN532_debug.h" 4 | 5 | int8_t SNEP::write(const uint8_t *buf, uint8_t len, uint16_t timeout) 6 | { 7 | if (0 >= llcp.activate(timeout)) { 8 | DMSG("failed to activate PN532 as a target\n"); 9 | return -1; 10 | } 11 | 12 | if (0 >= llcp.connect(timeout)) { 13 | DMSG("failed to set up a connection\n"); 14 | return -2; 15 | } 16 | 17 | // response a success SNEP message 18 | headerBuf[0] = SNEP_DEFAULT_VERSION; 19 | headerBuf[1] = SNEP_REQUEST_PUT; 20 | headerBuf[2] = 0; 21 | headerBuf[3] = 0; 22 | headerBuf[4] = 0; 23 | headerBuf[5] = len; 24 | if (0 >= llcp.write(headerBuf, 6, buf, len)) { 25 | return -3; 26 | } 27 | 28 | uint8_t rbuf[16]; 29 | if (6 > llcp.read(rbuf, sizeof(rbuf))) { 30 | return -4; 31 | } 32 | 33 | // check SNEP version 34 | if (SNEP_DEFAULT_VERSION != rbuf[0]) { 35 | DMSG("The received SNEP message's major version is different\n"); 36 | // To-do: send Unsupported Version response 37 | return -4; 38 | } 39 | 40 | // expect a put request 41 | if (SNEP_RESPONSE_SUCCESS != rbuf[1]) { 42 | DMSG("Expect a success response\n"); 43 | return -4; 44 | } 45 | 46 | llcp.disconnect(timeout); 47 | 48 | return 1; 49 | } 50 | 51 | int16_t SNEP::read(uint8_t *buf, uint8_t len, uint16_t timeout) 52 | { 53 | if (0 >= llcp.activate(timeout)) { 54 | DMSG("failed to activate PN532 as a target\n"); 55 | return -1; 56 | } 57 | 58 | if (0 >= llcp.waitForConnection(timeout)) { 59 | DMSG("failed to set up a connection\n"); 60 | return -2; 61 | } 62 | 63 | uint16_t status = llcp.read(buf, len); 64 | if (6 > status) { 65 | return -3; 66 | } 67 | 68 | 69 | // check SNEP version 70 | if (SNEP_DEFAULT_VERSION != buf[0]) { 71 | DMSG("The received SNEP message's major version is different\n"); 72 | // To-do: send Unsupported Version response 73 | return -4; 74 | } 75 | 76 | // expect a put request 77 | if (SNEP_REQUEST_PUT != buf[1]) { 78 | DMSG("Expect a put request\n"); 79 | return -4; 80 | } 81 | 82 | // check message's length 83 | uint32_t length = (buf[2] << 24) + (buf[3] << 16) + (buf[4] << 8) + buf[5]; 84 | // length should not be more than 244 (header + body < 255, header = 6 + 3 + 2) 85 | if (length > (status - 6)) { 86 | DMSG("The SNEP message is too large: "); 87 | DMSG_INT(length); 88 | DMSG_INT(status - 6); 89 | DMSG("\n"); 90 | return -4; 91 | } 92 | for (uint8_t i = 0; i < length; i++) { 93 | buf[i] = buf[i + 6]; 94 | } 95 | 96 | // response a success SNEP message 97 | headerBuf[0] = SNEP_DEFAULT_VERSION; 98 | headerBuf[1] = SNEP_RESPONSE_SUCCESS; 99 | headerBuf[2] = 0; 100 | headerBuf[3] = 0; 101 | headerBuf[4] = 0; 102 | headerBuf[5] = 0; 103 | llcp.write(headerBuf, 6); 104 | 105 | return length; 106 | } 107 | -------------------------------------------------------------------------------- /PN532/snep.h: -------------------------------------------------------------------------------- 1 | 2 | 3 | #ifndef __SNEP_H__ 4 | #define __SNEP_H__ 5 | 6 | #include "llcp.h" 7 | 8 | #define SNEP_DEFAULT_VERSION 0x10 // Major: 1, Minor: 0 9 | 10 | #define SNEP_REQUEST_PUT 0x02 11 | #define SNEP_REQUEST_GET 0x01 12 | 13 | #define SNEP_RESPONSE_SUCCESS 0x81 14 | #define SNEP_RESPONSE_REJECT 0xFF 15 | 16 | class SNEP { 17 | public: 18 | SNEP(PN532Interface &interface) : llcp(interface) { 19 | headerBuf = llcp.getHeaderBuffer(&headerBufLen); 20 | }; 21 | 22 | /** 23 | * @brief write a SNEP packet, the packet should be less than (255 - 2 - 3) bytes 24 | * @param buf the buffer to contain the packet 25 | * @param len lenght of the buffer 26 | * @param timeout max time to wait, 0 means no timeout 27 | * @return >0 success 28 | * =0 timeout 29 | * <0 failed 30 | */ 31 | int8_t write(const uint8_t *buf, uint8_t len, uint16_t timeout = 0); 32 | 33 | /** 34 | * @brief read a SNEP packet, the packet will be less than (255 - 2 - 3) bytes 35 | * @param buf the buffer to contain the packet 36 | * @param len lenght of the buffer 37 | * @param timeout max time to wait, 0 means no timeout 38 | * @return >=0 length of the packet 39 | * <0 failed 40 | */ 41 | int16_t read(uint8_t *buf, uint8_t len, uint16_t timeout = 0); 42 | 43 | private: 44 | LLCP llcp; 45 | uint8_t *headerBuf; 46 | uint8_t headerBufLen; 47 | }; 48 | 49 | #endif // __SNEP_H__ 50 | -------------------------------------------------------------------------------- /PN532_HSU/PN532_HSU.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "PN532_HSU.h" 3 | #include "PN532_debug.h" 4 | 5 | 6 | PN532_HSU::PN532_HSU(HardwareSerial &serial) 7 | { 8 | _serial = &serial; 9 | command = 0; 10 | } 11 | 12 | void PN532_HSU::begin() 13 | { 14 | _serial->begin(115200); 15 | } 16 | 17 | void PN532_HSU::wakeup() 18 | { 19 | _serial->write(0x55); 20 | _serial->write(0x55); 21 | _serial->write(0); 22 | _serial->write(0); 23 | _serial->write(0); 24 | 25 | /** dump serial buffer */ 26 | if(_serial->available()){ 27 | DMSG("Dump serial buffer: "); 28 | } 29 | while(_serial->available()){ 30 | uint8_t ret = _serial->read(); 31 | DMSG_HEX(ret); 32 | } 33 | 34 | } 35 | 36 | int8_t PN532_HSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 37 | { 38 | 39 | /** dump serial buffer */ 40 | if(_serial->available()){ 41 | DMSG("Dump serial buffer: "); 42 | } 43 | while(_serial->available()){ 44 | uint8_t ret = _serial->read(); 45 | DMSG_HEX(ret); 46 | } 47 | 48 | command = header[0]; 49 | 50 | _serial->write(PN532_PREAMBLE); 51 | _serial->write(PN532_STARTCODE1); 52 | _serial->write(PN532_STARTCODE2); 53 | 54 | uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA 55 | _serial->write(length); 56 | _serial->write(~length + 1); // checksum of length 57 | 58 | _serial->write(PN532_HOSTTOPN532); 59 | uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA 60 | 61 | DMSG("\nWrite: "); 62 | 63 | _serial->write(header, hlen); 64 | for (uint8_t i = 0; i < hlen; i++) { 65 | sum += header[i]; 66 | 67 | DMSG_HEX(header[i]); 68 | } 69 | 70 | _serial->write(body, blen); 71 | for (uint8_t i = 0; i < blen; i++) { 72 | sum += body[i]; 73 | 74 | DMSG_HEX(body[i]); 75 | } 76 | 77 | uint8_t checksum = ~sum + 1; // checksum of TFI + DATA 78 | _serial->write(checksum); 79 | _serial->write(PN532_POSTAMBLE); 80 | 81 | return readAckFrame(); 82 | } 83 | 84 | int16_t PN532_HSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) 85 | { 86 | uint8_t tmp[3]; 87 | 88 | DMSG("\nRead: "); 89 | 90 | /** Frame Preamble and Start Code */ 91 | if(receive(tmp, 3, timeout)<=0){ 92 | return PN532_TIMEOUT; 93 | } 94 | if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){ 95 | DMSG("Preamble error"); 96 | return PN532_INVALID_FRAME; 97 | } 98 | 99 | /** receive length and check */ 100 | uint8_t length[2]; 101 | if(receive(length, 2, timeout) <= 0){ 102 | return PN532_TIMEOUT; 103 | } 104 | if( 0 != (uint8_t)(length[0] + length[1]) ){ 105 | DMSG("Length error"); 106 | return PN532_INVALID_FRAME; 107 | } 108 | length[0] -= 2; 109 | if( length[0] > len){ 110 | return PN532_NO_SPACE; 111 | } 112 | 113 | /** receive command byte */ 114 | uint8_t cmd = command + 1; // response command 115 | if(receive(tmp, 2, timeout) <= 0){ 116 | return PN532_TIMEOUT; 117 | } 118 | if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){ 119 | DMSG("Command error"); 120 | return PN532_INVALID_FRAME; 121 | } 122 | 123 | if(receive(buf, length[0], timeout) != length[0]){ 124 | return PN532_TIMEOUT; 125 | } 126 | uint8_t sum = PN532_PN532TOHOST + cmd; 127 | for(uint8_t i=0; i return value buffer. 165 | len --> length expect to receive. 166 | timeout --> time of reveiving 167 | @retval number of received bytes, 0 means no data received. 168 | */ 169 | int8_t PN532_HSU::receive(uint8_t *buf, int len, uint16_t timeout) 170 | { 171 | int read_bytes = 0; 172 | int ret; 173 | unsigned long start_millis; 174 | 175 | while (read_bytes < len) { 176 | start_millis = millis(); 177 | do { 178 | ret = _serial->read(); 179 | if (ret >= 0) { 180 | break; 181 | } 182 | } while((timeout == 0) || ((millis()- start_millis ) < timeout)); 183 | 184 | if (ret < 0) { 185 | if(read_bytes){ 186 | return read_bytes; 187 | }else{ 188 | return PN532_TIMEOUT; 189 | } 190 | } 191 | buf[read_bytes] = (uint8_t)ret; 192 | DMSG_HEX(ret); 193 | read_bytes++; 194 | } 195 | return read_bytes; 196 | } 197 | -------------------------------------------------------------------------------- /PN532_HSU/PN532_HSU.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __PN532_HSU_H__ 3 | #define __PN532_HSU_H__ 4 | 5 | #include "PN532Interface.h" 6 | #include "Arduino.h" 7 | 8 | #define PN532_HSU_DEBUG 9 | 10 | #define PN532_HSU_READ_TIMEOUT (1000) 11 | 12 | class PN532_HSU : public PN532Interface { 13 | public: 14 | PN532_HSU(HardwareSerial &serial); 15 | 16 | void begin(); 17 | void wakeup(); 18 | virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 19 | int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); 20 | 21 | private: 22 | HardwareSerial* _serial; 23 | uint8_t command; 24 | 25 | int8_t readAckFrame(); 26 | 27 | int8_t receive(uint8_t *buf, int len, uint16_t timeout=PN532_HSU_READ_TIMEOUT); 28 | }; 29 | 30 | #endif 31 | -------------------------------------------------------------------------------- /PN532_I2C/PN532_I2C.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @modified picospuch 3 | */ 4 | 5 | #include "PN532_I2C.h" 6 | #include "PN532_debug.h" 7 | #include "Arduino.h" 8 | 9 | #define PN532_I2C_ADDRESS (0x48 >> 1) 10 | 11 | 12 | PN532_I2C::PN532_I2C(TwoWire &wire) 13 | { 14 | _wire = &wire; 15 | command = 0; 16 | } 17 | 18 | void PN532_I2C::begin() 19 | { 20 | _wire->begin(); 21 | } 22 | 23 | void PN532_I2C::wakeup() 24 | { 25 | delay(500); // wait for all ready to manipulate pn532 26 | } 27 | 28 | int8_t PN532_I2C::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 29 | { 30 | command = header[0]; 31 | _wire->beginTransmission(PN532_I2C_ADDRESS); 32 | 33 | write(PN532_PREAMBLE); 34 | write(PN532_STARTCODE1); 35 | write(PN532_STARTCODE2); 36 | 37 | uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA 38 | write(length); 39 | write(~length + 1); // checksum of length 40 | 41 | write(PN532_HOSTTOPN532); 42 | uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA 43 | 44 | DMSG("write: "); 45 | 46 | for (uint8_t i = 0; i < hlen; i++) { 47 | if (write(header[i])) { 48 | sum += header[i]; 49 | 50 | DMSG_HEX(header[i]); 51 | } else { 52 | DMSG("\nToo many data to send, I2C doesn't support such a big packet\n"); // I2C max packet: 32 bytes 53 | return PN532_INVALID_FRAME; 54 | } 55 | } 56 | 57 | for (uint8_t i = 0; i < blen; i++) { 58 | if (write(body[i])) { 59 | sum += body[i]; 60 | 61 | DMSG_HEX(body[i]); 62 | } else { 63 | DMSG("\nToo many data to send, I2C doesn't support such a big packet\n"); // I2C max packet: 32 bytes 64 | return PN532_INVALID_FRAME; 65 | } 66 | } 67 | 68 | uint8_t checksum = ~sum + 1; // checksum of TFI + DATA 69 | write(checksum); 70 | write(PN532_POSTAMBLE); 71 | 72 | _wire->endTransmission(); 73 | 74 | DMSG('\n'); 75 | 76 | return readAckFrame(); 77 | } 78 | 79 | int16_t PN532_I2C::getResponseLength(uint8_t buf[], uint8_t len, uint16_t timeout) { 80 | const uint8_t PN532_NACK[] = {0, 0, 0xFF, 0xFF, 0, 0}; 81 | uint16_t time = 0; 82 | 83 | do { 84 | if (_wire->requestFrom(PN532_I2C_ADDRESS, 6)) { 85 | if (read() & 1) { // check first byte --- status 86 | break; // PN532 is ready 87 | } 88 | } 89 | 90 | delay(1); 91 | time++; 92 | if ((0 != timeout) && (time > timeout)) { 93 | return -1; 94 | } 95 | } while (1); 96 | 97 | if (0x00 != read() || // PREAMBLE 98 | 0x00 != read() || // STARTCODE1 99 | 0xFF != read() // STARTCODE2 100 | ) { 101 | 102 | return PN532_INVALID_FRAME; 103 | } 104 | 105 | uint8_t length = read(); 106 | 107 | // request for last respond msg again 108 | _wire->beginTransmission(PN532_I2C_ADDRESS); 109 | for (uint16_t i = 0; i < sizeof(PN532_NACK); ++i) { 110 | write(PN532_NACK[i]); 111 | } 112 | _wire->endTransmission(); 113 | 114 | return length; 115 | } 116 | 117 | int16_t PN532_I2C::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) 118 | { 119 | uint16_t time = 0; 120 | uint8_t length; 121 | 122 | length = getResponseLength(buf, len, timeout); 123 | 124 | // [RDY] 00 00 FF LEN LCS (TFI PD0 ... PDn) DCS 00 125 | do { 126 | if (_wire->requestFrom(PN532_I2C_ADDRESS, 6 + length + 2)) { 127 | if (read() & 1) { // check first byte --- status 128 | break; // PN532 is ready 129 | } 130 | } 131 | 132 | delay(1); 133 | time++; 134 | if ((0 != timeout) && (time > timeout)) { 135 | return -1; 136 | } 137 | } while (1); 138 | 139 | if (0x00 != read() || // PREAMBLE 140 | 0x00 != read() || // STARTCODE1 141 | 0xFF != read() // STARTCODE2 142 | ) { 143 | 144 | return PN532_INVALID_FRAME; 145 | } 146 | 147 | length = read(); 148 | 149 | if (0 != (uint8_t)(length + read())) { // checksum of length 150 | return PN532_INVALID_FRAME; 151 | } 152 | 153 | uint8_t cmd = command + 1; // response command 154 | if (PN532_PN532TOHOST != read() || (cmd) != read()) { 155 | return PN532_INVALID_FRAME; 156 | } 157 | 158 | length -= 2; 159 | if (length > len) { 160 | return PN532_NO_SPACE; // not enough space 161 | } 162 | 163 | DMSG("read: "); 164 | DMSG_HEX(cmd); 165 | 166 | uint8_t sum = PN532_PN532TOHOST + cmd; 167 | for (uint8_t i = 0; i < length; i++) { 168 | buf[i] = read(); 169 | sum += buf[i]; 170 | 171 | DMSG_HEX(buf[i]); 172 | } 173 | DMSG('\n'); 174 | 175 | uint8_t checksum = read(); 176 | if (0 != (uint8_t)(sum + checksum)) { 177 | DMSG("checksum is not ok\n"); 178 | return PN532_INVALID_FRAME; 179 | } 180 | read(); // POSTAMBLE 181 | 182 | return length; 183 | } 184 | 185 | int8_t PN532_I2C::readAckFrame() 186 | { 187 | const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0}; 188 | uint8_t ackBuf[sizeof(PN532_ACK)]; 189 | 190 | DMSG("wait for ack at : "); 191 | DMSG(millis()); 192 | DMSG('\n'); 193 | 194 | uint16_t time = 0; 195 | do { 196 | if (_wire->requestFrom(PN532_I2C_ADDRESS, sizeof(PN532_ACK) + 1)) { 197 | if (read() & 1) { // check first byte --- status 198 | break; // PN532 is ready 199 | } 200 | } 201 | 202 | delay(1); 203 | time++; 204 | if (time > PN532_ACK_WAIT_TIME) { 205 | DMSG("Time out when waiting for ACK\n"); 206 | return PN532_TIMEOUT; 207 | } 208 | } while (1); 209 | 210 | DMSG("ready at : "); 211 | DMSG(millis()); 212 | DMSG('\n'); 213 | 214 | 215 | for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) { 216 | ackBuf[i] = read(); 217 | } 218 | 219 | if (memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK))) { 220 | DMSG("Invalid ACK\n"); 221 | return PN532_INVALID_ACK; 222 | } 223 | 224 | return 0; 225 | } 226 | -------------------------------------------------------------------------------- /PN532_I2C/PN532_I2C.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @modified picospuch 3 | */ 4 | 5 | #ifndef __PN532_I2C_H__ 6 | #define __PN532_I2C_H__ 7 | 8 | #include 9 | #include "PN532Interface.h" 10 | 11 | class PN532_I2C : public PN532Interface { 12 | public: 13 | PN532_I2C(TwoWire &wire); 14 | 15 | void begin(); 16 | void wakeup(); 17 | virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 18 | int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); 19 | 20 | private: 21 | TwoWire* _wire; 22 | uint8_t command; 23 | 24 | int8_t readAckFrame(); 25 | int16_t getResponseLength(uint8_t buf[], uint8_t len, uint16_t timeout); 26 | 27 | inline uint8_t write(uint8_t data) { 28 | #if ARDUINO >= 100 29 | return _wire->write(data); 30 | #else 31 | return _wire->send(data); 32 | #endif 33 | } 34 | 35 | inline uint8_t read() { 36 | #if ARDUINO >= 100 37 | return _wire->read(); 38 | #else 39 | return _wire->receive(); 40 | #endif 41 | } 42 | }; 43 | 44 | #endif 45 | -------------------------------------------------------------------------------- /PN532_SPI/PN532_SPI.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "PN532_SPI.h" 3 | #include "PN532_debug.h" 4 | #include "Arduino.h" 5 | 6 | #define STATUS_READ 2 7 | #define DATA_WRITE 1 8 | #define DATA_READ 3 9 | 10 | PN532_SPI::PN532_SPI(SPIClass &spi, uint8_t ss) 11 | { 12 | command = 0; 13 | _spi = &spi; 14 | _ss = ss; 15 | } 16 | 17 | void PN532_SPI::begin() 18 | { 19 | pinMode(_ss, OUTPUT); 20 | 21 | _spi->begin(); 22 | _spi->setDataMode(SPI_MODE0); // PN532 only supports mode0 23 | _spi->setBitOrder(LSBFIRST); 24 | #ifndef __SAM3X8E__ 25 | _spi->setClockDivider(SPI_CLOCK_DIV8); // set clock 2MHz(max: 5MHz) 26 | #else 27 | /** DUE spi library does not support SPI_CLOCK_DIV8 macro */ 28 | _spi->setClockDivider(42); // set clock 2MHz(max: 5MHz) 29 | #endif 30 | 31 | } 32 | 33 | void PN532_SPI::wakeup() 34 | { 35 | digitalWrite(_ss, LOW); 36 | delay(2); 37 | digitalWrite(_ss, HIGH); 38 | } 39 | 40 | 41 | 42 | int8_t PN532_SPI::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 43 | { 44 | command = header[0]; 45 | writeFrame(header, hlen, body, blen); 46 | 47 | uint8_t timeout = PN532_ACK_WAIT_TIME; 48 | while (!isReady()) { 49 | delay(1); 50 | timeout--; 51 | if (0 == timeout) { 52 | DMSG("Time out when waiting for ACK\n"); 53 | return -2; 54 | } 55 | } 56 | if (readAckFrame()) { 57 | DMSG("Invalid ACK\n"); 58 | return PN532_INVALID_ACK; 59 | } 60 | return 0; 61 | } 62 | 63 | int16_t PN532_SPI::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) 64 | { 65 | uint16_t time = 0; 66 | while (!isReady()) { 67 | delay(1); 68 | time++; 69 | if (timeout > 0 && time > timeout) { 70 | return PN532_TIMEOUT; 71 | } 72 | } 73 | 74 | digitalWrite(_ss, LOW); 75 | delay(1); 76 | 77 | int16_t result; 78 | do { 79 | write(DATA_READ); 80 | 81 | if (0x00 != read() || // PREAMBLE 82 | 0x00 != read() || // STARTCODE1 83 | 0xFF != read() // STARTCODE2 84 | ) { 85 | 86 | result = PN532_INVALID_FRAME; 87 | break; 88 | } 89 | 90 | uint8_t length = read(); 91 | if (0 != (uint8_t)(length + read())) { // checksum of length 92 | result = PN532_INVALID_FRAME; 93 | break; 94 | } 95 | 96 | uint8_t cmd = command + 1; // response command 97 | if (PN532_PN532TOHOST != read() || (cmd) != read()) { 98 | result = PN532_INVALID_FRAME; 99 | break; 100 | } 101 | 102 | DMSG("read: "); 103 | DMSG_HEX(cmd); 104 | 105 | length -= 2; 106 | if (length > len) { 107 | for (uint8_t i = 0; i < length; i++) { 108 | DMSG_HEX(read()); // dump message 109 | } 110 | DMSG("\nNot enough space\n"); 111 | read(); 112 | read(); 113 | result = PN532_NO_SPACE; // not enough space 114 | break; 115 | } 116 | 117 | uint8_t sum = PN532_PN532TOHOST + cmd; 118 | for (uint8_t i = 0; i < length; i++) { 119 | buf[i] = read(); 120 | sum += buf[i]; 121 | 122 | DMSG_HEX(buf[i]); 123 | } 124 | DMSG('\n'); 125 | 126 | uint8_t checksum = read(); 127 | if (0 != (uint8_t)(sum + checksum)) { 128 | DMSG("checksum is not ok\n"); 129 | result = PN532_INVALID_FRAME; 130 | break; 131 | } 132 | read(); // POSTAMBLE 133 | 134 | result = length; 135 | } while (0); 136 | 137 | digitalWrite(_ss, HIGH); 138 | 139 | return result; 140 | } 141 | 142 | boolean PN532_SPI::isReady() 143 | { 144 | digitalWrite(_ss, LOW); 145 | 146 | write(STATUS_READ); 147 | uint8_t status = read() & 1; 148 | digitalWrite(_ss, HIGH); 149 | return status; 150 | } 151 | 152 | void PN532_SPI::writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 153 | { 154 | digitalWrite(_ss, LOW); 155 | delay(2); // wake up PN532 156 | 157 | write(DATA_WRITE); 158 | write(PN532_PREAMBLE); 159 | write(PN532_STARTCODE1); 160 | write(PN532_STARTCODE2); 161 | 162 | uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA 163 | write(length); 164 | write(~length + 1); // checksum of length 165 | 166 | write(PN532_HOSTTOPN532); 167 | uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA 168 | 169 | DMSG("write: "); 170 | 171 | for (uint8_t i = 0; i < hlen; i++) { 172 | write(header[i]); 173 | sum += header[i]; 174 | 175 | DMSG_HEX(header[i]); 176 | } 177 | for (uint8_t i = 0; i < blen; i++) { 178 | write(body[i]); 179 | sum += body[i]; 180 | 181 | DMSG_HEX(body[i]); 182 | } 183 | 184 | uint8_t checksum = ~sum + 1; // checksum of TFI + DATA 185 | write(checksum); 186 | write(PN532_POSTAMBLE); 187 | 188 | digitalWrite(_ss, HIGH); 189 | 190 | DMSG('\n'); 191 | } 192 | 193 | int8_t PN532_SPI::readAckFrame() 194 | { 195 | const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0}; 196 | 197 | uint8_t ackBuf[sizeof(PN532_ACK)]; 198 | 199 | digitalWrite(_ss, LOW); 200 | delay(1); 201 | write(DATA_READ); 202 | 203 | for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) { 204 | ackBuf[i] = read(); 205 | } 206 | 207 | digitalWrite(_ss, HIGH); 208 | 209 | return memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)); 210 | } 211 | -------------------------------------------------------------------------------- /PN532_SPI/PN532_SPI.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __PN532_SPI_H__ 3 | #define __PN532_SPI_H__ 4 | 5 | #include 6 | #include "PN532Interface.h" 7 | 8 | class PN532_SPI : public PN532Interface { 9 | public: 10 | PN532_SPI(SPIClass &spi, uint8_t ss); 11 | 12 | void begin(); 13 | void wakeup(); 14 | int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 15 | 16 | int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); 17 | 18 | private: 19 | SPIClass* _spi; 20 | uint8_t _ss; 21 | uint8_t command; 22 | 23 | boolean isReady(); 24 | void writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 25 | int8_t readAckFrame(); 26 | 27 | inline void write(uint8_t data) { 28 | _spi->transfer(data); 29 | }; 30 | 31 | inline uint8_t read() { 32 | return _spi->transfer(0); 33 | }; 34 | }; 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /PN532_SWHSU/PN532_SWHSU.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include "PN532_SWHSU.h" 3 | #include "PN532_debug.h" 4 | 5 | 6 | PN532_SWHSU::PN532_SWHSU(SoftwareSerial &serial) 7 | { 8 | _serial = &serial; 9 | command = 0; 10 | } 11 | 12 | void PN532_SWHSU::begin() 13 | { 14 | _serial->begin(115200); 15 | } 16 | 17 | void PN532_SWHSU::wakeup() 18 | { 19 | _serial->write(0x55); 20 | _serial->write(0x55); 21 | _serial->write((uint8_t) 0); 22 | _serial->write((uint8_t) 0); 23 | _serial->write((uint8_t) 0); 24 | 25 | /** dump serial buffer */ 26 | if(_serial->available()){ 27 | DMSG("Dump serial buffer: "); 28 | } 29 | while(_serial->available()){ 30 | uint8_t ret = _serial->read(); 31 | DMSG_HEX(ret); 32 | } 33 | 34 | } 35 | 36 | int8_t PN532_SWHSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) 37 | { 38 | 39 | /** dump serial buffer */ 40 | if(_serial->available()){ 41 | DMSG("Dump serial buffer: "); 42 | } 43 | while(_serial->available()){ 44 | uint8_t ret = _serial->read(); 45 | DMSG_HEX(ret); 46 | } 47 | 48 | command = header[0]; 49 | 50 | _serial->write((uint8_t) PN532_PREAMBLE); 51 | _serial->write((uint8_t) PN532_STARTCODE1); 52 | _serial->write((uint8_t) PN532_STARTCODE2); 53 | 54 | uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA 55 | _serial->write(length); 56 | _serial->write(~length + 1); // checksum of length 57 | 58 | _serial->write((uint8_t) PN532_HOSTTOPN532); 59 | uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA 60 | 61 | DMSG("\nWrite: "); 62 | 63 | _serial->write(header, hlen); 64 | for (uint8_t i = 0; i < hlen; i++) { 65 | sum += header[i]; 66 | 67 | DMSG_HEX(header[i]); 68 | } 69 | 70 | _serial->write(body, blen); 71 | for (uint8_t i = 0; i < blen; i++) { 72 | sum += body[i]; 73 | 74 | DMSG_HEX(body[i]); 75 | } 76 | 77 | uint8_t checksum = ~sum + 1; // checksum of TFI + DATA 78 | _serial->write(checksum); 79 | _serial->write((uint8_t) PN532_POSTAMBLE); 80 | 81 | return readAckFrame(); 82 | } 83 | 84 | int16_t PN532_SWHSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) 85 | { 86 | uint8_t tmp[3]; 87 | 88 | DMSG("\nRead: "); 89 | 90 | /** Frame Preamble and Start Code */ 91 | if(receive(tmp, 3, timeout)<=0){ 92 | return PN532_TIMEOUT; 93 | } 94 | if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){ 95 | DMSG("Preamble error"); 96 | return PN532_INVALID_FRAME; 97 | } 98 | 99 | /** receive length and check */ 100 | uint8_t length[2]; 101 | if(receive(length, 2, timeout) <= 0){ 102 | return PN532_TIMEOUT; 103 | } 104 | if( 0 != (uint8_t)(length[0] + length[1]) ){ 105 | DMSG("Length error"); 106 | return PN532_INVALID_FRAME; 107 | } 108 | length[0] -= 2; 109 | if( length[0] > len){ 110 | return PN532_NO_SPACE; 111 | } 112 | 113 | /** receive command byte */ 114 | uint8_t cmd = command + 1; // response command 115 | if(receive(tmp, 2, timeout) <= 0){ 116 | return PN532_TIMEOUT; 117 | } 118 | if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){ 119 | DMSG("Command error"); 120 | return PN532_INVALID_FRAME; 121 | } 122 | 123 | if(receive(buf, length[0], timeout) != length[0]){ 124 | return PN532_TIMEOUT; 125 | } 126 | uint8_t sum = PN532_PN532TOHOST + cmd; 127 | for(uint8_t i=0; i return value buffer. 165 | len --> length expect to receive. 166 | timeout --> time of reveiving 167 | @retval number of received bytes, 0 means no data received. 168 | */ 169 | int8_t PN532_SWHSU::receive(uint8_t *buf, int len, uint16_t timeout) 170 | { 171 | int read_bytes = 0; 172 | int ret; 173 | unsigned long start_millis; 174 | 175 | while (read_bytes < len) { 176 | start_millis = millis(); 177 | do { 178 | ret = _serial->read(); 179 | if (ret >= 0) { 180 | break; 181 | } 182 | } while((timeout == 0) || ((millis()- start_millis ) < timeout)); 183 | 184 | if (ret < 0) { 185 | if(read_bytes){ 186 | return read_bytes; 187 | }else{ 188 | return PN532_TIMEOUT; 189 | } 190 | } 191 | buf[read_bytes] = (uint8_t)ret; 192 | DMSG_HEX(ret); 193 | read_bytes++; 194 | } 195 | return read_bytes; 196 | } 197 | -------------------------------------------------------------------------------- /PN532_SWHSU/PN532_SWHSU.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef __PN532_SWHSU_H__ 3 | #define __PN532_SWHSU_H__ 4 | 5 | #include 6 | 7 | #include "PN532Interface.h" 8 | #include "Arduino.h" 9 | 10 | #define PN532_SWHSU_DEBUG 11 | 12 | #define PN532_SWHSU_READ_TIMEOUT (1000) 13 | 14 | class PN532_SWHSU : public PN532Interface { 15 | public: 16 | PN532_SWHSU(SoftwareSerial &serial); 17 | 18 | void begin(); 19 | void wakeup(); 20 | virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0); 21 | int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout); 22 | 23 | private: 24 | SoftwareSerial* _serial; 25 | uint8_t command; 26 | 27 | int8_t readAckFrame(); 28 | 29 | int8_t receive(uint8_t *buf, int len, uint16_t timeout=PN532_SWHSU_READ_TIMEOUT); 30 | }; 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## NFC library for Arduino 2 | 3 | This is an Arduino library for PN532 to use NFC technology. It's based on 4 | [Adafruit_NFCShield_I2C](http://goo.gl/pk3FdB) 5 | , improved by [Seeed Studio](http://goo.gl/zh1iQh), added HSU(High Speed Uart) driver by [Elechouse](http://elechouse.com). 6 | 7 | It works with: 8 | 9 | + [Elechouse NFC Module](http://goo.gl/i0EQgd) 10 | + [Seeed Studio NFC Shield](http://goo.gl/Cac2OH) 11 | + [Xadow NFC](http://goo.gl/qBZMt0) 12 | + [Adafruit PN532 NFC/RFID controller breakout board](http://goo.gl/tby9Sw) 13 | 14 | ### Features 15 | + Support all interfaces of PN532 (I2C, SPI, HSU ) 16 | + Read/write Mifare Classic Card 17 | + Works with [Don's NDEF Library](http://goo.gl/jDjsXl) 18 | + Support Peer to Peer communication(exchange data with android 4.0+) 19 | + Support [mbed platform](http://goo.gl/kGPovZ) 20 | 21 | ### Getting Started 22 | 1. **Download [zip file](https://github.com/elechouse/PN532/archive/PN532_HSU.zip) and 23 | extract the three folders(PN532, PN532_SPI, PN532_HSU and PN532_I2C) into libraries of Arduino.** 24 | 2. Downlaod [Don's NDEF library](http://goo.gl/ewxeAe) and extract it into libraries of Arduino's into a new folder called "NDEF" (Note if you leave this folder as NDEF-Master Arduino will not be able to use it as a library) 25 | 2. Follow the examples of the PN532 library 26 | 27 | ### To do 28 | + Card emulation 29 | 30 | ## HSU Interface 31 | 32 | HSU is short for High Speed Uart. HSU interface needs only 4 wires to connect PN532 with Arduino, [Sensor Shield](http://goo.gl/i0EQgd) can make it more easier. For some Arduino boards like [Leonardo][Leonardo], [DUE][DUE], [Mega][Mega] ect, there are more than one `Serial` on these boards, so we can use this additional Serial to control PN532, HSU uses 115200 baud rate . 33 | 34 | To use the `Serial1` control PN532, refer to the code below. 35 | 36 | #include 37 | #include 38 | 39 | PN532_HSU pn532hsu(Serial1); 40 | PN532 nfc(pn532hsu); 41 | 42 | void setup(void) 43 | { 44 | nfc.begin(); 45 | //... 46 | } 47 | 48 | If your Arduino has only one serial interface and you want to keep it for control or debugging with the Serial Monitor, you can use the [`SoftwareSerial`][SoftwareSerial] library to control the PN532 by emulating a serial interface. Include `PN532_SWHSU.h` instead of `PN532_HSU.h`: 49 | 50 | #include 51 | #include 52 | #include 53 | 54 | SoftwareSerial SWSerial( 10, 11 ); // RX, TX 55 | 56 | PN532_SWHSU pn532swhsu( SWSerial ); 57 | PN532 nfc( pn532swhsu ); 58 | 59 | void setup(void) 60 | { 61 | nfc.begin(); 62 | //... 63 | } 64 | 65 | [Mega]: http://arduino.cc/en/Main/arduinoBoardMega 66 | [DUE]: http://arduino.cc/en/Main/arduinoBoardDue 67 | [Leonardo]: http://arduino.cc/en/Main/arduinoBoardLeonardo 68 | [SoftwareSerial]: https://www.arduino.cc/en/Reference/softwareSerial 69 | 70 | --------------------------------------------------------------------------------