jerryshi
Posts: 2
Joined: Tue May 13, 2014 2:18 am
Location: China
Contact: Website

Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Sat Jun 07, 2014 2:30 am

ITEAD PN532 NFC module is equipped with double-row pins, which can be connected directly to the Raspberry Pie via connection cable and then drive the module for non-contact near field communication operations, such as reading and writing 13.56M IC card. You can buy this module from here: http://imall.iteadstudio.com/im130625002.html

libnfc is the first libre low level NFC SDK and Programmers API released under the GNU Lesser General Public License. It provides complete transparency and royalty-free use for everyone. The library currently supports modulations for ISO/IEC 14443 A and B, FeliCa, Jewel/Topaz tags and Data Exchange Protocol (P2P) as target and as initiator. For more information, you can refer to http://nfc-tools.org/

The following tutorial demonstrates how to use libnfc on Raspberry Pi to drive ITEAD PN532 module with the SPI bus.

1, Hardware connection

As Itead PN532 Module is customized for Raspberry Pi, it can be connected directly to Raspberry Pi via the adapter cable as shown in picture below
Image

According to the connection in the picture above, Itead PN532 Module is connected via the SPI bus with raspberry pie, therefore, operating mode of PN532 Module should be set to SPI mode, as shown below:

Code: Select all

SET0-->L
SET1-->H
Image

2, Install the software pack needed

Code: Select all

sudo apt-get update
sudo apt-get install libusb-dev libpcsclite-dev
3, Download and compress source code pack of libnfc

Code: Select all

cd ~
wget http://dl.bintray.com/nfc-tools/sources/libnfc-1.7.1.tar.bz2
tar -xf libnfc-1.7.1.tar.bz2  
4, Compile and install

Code: Select all

cd libnfc-1.7.1
./configure --prefix=/usr --sysconfdir=/etc
make
sudo make install 
5, Modify configuration file

Code: Select all

cd /etc
sudo mkdir nfc
sudo nano /etc/nfc/libnfc.conf
Copy and paste the following contents to file /etc/nfc/libnfc.conf:

Code: Select all

# Allow device auto-detection (default: true)
# Note: if this auto-detection is disabled, user has to set manually a device
# configuration using file or environment variable
allow_autoscan = true

# Allow intrusive auto-detection (default: false)
# Warning: intrusive auto-detection can seriously disturb other devices
# This option is not recommended, user should prefer to add manually his device.
allow_intrusive_scan = false

# Set log level (default: error)
# Valid log levels are (in order of verbosity): 0 (none), 1 (error), 2 (info), 3 (debug)
# Note: if you compiled with --enable-debug option, the default log level is "debug"
log_level = 1

# Manually set default device (no default)
# To set a default device, you must set both name and connstring for your device
# Note: if autoscan is enabled, default device will be the first device available in device list.
device.name = "Itead_PN532_SPI"
device.connstring = "pn532_spi:/dev/spidev0.0:500000"
6, As Raspberry Pi defaults to disable the driver for SPI module, we need to enable it

Code: Select all

sudo nano /etc/modprobe.d/raspi-blacklist.conf
Add # in front of blacklist spi-bcm2708 and it will become #blacklist spi-bcm2708
As shown in the picture below
Image

You can see two spi devices under /dev after rebooting.
Image

7, Up to now, preparations are done. And then we can use command nfc-list to check if it is successfully installed.
Image

Let's try swiping the card.
Image

8, Configurations for connection via I2C bus

8.1 Software configuration
Enable I2C bus on Raspberry Pi, and change blacklist i2c-bcm2708 in /etc/modprobe.d/raspi-blacklist.conf to #blacklist i2c-bcm2708

Add i2c-dev at the end of /etc/modules

Modify last line of /etc/nfc/libnfc.conf to pn532_i2c:/dev/i2c-1 as shown in the picture below
Image

8.2 Hardware connection

Connection is as shown in the picture below:
Image

Running result is as shown in the picture below:
Image

