NFC Shield V2.0

Aus Aptofun WIKI
Version vom 29. Mai 2019, 22:54 Uhr von Shuo (Diskussion | Beiträge) (Introduction)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu: Navigation, Suche

AptoFun NFC/RFID Reader/Writer PN532 für Arduino/Development Boards Module V 2.0

Introduction

NFC (Near Field Communication) is a technology that is widely used. Some of NFC's applications include wireless access control systems (e.g. keyless doors, and locks), and mobile device payments (e.g. store registers that receive payment information via a phone application).

The NFC Shield features a transceiver module, PN532, which handles wireless communication at 13.56MHz, this means that you can read and write a 13.56MHz tag with this shield or implement point to point (P2P) data exchange between the shield and a smart phone.

For this new version of the shield we have created a separate, independent, PCB antenna area which allows you to more easily stretch the NFC interface outside of your main circuit enclosure.

Feature

  • Use of the ICSP header for SPI. This means that the shield works with the following Arduino development boards: Uno, Mega, Leonardo
  • Wireless NFC communication at 13.56MHz
  • SPI protocol - pin saving interface that requires only 4 pins
  • Input Voltage: 5V from the Arduino's 5V pin
  • Typical Current: 100mA
  • 5cm max effective range
  • Supports P2P communication
  • Support ISO14443 Type A and Type B protocols

Specification

Nfc1.jpg

NFC shield interface

  • D10 and D9 are used for SPI chip select (CS/SS). D10 is connected by default, to connect D9 soldering the SS pad to the D9 pad and scraping off the connection between SS and D10 is required.
  • D2 can be used to receive the shield's interrupt request (IRQ) pin signal. The interrupt is not connect by default, soldering of the "D2/INT0" and "IRQ" pads is required.
  • The shield gets its SPI interface (SPI MOSI, MISO, and SCK pins) from the Arduino's ICSP header directly, this means that the shield works the following Arduinos: Uno, Mega, and Leonardo.
  • The ANT1 terminal is where the NFC antenna (included with the shield) is connected to.
  • The shield is powered by 5V from the Arduino board.

The NFC shield's antenna, included with the shield, is a separate PCB module that is attached to the shield via a cable. The antenna is the area used to receive and transmit information.

Nfc2.jpg

Nfc3.pngNFC antenna PCB attachment

Hardware Installation

  1. Attach the NFC Antenna to the shield.
  2. Stack the NFC Shield on your Arduino development board and connect the board to a PC using a USB cable.

Software Libraries Installation

Close the Arduino IDE if you have it open.

  1. Download the PN532 library ZIP folder and extract the files.
  2. Copy the folders PN532, PN532_HSU, PN532_SPI, and PN532_I2C into the Arduino "libraries" folder.
  3. Download Don's NDEF library ZIP folder and extract the files.
  4. Open the extracted folder and rename the "NDEF-master" folder to "NDEF".
  5. Copy the "NDEF" folder to the Arduino "libraries" folder.
  6. Restart the Arduino IDE. You should now be able to see "NDEF" and "PN532" as options in the Arduino "Examples" sub-menu (See figure below).

Nfc4.png Arduino available libraries menu

NFC Shield Examples/Applications

Example #1: NFC Tag Scan

This example will show you how to use the NFC shield to scan an NFC tag and display its information/data.

In the Arduino IDE copy, paste, then upload the code below to your board.

 1     #include <SPI.h>
 2     #include "PN532_SPI.h"
 3     #include "PN532.h"
 4     #include "NfcAdapter.h"
 5 
 6     PN532_SPI interface(SPI, 10); // create a PN532 SPI interface with the SPI CS terminal located at digital pin 10
 7     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
 8 
 9     void setup(void) {
10         Serial.begin(115200); // begin serial communication
11         Serial.println("NDEF Reader");
12         nfc.begin(); // begin NFC communication
13     }
14 
15     void loop(void) {
16 
17         Serial.println("\nScan an NFC tag\n");
18         if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
19         {
20             NfcTag tag = nfc.read(); // read the NFC tag into an object, nfc.read() returns an NfcTag object.
21             tag.print(); // prints the NFC tags type, UID, and NDEF message (if available)
22         }
23         delay(500); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
24     }