Appendix: related links
A1. libnfc configuration method: http://nfc-tools.org/index.php?title=Li ... figuration
A2. libnfc installation tutorial: http://nfc-tools.org/index.php?title=Libnfc
A3. libnfc user API: http://nfc-tools.org/index.php?title=Libnfc:API
A4. libnfc main page: http://nfc-tools.org/index.php?title=Main_Page
A5. libnfc tutorial: http://nfc-tools.org/index.php?title=Ca ... c:Examples
A6. Iteadstudio PN532 Module website: http://imall.iteadstudio.com/im130625002.html
A7. Disable R-Pi/RASPBIAN serial console for using UART0: http://learn.adafruit.com/adafruit-nfc- ... -on-the-pi

Note: this post is reprinted from http://blog.iteadstudio.com/raspberry-p ... th-libnfc/

iyosch
Posts: 19
Joined: Tue Jun 09, 2015 6:40 am
Location: Jakarta, Indonesia

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Wed Jul 22, 2015 7:15 am

thank you for your post about this wonderful tutorial about nfc. I now able to read UID from mifare classic 1k nfc tag using this libnfc. But I wonder, how can we read the ndef message or even read the data block inside the nfc tag? I write my tag using my android phone, it should consist some data on it. But the libnfc using nfc-poll only shows UID.

I tried to modify the quick_start_example1.c but i haven't succeeded yet to read data block. Do you know how?
this is my modified code

Code: Select all

/**
 * @file quick_start_example1.c
 * @brief Quick start example that presents how to use libnfc
 */
 
/**
 * this code is edited from quick_start_example1
 * this code doesnt work.
 */

// To compile this simple example:
// $ gcc -o quick_start_example1 quick_start_example1.c -lnfc

#include <stdlib.h>
#include </home/pi/libnfc-1.7.1/include/nfc/nfc.h> //located on libnfc-1.7.1/include/nfc/nfc.h
#include <string.h>
//#include <nfc/nfc-types.h> //located on libnfc-1.7.1/include/nfc/nfc-types.h
#include </home/pi/libnfc-1.7.1/utils/mifare.h>

static mifare_param mp; //addition
nfc_target_info nti; //declare nfc_target_info as nti for ease of use
nfc_device *pnd;



//declaring keys 6x8 = 48 bit
static uint8_t keys[] = {
        0xff,0xff,0xff,0xff,0xff,0xff,
        0xd3,0xf7,0xd3,0xf7,0xd3,0xf7,
        0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,
        0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,
        0x4d,0x3a,0x99,0xc3,0x51,0xdd,
        0x1a,0x98,0x2c,0x7e,0x45,0x9a,
        0xaa,0xbb,0xcc,0xdd,0xee,0xff,
        0x00,0x00,0x00,0x00,0x00,0x00
};


//function to authenticate
static bool
authenticate(int block, int keynum, bool keyB) {
        memcpy(mp.mpa.abtAuthUid,nti.nai.abtUid,4);
        memcpy(mp.mpa.abtKey, &keys[keynum], 6);
        
        bool res = nfc_initiator_mifare_cmd(pnd, (keyB ? MC_AUTH_B : MC_AUTH_A), block, &mp);
        if (res) {
                printf("Authentication succcessful on block %d\n",block);
        } else {
                printf("Authentication failed on block %d\n",block);
        }
        return res;
}


//function to readblock
void readblocks(int start, int end) {
        int block;
        for (block=start; block<(end+1); block++) {
                bool res = nfc_initiator_mifare_cmd(pnd, MC_READ, block, &mp);
                if (res) {
                        printf("Block %d data: ",block);
                        //print_hex(mp.mpd.abtData,16);
                } else {
                        printf("Reading block %d failed\n",block);
                }
        }
}


//function print_hex to show data on terminal
static void print_hex(const uint8_t *pbtData, const size_t szBytes)
{
  size_t  szPos;

  for (szPos = 0; szPos < szBytes; szPos++) {
    printf("%02x  ", pbtData[szPos]);
  }
  printf("\n");
}

//function main
int
main(int argc, const char *argv[])
{
  //nfc_device *pnd; //this initialization is moved to the top of the file
  nfc_target nt;
  
  // Allocate only a pointer to nfc_context
  nfc_context *context;

  // Initialize libnfc and set the nfc_context
  nfc_init(&context);
  if (context == NULL) {
    printf("Unable to init libnfc (malloc)\n");
    exit(EXIT_FAILURE);
  }

  // Display libnfc version
  const char *acLibnfcVersion = nfc_version();
  (void)argc;
  printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);

  // Open, using the first available NFC device which can be in order of selection:
  //   - default device specified using environment variable or
  //   - first specified device in libnfc.conf (/etc/nfc) or
  //   - first specified device in device-configuration directory (/etc/nfc/devices.d) or
  //   - first auto-detected (if feature is not disabled in libnfc.conf) device
  pnd = nfc_open(context, NULL);

  if (pnd == NULL) {
    printf("ERROR: %s\n", "Unable to open NFC device.");
    exit(EXIT_FAILURE);
  }
  // Set opened NFC device to initiator mode
  if (nfc_initiator_init(pnd) < 0) {
    nfc_perror(pnd, "nfc_initiator_init");
    exit(EXIT_FAILURE);
  }

  printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));

  // Poll for a ISO14443A (MIFARE) tag
  const nfc_modulation nmMifare = {
    .nmt = NMT_ISO14443A,
    .nbr = NBR_106,
  };
  if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
    printf("The following (NFC) ISO14443A tag was found:\n");
    printf("    ATQA (SENS_RES): ");
    print_hex(nt.nti.nai.abtAtqa, 2);
    printf("       UID (NFCID%c): ", (nt.nti.nai.abtUid[0] == 0x08 ? '3' : '1'));
    print_hex(nt.nti.nai.abtUid, nt.nti.nai.szUidLen);
    printf("      SAK (SEL_RES): ");
    print_hex(&nt.nti.nai.btSak, 1);
    if (nt.nti.nai.szAtsLen) {
      printf("          ATS (ATR): ");
      print_hex(nt.nti.nai.abtAts, nt.nti.nai.szAtsLen);
    }
    
    //try to read blocks
        } else {
                goto DISCONNECT;
        }
        // Try to login to sector 0. Use the default key FFFF, for key A
        bool authenticated = authenticate(3,0,false);
        
        if (!authenticated) {
                goto DISCONNECT;
        }
        
        readblocks(0,3); //read block 0 untill 3 (4 blocks)
        
        DISCONNECT: 
        // Disconnect from NFC device
        nfc_disconnect(pnd);
        return EXIT_SUCCESS;
        
    
    //compare the UID from nt.nti.nai.abtUid with stored UID
    const uint8_t winner[] = { 0x9e, 0x74, 0x03, 0x0a};
        if (memcmp(nt.nti.nai.abtUid, winner, 4) == 0) {
            printf("UID matched\n");
        }
    //nt.nti.nai.abtUid
    //nt = nfc_target
    //nti = nfc_target info
    //nai =  nfc_iso14443a_info nai <- all this is set on nfc-types.h
    //abtUid = UID of the nfc tag
        
    //template of memcmp 
    //int memcmp(const void *str1, const void *str2, size_t n)
    
    //try to read the data block
    //template to read data block
    //uint8_t mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data);
    
    //print the ats
    printf("         Test ATS : ");
    print_hex(nt.nti.nai.abtAts, 254);
    
    //print dep info
    printf("         DEP abtNFCID3 : ");
    print_hex(nt.nti.ndi.abtNFCID3 , 11);    

    
  // Close NFC device
  nfc_close(pnd);
  // Release the context
  nfc_exit(context);
  exit(EXIT_SUCCESS);
}



ziggyeye
Posts: 5
Joined: Thu Jul 23, 2015 9:24 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Jul 23, 2015 9:31 am

I'm not having much luck getting this to work.
I have Raspberry Pi 2 and ITEAD PN532.
libnfc is installed properly. I wired it for i2c. I followed all the instructions for i2c above.
But for some reason, it is still not detected properly.
i2cdetect -y 1 seems to return all addesses.
I am able to clear it by ./pintest from wiringPi. But after rebooting, it returns all the addresses again.
If anyone can help, I would much appreciate it.
Thanks.