To test the code:

  1. Open the Arduino Serial monitor window
  2. Set the baudrate to 115200
  3. Hold an NFC tag over the NFC antenna area
  4. The NFC shield will scan the tag and you should be able to see the NFC tag’s UID, tag type, and message (if available) in the serial monitor window. See the figure below.

Nfc5.png Example #1 serial communication window output when scanning an NFC tag.

Example #2: NFC(keyless) Door Lock

This example will show you how to use an NFC tag as a key to unlock a door or a lock. The door/lock mechanism will be left to your imagination, we'll only cover the NFC part of the code.

  1. Do Example #1: NFC Tag Scan, above, to get your NFC tag's UID.
  2. Optional Step - connect a green LED to pin 3 as shown in the figure/schematic below. We'll use this LED to signal a successful match in keys.
  3. ptional Step – connect a red LED to pin 4 as shown in the figure/schematic below. We'll use this LED to signal a mismatched key.
    Nfc6.pngNFC lock circuit
  4. In the Arduino IDE create a new sketch and copy, paste, and upload the code below to your Arduino board replacing the myUID string constant with your tag’s UID obtained from Example
    Nfc7.jpg
 1     #include <SPI.h>
 2     #include "PN532_SPI.h"
 3     #include "PN532.h"
 4     #include "NfcAdapter.h"
 5 
 6     String const myUID = "1B B3 C6 EF"; // replace this UID with your NFC tag's UID
 7     int const greenLedPin = 3; // green led used for correct key notification
 8     int const redLedPin = 4; // red led used for incorrect key notification
 9 
10     PN532_SPI interface(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
11     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
12 
13     void setup(void) {
14         Serial.begin(115200); // start serial comm
15         Serial.println("NDEF Reader");
16         nfc.begin(); // begin NFC comm
17 
18         // make LED pins outputs
19         pinMode(greenLedPin,OUTPUT);
20         pinMode(redLedPin,OUTPUT);
21 
22         // turn off the LEDs
23         digitalWrite(greenLedPin,LOW);
24         digitalWrite(redLedPin,LOW);
25     }
26 
27     void loop(void) {
28 
29         Serial.println("Scanning...");
30         if (nfc.tagPresent()) // check if an NFC tag is present on the antenna area
31         {
32             NfcTag tag = nfc.read(); // read the NFC tag
33             String scannedUID = tag.getUidString(); // get the NFC tag's UID
34 
35             if( myUID.compareTo(scannedUID) == 0) // compare the NFC tag's UID with the correct tag's UID (a match exists when compareTo returns 0)
36             {
37               // The correct NFC tag was used
38               Serial.println("Correct Key");
39               // Blink the green LED and make sure the RED led is off
40               digitalWrite(greenLedPin,HIGH);
41               digitalWrite(redLedPin,LOW);
42 
43               delay(500);
44               digitalWrite(greenLedPin,LOW);
45               delay(500);
46               digitalWrite(greenLedPin,HIGH);
47               delay(500);
48               digitalWrite(greenLedPin,LOW);
49               // put your here to trigger the unlocking mechanism (e.g. motor, transducer)
50             }else{
51               // an incorrect NFC tag was used
52               Serial.println("Incorrect key");
53               // blink the red LED and make sure the green LED is off
54               digitalWrite(greenLedPin,LOW);
55               digitalWrite(redLedPin,HIGH);
56 
57               delay(500);
58               digitalWrite(redLedPin,LOW);
59               delay(500);
60               digitalWrite(redLedPin,HIGH);
61               delay(500);
62               digitalWrite(redLedPin,LOW);
63               // DO NOT UNLOCK! an incorrect NFC tag was used.
64               // put your code here to trigger an alarm (e.g. buzzard, speaker) or do something else
65             }
66         }
67         delay(2000);
68     }

To test the code/application:

  1. Open the Arduino's serial monitor window
  2. Hold the NFC tag with the correct key on the antenna area.
  3. The green LED should light up and the serial window should print "Correct Key"
  4. Now hold a different NFC on the antenna area
  5. The red LED should light up and the serial window should print "Incorrect Key"

Example #3: How to use the Interrupt Pin (Example #2: Revisited)

Although the code in Example #2 above does what we need there is a more elegant approach to handling NFC tag detections. In this example we'll show you how to make use of the interrupt pin in the NFC shield so that instead of polling the shield (asking "is there a tag present?") we wait for the shield to tell the Arduino that a tag is available to be read. Why would you want to do this? There are many reasons and interrupts are a whole different topic, but one reason that may convince you is that your project/circuit will save battery since we are not triggering the shield circuit continuously.

Hardware Modification

The NFC shield’s interrupt pin (IRQ) is disconnect from the Arduino's digital pin 2 (D2), to connect the IRQ and D2 pin together go ahead and solder the pad on the shield labeled "D2/INT0 IRQ".

Code

Upload the following code to your Arduino board:

  1     #include <SPI.h>
  2     #include "PN532_SPI.h"
  3     #include "PN532.h"
  4     #include "NfcAdapter.h"
  5 
  6     // FLAG_NONE used to signal nothing needs to be done
  7     #define FLAG_NONE 0
  8     // FLAG_IRQ_TRIGGERED used to signal an interrupt trigger
  9     #define FLAG_IRQ_TRIGGERED 1
 10     // FLAG_RESET_IRQ used to signal that the interrupt needs to be reset
 11     #define FLAG_RESET_IRQ 2
 12     // flags variable used to store the present flag
 13     volatile int flags = FLAG_NONE;
 14 
 15     String const myUID = "1B B3 C6 EF"; // replace this UID with your NFC tag's UID
 16     // LED pins
 17     int const greenLedPin = 3; // green led used for correct key notification
 18     int const redLedPin = 4; // red led used for incorrect key notification
 19 
 20     // the interrupt we'll be using (interrupt 0) is located at digital pin 2
 21     int const irqPin = 2; // interrupt pin
 22 
 23     PN532_SPI interface(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
 24 
 25     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
 26 
 27     String scannedUID = ""; // this is where we'll store the scanned tag's UID
 28 
 29     void setup(void) {
 30         // make LED pins outputs
 31         pinMode(greenLedPin,OUTPUT);
 32         pinMode(redLedPin,OUTPUT);
 33 
 34         Serial.begin(115200); // start serial comm
 35         Serial.println("NDEF Reader");
 36         nfc.begin(); // begin NFC comm
 37 
 38         // turn off the LEDs
 39         digitalWrite(greenLedPin,LOW);
 40         digitalWrite(redLedPin,LOW);
 41        // attach the function "irq" to interrupt 0 on the falling edges
 42        attachInterrupt(0,irq,FALLING);// digital pin 2 is interrupt 0, we'll call the irq function (below) on the falling edge of this pin
 43     }
 44 
 45     void loop(void) {
 46         int flag = getFlag(); // get the present flag
 47 
 48         switch(flag) // check which flag/signal we are on
 49         {
 50            case FLAG_NONE:
 51              // nothing needs to be done
 52            break;
 53            case FLAG_IRQ_TRIGGERED: // the interrupt pin has been triggered
 54                Serial.println("Interrupt Triggered");
 55                if (nfc.tagPresent())
 56                {
 57                  // an NFC tag is present
 58                   NfcTag tag = nfc.read(); // read the NFC tag
 59                   scannedUID = tag.getUidString(); // get the NFC tag's UID
 60                   if(myUID.compareTo(scannedUID) == 0) // compare the NFC tag's UID with the correct tag's UID (a match exists when compareTo returns 0)
 61                   {
 62                     // the scanned NFC tag matches the saved myUID value
 63                     Serial.println("Correct tag/key");
 64                     blinkLed(greenLedPin,200,4); // blink the green led
 65                     // put your here to trigger the unlocking mechanism (e.g. motor, transducer)
 66                   }else{
 67                     // the scanned NFC tag's UDI does not match the myUID value
 68                     Serial.println("Incorrect tag/key");
 69                     blinkLed(redLedPin,200,4); // blink the red led
 70                     // DO NOT UNLOCK! an incorrect NFC tag was used.
 71                     // put your code here to trigger an alarm (e.g. buzzard, speaker) or do something else
 72                   }
 73                   // return to the original state
 74                   setFlag(FLAG_NONE);
 75                   reset_PN532_IRQ_pin();
 76                }else{
 77                  // a tag was not present (the IRQ was triggered by some other action)
 78                  setFlag(FLAG_NONE);
 79                }
 80            break;
 81            default:
 82              // do any other stuff for flags not handled above
 83            break;
 84         }
 85     }
 86 
 87     /*
 88     * Name: setFlat
 89     * Description: used to set actions/flags to be executed in the loop(void) function
 90     * Parameters:
 91     *        int flag - the action/flag to store
 92     * Returns: void
 93     */
 94     void setFlag(int flag)
 95     {
 96       flags = flag;
 97     }
 98 
 99     /*
100     * Name: getFlag
101     * Description: used to get the present flag/action
102     * Parameters: void
103     * Returns: int - the flags variable. The action/flag set by setFlag
104     */
105     int getFlag()
106     {
107       return flags;
108     }
109 
110     /*
111     * Name: irq
112     * Description: Interrupt service routine (ISR). This function will be executed whenever there is a falling edge on digital pin 2 (the interrupt 0 pin)
113     * Parameters: void
114     * Returns: void
115     */
116     void irq()
117     {
118       if(getFlag()==FLAG_NONE){
119         setFlag(FLAG_IRQ_TRIGGERED);
120       }
121     }
122     /*
123     * Name: reset_PN532_IRQ_pin
124     * Description: used to reset the PN532 interrupt request (IRQ) pin
125     * Parameters: void
126     * Returns: void
127     */
128     void reset_PN532_IRQ_pin()
129     {
130       nfc.tagPresent();
131     }
132 
133     /*
134     * Name: blinkLed
135     * Description: used to toggle a pin to blink an LED attached to the pin
136     * Parameters:
137     *      ledPin - the pin where the led is connected to
138     *      delayTime - the time in milliseconds between HIGH and LOW
139     *      times - the number of times to toggle the pin
140     * Returns: void
141     */
142     void blinkLed(int ledPin,int delayTime,int times)
143     {
144       for(int i=0;i<times;i++){
145         digitalWrite(ledPin,HIGH);
146         delay(delayTime);
147         digitalWrite(ledPin,LOW);
148         delay(delayTime);
149       }
150     }

To test the code/application:

  1. If desired, connect the LEDs as shown in Example #2 above.
  2. Open the Arduino's serial monitor window
  3. Hold the NFC tag with the correct key on the antenna area.
  4. The green LED should light up and the serial window should print "Correct Key"
  5. Now hold a different NFC on the antenna area
  6. The red LED should light up and the serial window should print "Incorrect Key"

The serial window from our test of this code is displayed below, yours should be similar.

Nfc8.png Serial comm window output from example 3.

Example #4: Write an NDEF Message to a Tag

NFC tags are capable of storing data, the amount of data is dependent on each tag. In this example we will store two strings/messages on a tag, you will then be able to read this message with the code in Example #6: Read an NDEF Message From a Tag. Upload the following code to your Arduino development board.

Note

If your NFC tag is not properly formatted ("Message write failed" will be displayed in the serial comm window) you'll need to see if you tag can be formatted with the code in Example #5: Format a Tag as NDEF Code

 1     #include <SPI.h>
 2     #include "PN532_SPI.h"
 3     #include "PN532.h"
 4     #include "NfcAdapter.h"
 5 
 6     PN532_SPI interface(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
 7 
 8     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
 9 
10     void setup(void)
11     {
12         Serial.begin(115200); // start serial comm
13         Serial.println("NDEF Reader");
14         nfc.begin(); // begin NFC comm
15     }
16 
17     void loop(void)
18     {
19       Serial.println("Place a formatted Mifare Classic NFC tag on the reader.");
20       if(nfc.tagPresent())
21       {
22         NdefMessage message = NdefMessage();
23         message.addUriRecord("Hello, world!");
24         message.addUriRecord("How are you today?");
25 
26         bool success = nfc.write(message);
27         if(success)
28         {
29           Serial.println("The message was successfully written to the tag.");Ho
30         }else{
31           Serial.println("Message write failed.");
32         }
33       }
34 
35       delay(5000);
36     }

To test the code above:

  1. Open an Arduino serial comm window
  2. Hold the NFC tag over the NFC shield antenna's area and wait for the success or failure message to appear as shown in the figure below.
  3. Remove the NFC tag form the antenna's area as soon as the success message is displayed to prevent a rewrite.

Nfc9.pngSerial comm window for NDEF message written to card example.

Example #5: Format a Tag as NDEF

Your brand new NFC tag might not be NDEF formatted initially. To format a tag as NDEF upload the following code to your Arduino development board: Code

 1     #include <SPI.h>
 2     #include "PN532_SPI.h"
 3     #include "PN532.h"
 4     #include "NfcAdapter.h"
 5 
 6     PN532_SPI interface(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
 7 
 8     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
 9 
10     void setup(void)
11     {
12         Serial.begin(115200); // start serial comm
13         Serial.println("NDEF Reader");
14         nfc.begin(); // begin NFC comm
15     }
16 
17     void loop(void)
18     {
19         Serial.println("Place an unformatted Mifare Classic tag on the reader.");
20         if (nfc.tagPresent()) {
21 
22             bool success = nfc.format();
23             if (success) {
24               Serial.println("Success, tag formatted as NDEF.");
25             } else {
26               Serial.println("Format failed.");
27             }
28 
29         }
30         delay(5000);
31     }

To test/run the code:

  1. Open the Arduino serial comm window.
  2. Hold the NFC tag you wish to format over the NFC shield antenna's area.
  3. Wait for the success or fail message to appear as shown in the figure below.
  4. Remove the NFC tag from the antenna's area to prevent a re-format.

Note

If your tag failed to get formatted, try again. If it fails your tag is not capable of getting formatted as NDEF.

Nfc10.pngSerial comm window output when formatting an NFC tag to NDEF.

Example #6: Read an NDEF Message From a Tag

As you have seen in the example's above, the NFC shield is capable of writing messages to NFC tags. The NFC is also capable of reading NDEF messages from tags, in this example we'll show you how.

Code

Upload the following code to your Arduino development board.

 1     #include <SPI.h>
 2     #include "PN532_SPI.h"
 3     #include "PN532.h"
 4     #include "NfcAdapter.h"
 5 
 6     PN532_SPI interface(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
 7 
 8     NfcAdapter nfc = NfcAdapter(interface); // create an NFC adapter object
 9 
10     void setup(void)
11     {
12         Serial.begin(115200); // start serial comm
13         Serial.println("NDEF Reader");
14         nfc.begin(); // begin NFC comm
15     }
16 
17     void loop(void)
18     {
19       Serial.println("\nScan an NFC tag\n");
20       if (nfc.tagPresent()) // Do an NFC scan to see if an NFC tag is present
21       {
22           NfcTag tag = nfc.read(); // read the NFC tag
23           if(tag.hasNdefMessage())
24           {
25             NdefMessage message = tag.getNdefMessage();
26             for(int i=0;i<message.getRecordCount();i++)
27             {
28               NdefRecord record = message.getRecord(i);
29               int payloadLength = record.getPayloadLength();
30               byte payload[payloadLength];
31               record.getPayload(payload);
32               Serial.write(payload,payloadLength);
33             }
34           }
35       }
36       delay(500); // wait half a second (500ms) before scanning again (you may increment or decrement the wait time)
37     }

To test code above:

  1. Open an Arduino serial comm window
  2. Hold the an NFC tag with an NDEF message over the NFC shield antenna's area.
  3. The NDEF message written on the tag should be displayed as shown in the figure below.

Nfc11.pngSerial comm window output for NDEF message read

Example #7: How to Change the Chip Select Pin From D10 to D9

Hardware Modification

  1. Scrape off the connection from the pads labeled "SS" and "D10" on the shield
  2. Connect/solder pads "SS" and "D9" on the shield.

You can then use the same code in the examples above but with pin 9 instead of 10 for the PN532 interface:

Code

PN532_SPI interface(SPI, 9); // create a SPI interface for the shield with the SPI CS terminal at digital pin 9

Example #8: Use Two NFC Shields With One Arduino Board

Hardware Modification

  1. Do the hardware modification described in Example #7 on one of the two shields.
  2. Stack both shields on the Arduino Board.

You may now create two separate NFC objects, one for each shield, as follows: Code

1     PN532_SPI interface_shield_1(SPI, 10); // create a SPI interface for the shield with the SPI CS terminal at digital pin 10
2     PN532_SPI interface_shield_2(SPI, 9); // create a SPI interface for the shield with the SPI CS terminal at digital pin 9
3 
4     NfcAdapter nfc_shield_1 = NfcAdapter(interface_shield_1); // create an NFC adapter object for shield one
5     NfcAdapter nfc_shield_2 = NfcAdapter(interface_shield_2); // create an NFC adapter object for shield two