sudo i2cdetect -y 1
0 1 2 3 4 5 6 7 8 9 a b c d e f
00: 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
10: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
20: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
30: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
40: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
50: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
60: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
70: 70 71 72 73 74 75 76 77

Code: Select all

sudo nfc-scan-device -v
debug	libnfc.general	log_level is set to 3
debug	libnfc.general	allow_autoscan is set to true
debug	libnfc.general	allow_intrusive_scan is set to false
debug	libnfc.general	1 device(s) defined by user
debug	libnfc.general	  #0 name: "Itead_PN532", connstring: "pn532_i2c:/dev/i2c-1"
nfc-scan-device uses libnfc 1.7.1
debug	libnfc.general	0 device(s) found using acr122_usb driver
debug	libnfc.general	0 device(s) found using pn53x_usb driver
1 NFC device(s) found:
debug	libnfc.chip.pn53x	Diagnose
debug	libnfc.chip.pn53x	Timeout value: 500
debug	libnfc.chip.pn53x	SAMConfiguration
debug	libnfc.chip.pn53x	Timeout value: 1000
debug	libnfc.bus.i2c	TX: 00 00 ff 03 fd d4 14 01 17 00 
debug	libnfc.bus.i2c	wrote 10 bytes successfully.
debug	libnfc.driver.pn532_i2c	timeout reached with no READY frame.
pn53x_check_communication: Timeout
debug	libnfc.chip.pn53x	InRelease
debug	libnfc.bus.i2c	TX: 00 00 ff 03 fd d4 52 00 da 00 
debug	libnfc.bus.i2c	wrote 10 bytes successfully.
pdebug	libnfc.driver.pn532_i2c	timeout reached with no READY frame.
debug	libnfc.general	Unable to open "pn532_i2c:/dev/i2c-1".
nfc_open failed for pn532_i2c:/dev/i2c-1

User avatar
DougieLawson
Posts: 35364
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Jul 23, 2015 10:19 pm

Have you got SDA & SCL swapped?
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

ziggyeye
Posts: 5
Joined: Thu Jul 23, 2015 9:24 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Jul 23, 2015 11:10 pm

No. It shouldn't be swapped.
Image

I thought maybe I damaged the Pi, but I tried a different Pi with nothing plugged in and I still see all addresses in i2cdetect.

iyosch
Posts: 19
Joined: Tue Jun 09, 2015 6:40 am
Location: Jakarta, Indonesia

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Fri Jul 24, 2015 10:14 am

what happens when you type

Code: Select all

nfc-poll

on linuxterminal?

jctlmm
Posts: 11
Joined: Fri May 08, 2015 12:22 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Aug 13, 2015 5:58 am

Has anyone tried to use the ITEAD on the UART? I need some help... Thanks!

chaycv
Posts: 1
Joined: Fri Mar 11, 2016 4:08 pm

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Fri Mar 11, 2016 4:11 pm

jctlmm » I have tried with UART .. I have had some problems but at the final it worked nice...

spacek33z
Posts: 2
Joined: Wed May 25, 2016 5:57 pm

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Wed May 25, 2016 6:03 pm

chaycv wrote:jctlmm » I have tried with UART .. I have had some problems but at the final it worked nice...
What problems did you have? I'm trying with a RPi3 and UART. On some blogs I found that on the RPi3 you need to disable bluetooth by adding `dtoverlay=pi3-disable-bt` to /boot/config.txt and running `systemctl disable hciuart`.

After compiling libnfc, I tried to add this to /etc/nfc/libnfc.conf:

Code: Select all

device.name = "Itead_PN532_UART"
device.connstring = "pn532_uart:/dev/ttyAMA0"
This results in:

Code: Select all

error	libnfc.driver.pn532_uart	pn53x_check_communication error
nfc-list: ERROR: Unable to open NFC device: pn532_uart:/dev/ttyAMA0

jctlmm
Posts: 11
Joined: Fri May 08, 2015 12:22 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Wed May 25, 2016 10:16 pm

I did 2 things to make it work...

1) Freeing UART on the Pi:
Type: sudo raspi-config
Select “Advanced Options”
Select “Serial”
Select “No”
Select “Finish”
Select “Yes” (to reboot)

2) Setup libnfc for the Pi:
cd libnfc-libnfc-1.7.1
sudo mkdir /etc/nfc
sudo mkdir /etc/nfc/devices.d
sudo cp contrib/libnfc/pn532_uart_on_rpi.conf.sample /etc/nfc/devices.d/pn532_uart_on_rpi.conf
sudo nano /etc/nfc/devices.d/pn532_uart_on_rpi.conf
Add the following line at the end:
allow_intrusive_scan = true
Save and exit

I haven't tied RPi3...

rpsip
Posts: 2
Joined: Thu May 26, 2016 4:10 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu May 26, 2016 4:19 am

I'm having the exact same problem as spacek33z. I'm using the most recent version of libnfc as of yesterday, with the same ITEAD card, and the RPi 3. According to the debug dump at log level 3, it is a timeout issue. The transmissions to the ITEAD board seem to go fine, but libnfc is unable to read the ACK (probably doesn't receive one). It finally times out with unable to open NFC device.

The first transmission (55 55 00 00 ...) seems to be fine, maybe because it's a one way broadcast from the host. The second transmission (00 00 ff 03 fd ...) does not cause an ACK to be received. This transmission is attempted twice before the timeout.

rpsip
Posts: 2
Joined: Thu May 26, 2016 4:10 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Sat May 28, 2016 1:02 am

Resolved by disabling bluetooth:

Code: Select all

sudo systemctl disable hciuart

spacek33z
Posts: 2
Joined: Wed May 25, 2016 5:57 pm

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Sat May 28, 2016 1:40 pm

rpsip wrote:Resolved by disabling bluetooth:

Code: Select all

sudo systemctl disable hciuart
Nice! For me this didn't work unfortunately. Could you please show / tell me what pins you've connected?

I've connected them according this blogpost:
Connect Pin 2 (5V) on the Pi to the Pin marked 5V on the PN532
Connect Pin 6 (Ground) on the Pi to the Pin marked GND on the PN532
Connect Pin 8 (GPIO14) (UART TX) on the Pi to the Pin marked NSS/RCL/RX on the PN532
Connect Pin 10 (GPIO15) (UART RX) on the Pi to the Pin marked MO/SDA/TX on the PN532
... but maybe that's wrong. Also, the slide switches on the board are both set on L for SET0 and SET1. Do you also have that?

snoarf
Posts: 1
Joined: Thu Dec 22, 2016 4:05 pm

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Dec 22, 2016 4:10 pm

I did everything as listed above, (connected to spi, checked mode which was correct by default) but the spi devices do not show up.
I've got a PI 3B.

One thing was unexpected: the /etc/modprobe.d/raspi-blacklist.conf is existing, but empty.

Any idea how to debug?

thx, snoarf

Aztharos
Posts: 5
Joined: Thu Jun 01, 2017 10:07 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Thu Jun 08, 2017 8:50 am

Hi, If I realize this project, Can I use the nfc to login to raspbian ? (like NFC tag authentication) ? With PAM or something how is that possible

thank you

karlshea
Posts: 4
Joined: Sun Jun 18, 2017 6:19 am

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Sun Jun 18, 2017 6:22 am

I was having problems getting this board to work with a Pi 3, and although I could never get i2c and serial to work I was able to get it working with SPI. The frequency just needs to be turned down, so my connection string looks like this:

Code: Select all

pn532_spi:/dev/spidev0.0:280000

NavarroTec
Posts: 1
Joined: Sun May 12, 2019 6:25 pm

Re: Raspberry Pi Drives ITEAD PN532 NFC Module with libnfc

Sun May 12, 2019 6:32 pm

Hi there! I was having problems with the activation using spi and i2c communication.
When I wrote nfc-list , the console showed that no device was found.
After a search, I found the problem.
You have to go to cd /etc
and there you put the next code
sudo LIBNFC_LOG_LEVEL=3 nfc-scan-device -i -v
sudo nfc-list

and the pi recognizes your itead pn532 ;)
Sorry if don't explain a lot, I'm beginner in electronics stuff and english!
All good!

Return to “HATs and other add-ons”