- Introduction to nfc
- Getting started with pn532: arduino guide
- Hardware configurations
- Hardware configurations:
- Interfacing pn532 nfc rfid module with arduino — electropeak
- Looking for a pn532 nfc shield instead? not to worry, we provide just that!
- Main applications of nfc
- Nfc-пульт
- Particle photon grove nfc grove lcd via i2c
- Passive nfc device example: nfc display
- Pn532 nfc rfid wireless module v3 — купите pn532 nfc rfid wireless module v3 с бесплатной доставкой на алиэкспресс version
- Pn532 nfc купить по низкой цене на aliexpress
- Second tutorial: play with seeeduino v4.2 (i2c)
- Software configurations
- Software configurations:
- Summary
- Types of nfc devices
- Waveshare pn532 nfc hat on raspberry pi 4
- What do you need?
- What is nfc
- What is pn532
- Комплектация
- Контакты подключения антенны
- Микросхема pn532
- Подключение
- Подробнее о модуле
- Пример программы для arduino
- Пример программы для iskrajs
- Примеры работы
- Схема подключения
- Технология nfc
- Технология rfid
- Технология rfid/nfc
- Характеристики
Introduction to nfc
Before understanding PN532 as a whole, let’s dive deeper into what NFC is truly about and how does it work?
Getting started with pn532: arduino guide
Before we begin with the Arduino Guide, do consider if you need interface changes into I2C. If needed, you should cut the UART connection and solder the I2C pins as below:
Considered the above? Let’s get started now!
This guide will utilize the Seeed Arduino NFC library, which supports:
- Arduino Uno/Seeeduino v4.2
- Arduino Mega/Seeeduino Mega
- Arduino Zero/Seeeduino Lorawan
- Arduino Leonardo/Seeeduino Lite
*Seeeduino is Seeed’s very own Arduino, built with benefits over the regular Arduino boards
Hardware configurations
- Step 1: Connect Grove – NFC to port UART of Grove-Base Shield
- Step 2: Plug Grove – Base Shield into Seeeduino Lite
- Step 3: Connect Seeeduino Lite to PC via a USB cable
Hardware configurations:
- Step 1. Connect Grove – NFC to port I2C of Grove-Base Shield. Please make sure you follow hardware overview to change the default UART setting to I2C.
- Step 2. Plug Grove – Base Shield into Seeeduino V4.2.
- Step 3. Connect Seeeduino V4.2 to PC via a USB cable
Interfacing pn532 nfc rfid module with arduino — electropeak
As mentioned above, this module supports HSU, SPI and I2C communication protocols. The module uses separate pins for SPI protocol, but the pins used for I2C and HSU communication protocols are the same. The names of the I2C pins are on the front of the module and the names of the HSU pins are on the back of the module. HSU is the default protocol of the module. You can change the communication protocol of the module to one of the I2C, SPI or HSU using DIP switches on the module.
This Module has 16 pins. The pins of each protocol are as follows:
I2C protocol:
- VCC: Module power supply – 5V
- GND: Ground
- SDA: Data pin
- SCL: Clock pin
SPI protocol:
- VCC: Module power supply – 3-5V
- GND: Ground
- SCK: Clock pin
- MISO: Output data pin
- MOSI: Input data pin
- SS: Slave select
- IRQ: Interrupt pin
- RSTO: Reset pin
HSU protocol:
- VCC: Module power supply – 5V
- GND: Ground
- TXD: Transmit data pin
- RXD: Receive data pin
You can see the pinout of this module in the image below.
Looking for a pn532 nfc shield instead? not to worry, we provide just that!
Built around the PN532 module, this NFC shield allows for a 5cm max effective range, with support for SPI interface, allowing you to stack it on your Arduino boards!
Key Features include:
- 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
Note: This NFC shield can be used for Raspberry Pi as well, but you’ll need to modify the library
Interested in finding out more on the NFC Shield? You can head to its product page to find out more!
This is an NFC HAT based on PN532 operating in the 13.56MHz frequency range that not only supports Raspberry Pi with its GPIO pins, it easily works on host boards like STM32 and Arduino as well!
Its features include:
- Standard Raspberry Pi 40PIN GPIO extension header, supports Raspberry Pi series boards
- Onboard PN532 chip, supports various NFC/RFID cards like MIFARE/NTAG2xx, etc.
- Three interface options: I2C, SPI, and UART, configured via jumpers and switches
- Breakout control pins, for easily connecting with host boards like STM32/Arduino
- Comes with development resources and manual (examples for Raspberry Python/C, STM32, Arduino)
Interested in finding out more on the NFC Shield? You can head to its product page to find out more!
Main applications of nfc
- Mobile payments; Apple Pay NFC, Google Wallet
- Tap-to-Pair; Pairing Bluetooth devices just by tapping, instead of manual entering
- Embedding digital experience in physical products; NFC’s small form factor allows for it to be embedded into physical products, enabling a unique experience when interacted
- Security
- Password replacement
- Product Authentication
Want to find out more about the differences between NFC and RFID? Check out this article!
Nfc-пульт
Попробуем управлять тремя светодиодами с помощью RFID/NFC-сканера, каждому светодиоду будет соответствовать своя карта. При поднесении известной карты будет переключаться светодиод. Для удобства контроля работы будем отправлять в Serial-порт название считанной карты.
Particle photon grove nfc grove lcd via i2c
With most of the tutorials on Photon and NFC using SPI and RC522 Modules, this tutorial helps you read out the UID of an NFC card!
What do you need?
Hardware components
Interested? Check out the full tutorial by An Tran on hackster.io!
Passive nfc device example: nfc display
To further understand passive NFC devices, let’s take a look at this 4.2inch NFC screen that’s powered without battery or cables!
How is it powered then?
As mention in the earlier comparison, passive NFC devices connect to active ones, and this screen is no exception. As long as you have a smartphone with NFC function, you can use it to control this screen and transmit images to it!
No battery, no cables, no trouble, just passive NFC technology by swiping like a credit card!
Interested to find out more about it? You can head to our product page!
Pn532 nfc rfid wireless module v3 — купите pn532 nfc rfid wireless module v3 с бесплатной доставкой на алиэкспресс version
Перед покупкой сравните цены на pn532 nfc rfid wireless module v3, прочитайте реальные отзывы покупателей, ознакомьтесь с техническими характеристиками.
Закажите pn532 nfc rfid wireless module v3 онлайн с доставкой по России: товары с пометкой Plus доступны с ускоренной доставкой и улучшенными условиями возврата.
На Алиэкспресс pn532 nfc rfid wireless module v3 всегда в наличии в большом ассортименте: на площадке представлены как надежные мировые бренды, так и перспективные молодые.
Pn532 nfc купить по низкой цене на aliexpress
pn532 nfc хорошего качества и по доступной цене? Мы знаем, где искать! На AliExpress можно найти всё по ключевым словам, например, pn532 nfc — вы получите выгодные предложения и сможете сэкономить. Вот краткое руководство о том, как найти самые низкие цены и качественные товары.
Используйте фильтры. На AliExpress есть широкий выбор самых разнообразных товаров. Чтобы найти товар pn532 nfc по вашим параметрам, настройте фильтры и отсортируйте всё по соответствующим результатам, количеству заказов или цене. Вы также можете выбрать фильтры с бесплатной доставкой, быстрой доставкой или бесплатным возвратом.
Изучайте бренды. pn532 nfc от надёжных и известных брендов, которые вам нравятся — просто нажмите логотип бренда на левой боковой панели. Это поможет вам отфильтровать результаты поиска.
Читайте отзывы. Посмотрите, нравится ли pn532 nfc другим покупателям. Читайте реальные отзывы о товаре — вы найдёте много полезной информации, а также советы и подсказки для удобного шопинга.
Так будет проще найти pn532 nfc по выгодной цене и воспользоваться быстрой доставкой или бесплатным возвратом товара. А новых пользователей ждут спецпредложения и подарки! Заходите на сайт AliExpress, чтобы найти и купить ещё больше товаров из категории.»
Second tutorial: play with seeeduino v4.2 (i2c)
You can connect the PN532 with Seeduino V4.2, an Arduino Uno alternative
Note: Do choose 13.5MHz, ISO14443 NFC Tags, if not the Grove-NFC module may not read the tag
For this demo, it works without the base shield since the Seeeduino V4.2 has an onboard Grove I2C connector
Let’s get started!
Software configurations
- Step 1: Download Seeed Arduino NFC Library
- Step 2: Refer to How to install library to install Seeed Arduino NFC library for Arduino
- Step 3: Download PN532 Library and put it under C:Program Files (x86)ArduinolibrariesSeeed_Arduino_NFC-mastersrc.
- Step 4: Open “ReadTag” code via the path:
- File → Examples → ReadTag.
- Step 5: Modify the code as below to enable UART communication
#if 0 // use SPI
#include <SPI.h>
#include <PN532/PN532_SPI/PN532_SPI.h>
PN532_SPI pn532spi(SPI, 9);
NfcAdapter nfc = NfcAdapter(pn532spi);
#elif 1 // use hardware serial
#include <PN532/PN532_HSU/PN532_HSU.h>
PN532_HSU pn532hsu(Serial1);
NfcAdapter nfc(pn532hsu);
#elif 0 // use software serial
#include <PN532/PN532_SWHSU/PN532_SWHSU.h>
#include "SoftwareSerial.h"
SoftwareSerial SWSerial(2, 3);
PN532_SWHSU pn532swhsu(SWSerial);
NfcAdapter nfc(pn532swhsu);
#else //use I2C
#include <Wire.h>
#include <PN532/PN532_I2C/PN532_I2C.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif- Step 7: Upload the code. If you’re unsure on how to do so, please check How to upload the code
- Step 8: Open the Serial Monitor of Arduino IDE by clicking Tool-> Serial Monitor. Or tap the Ctrl Shift M key at the same time. Set the Baud Rate at 9600
- Step 9: Use the Grove – NFC to get close to an NFC Tag. If everything goes well, you will get the NFC Tage Information in the Serial Monitor.
Note:
For connection to Arduino Mega UART ports, you can change the PN532_HSU pn532hsu (Serial 1) to PN532_HSU pn532hsu (Serial X)
For the connection of Grove-NFC sensors to Arduino Uno, you can use the software serial. Do follow below to configure software serial.
#if 0 // use SPI
#include <SPI.h>
#include <PN532/PN532_SPI/PN532_SPI.h>
PN532_SPI pn532spi(SPI, 9);
NfcAdapter nfc = NfcAdapter(pn532spi);
#elif 0 // use hardware serial
#include <PN532/PN532_HSU/PN532_HSU.h>
PN532_HSU pn532hsu(Serial1);
NfcAdapter nfc(pn532hsu);
#elif 1 // use software serial
#include <PN532/PN532_SWHSU/PN532_SWHSU.h>
#include "SoftwareSerial.h"
SoftwareSerial SWSerial(2, 3);
PN532_SWHSU pn532swhsu(SWSerial);
NfcAdapter nfc(pn532swhsu);
#else //use I2C
#include <Wire.h>
#include <PN532/PN532_I2C/PN532_I2C.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endifSoftware configurations:
#if 0 // use SPI
#include <SPI.h>
#include <PN532/PN532_SPI/PN532_SPI.h>
PN532_SPI pn532spi(SPI, 9);
NfcAdapter nfc = NfcAdapter(pn532spi);
#elif 0 // use hardware serial
#include <PN532/PN532_HSU/PN532_HSU.h>
PN532_HSU pn532hsu(Serial1);
NfcAdapter nfc(pn532hsu);
#elif 0 // use software serial
#include <PN532/PN532_SWHSU/PN532_SWHSU.h>
#include "SoftwareSerial.h"
SoftwareSerial SWSerial(2, 3);
PN532_SWHSU pn532swhsu(SWSerial);
NfcAdapter nfc(pn532swhsu);
#else //use I2C
#include <Wire.h>
#include <PN532/PN532_I2C/PN532_I2C.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif- Step 6: Upload the code. If you’re unsure on how, please check How to upload code
- Step 7: Open the Serial Monitor of Arduino IDE by click Tool-> Serial Monitor. Or tap the Ctrl Shift M key at the same time. Set the baud rate 9600
- Step 8: Use the Grove – NFC to get close to an NFC Tag. If everything goes well, you will get the NFC Tag information in the Serial Monitor
Summary
That’s all for today’s blog. I hope you learnt more about NFC and PN532.
Overall, with the rise of NFC technology in recent years and the countless possibilities for using NFC and RFID, start building your own project ideas today!
Do consider the products covered in today’s blog to help you get started:
Types of nfc devices
There are two types of NFC devices; Active NFC, Passive NFC:
Waveshare pn532 nfc hat on raspberry pi 4
I bought myself the Waveshare PN532 NFC HAT and mounted it to my Raspberry Pi 4 Model B.
I followed the official guide on how to install the hard- and software.
Now I’ve tried to run some of the example scripts given, but I got an error.
Running the example_get_uid.py script worked perfectly fine.
Running the example_rw_mifare.py script threw this error:
pi@raspberrypi:~/raspberrypi/python $ python3 example_rw_mifare.py Found PN532 with firmware version: 1.6 Waiting for RFID/NFC card to write to! ...Found card with UID: ['0x1', '0x23', '0x45', '0x67'] Traceback (most recent call last): File "example_rw_mifare.py", line 57, in uid, block_number=block_number, key_number=nfc.MIFARE_CMD_AUTH_A, key=key_a) File "/home/pi/raspberrypi/python/pn532/pn532.py", line 395, in mifare_classic_authenticate_block if response[0]: TypeError: 'NoneType' object is not subscriptable
So it looks like there’s an error in the given pn532 library.
Is there anyone who had this error before and knows how to fix it?
Thanks already for your answers.
EDIT:
example_rw_mifare.py
""" This example shows connecting to the PN532 and writing an M1 type RFID tag Warning: DO NOT write the blocks of 4N 3 (3, 7, 11, ..., 63) or else you will change the password for blocks 4N ~ 4N 2. Note: 1. The first 6 bytes (KEY A) of the 4N 3 blocks are always shown as 0x00, since 'KEY A' is unreadable. In contrast, the last 6 bytes (KEY B) of the 4N 3 blocks are readable. 2. Block 0 is unwritable. """ import RPi.GPIO as GPIO import pn532.pn532 as nfc from pn532 import * pn532 = PN532_SPI(debug=False, reset=20, cs=4) #pn532 = PN532_I2C(debug=False, reset=20, req=16) #pn532 = PN532_UART(debug=False, reset=20) ic, ver, rev, support = pn532.get_firmware_version() print('Found PN532 with firmware version: {0}.{1}'.format(ver, rev)) # Configure PN532 to communicate with MiFare cards pn532.SAM_configuration() print('Waiting for RFID/NFC card to write to!') while True: # Check if a card is available to read uid = pn532.read_passive_target(timeout=0.5) print('.', end="") # Try again if no card is available. if uid is not None: break print('Found card with UID:', [hex(i) for i in uid]) """ Warning: DO NOT write the blocks of 4N 3 (3, 7, 11, ..., 63) or else you will change the password for blocks 4N ~ 4N 2. Note: 1. The first 6 bytes (KEY A) of the 4N 3 blocks are always shown as 0x00, since 'KEY A' is unreadable. In contrast, the last 6 bytes (KEY B) of the 4N 3 blocks are readable. 2. Block 0 is unwritable. """ # Write block #6 block_number = 6 key_a = b'xFFxFFxFFxFFxFFxFF' data = bytes([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]) try: pn532.mifare_classic_authenticate_block(uid, block_number=block_number, key_number=nfc.MIFARE_CMD_AUTH_A, key=key_a) pn532.mifare_classic_write_block(block_number, data) if pn532.mifare_classic_read_block(block_number) == data: print('write block %d successfully' % block_number) except nfc.PN532Error as e: print(e.errmsg) GPIO.cleanup()and this is the code part in pn532.py
def mifare_classic_authenticate_block(self, uid, block_number, ey_number, key): # pylint: disable=invalid-name """Authenticate specified block number for a MiFare classic card. Uid should be a byte array with the UID of the card, block number should be the block to authenticate, key number should be the key type (like MIFARE_CMD_AUTH_A or MIFARE_CMD_AUTH_B), and key should be a byte array with the key data. Returns True if the block was authenticated, or False if not authenticated. """ # Build parameters for InDataExchange command to authenticate MiFare card. uidlen = len(uid) keylen = len(key) params = bytearray(3 uidlen keylen) params[0] = 0x01 # Max card numbers params[1] = key_number & 0xFF params[2] = block_number & 0xFF params[3:3 keylen] = key params[3 keylen:] = uid # Send InDataExchange request and verify response is 0x00. response = self.call_function(_COMMAND_INDATAEXCHANGE, params=params, response_length=1) if response[0]: raise PN532Error(response[0]) return response[0] == 0x00
What do you need?
Note: Do prepare NFC Tags yourself
What is nfc
NFC, in short for Near Field Communications is a technology standard based on Radio Frequency Identification (RFID), transmitting information wirelessly over short distances. Think of it as an authentication-free Bluetooth!

Packed like a sticker, NFC tags may seem unimpressive but what goes into it made applications possible in places where other technologies couldn’t.
What is pn532
Now that we’ve understood more about NFC and its applications, I’ll quickly introduce PN532 before moving on to an integrated module.
Комплектация
- 1x Модуль RFID-модуль PN532;
- 1x Метка брелок;
- 1x Метка карточка;
- 1x Штыревой соединитель;
Контакты подключения антенны
Модуль приёмник и антенна соединяются трёхпроводным шлейфом. Полярность подключения не имеет значения.
Микросхема pn532
PN532 — это микросхема трансивера для бесконтактной передачи данных на частоте 13,56 МГц. Ядро схемы – микроконтроллер 80C51. Микросхема взаимодействует с управляющей электроникой по протоколу I2C.
Подключение
Для удобства подключения к Arduino воспользуйтесь Trema Shield, Trema Power Shield, Motor Shield или Trema Set Shield.
Модуль поддерживает работу по нескольким интерфейсам. для того, чтобы подключить модуль по шине I2C, измените положение переключателя согласно таблице возле него.
Подключение по I2C:
- SDA — к выводу A4;
- SCL — к выводу A5;
- VCC — 5V;
- GND — GND;
- IRQ — к цифровому выводу 2;
- RSTO — к цифровому выводу 3;
Подключение по SPI:
- SS — 10;
- MOSI — 11;
- MISO — 12;
- SCK — 13;
- VCC — 5V;
- GND — GND;
Подробнее о модуле
Для более удобной работы с модулем предлагаем вам воспользоваться библиотекой Adafruit_PN532.
Пример программы для arduino
Перед загрузкой кода, ранее считанные значения ID Value перенесём в программу, массивы uidFirstCard, uidSecondCard и uidThirdCard предназначены для хранения ID Карт.
- nfc_rfid_three_led_arduino.ino
#include <Wire.h>#include <SPI.h> // библиотека для работы с RFID/NFC#include <Adafruit_PN532.h> // пин прерывания#define PN532_IRQ 9 // создаём объект для работы со сканером и передаём ему два параметра// первый — номер пина прерывания// вторым — число 100// от Adafruit был программный сброс шилда// в cканере RFID/NFC 13,56 МГц (Troyka-модуль) этот пин не используется// поэтому передаём цифру, большая чем любой пин ArduinoAdafruit_PN532 nfc(PN532_IRQ,100); // пины к которым подключены светодиоды Troyka_led#define LED_FIRST A0#define LED_SECOND A1#define LED_THIRD A2 // Массивы в которые необходимо записать ID карт:uint8_t uidFirstCard[]={0x04,0x40,0xA9,0xDA,0xA3,0x40,0x80};uint8_t uidSecondCard[]={0x04,0xAB,0xB4,0xDA,0xA3,0x40,0x80};uint8_t uidThirdCard[]={0x04,0x71,0xC1,0xDA,0xA3,0x40,0x81}; // функция которая сравнивает два переданных ID// при совпадении возвращает значение true// и значение false если ID разныеboolean comparisonOfUid(uint8_t uidRead[8],uint8_t uidComp[8],uint8_t uidLen){for(uint8_t i =0; i < uidLen; i ){if(uidRead[i]!= uidComp[i]){returnfalse;}if(i ==(uidLen)-0x01){returntrue;}}} // функция переключающая светодиод, получает входные параметры:// номер светодиода ledvoid toggleLed(int led){if(digitalRead(led)== LOW){ digitalWrite(led, HIGH);}else{ digitalWrite(led, LOW);}} void setup(void){// инициализация пинов Led pinMode(LED_FIRST, OUTPUT); pinMode(LED_SECOND, OUTPUT); pinMode(LED_THIRD, OUTPUT); // инициализация Serial - порта Serial.begin(9600);// инициализация RFID/NFC сканера nfc.begin();int versiondata = nfc.getFirmwareVersion();if(!versiondata){while(1){ Serial.print("Didn't find RFID/NFC reader"); delay(1000);}} Serial.println("Found RFID/NFC reader");// настраиваем модуль nfc.SAMConfig(); Serial.println("Waiting for a card ...");} void loop(void){uint8_t success;// буфер для хранения ID картыuint8_t uid[8];// размер буфера картыuint8_t uidLength;// слушаем новые метки success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid,&uidLength);// если найдена картаif(success){// Переключаем первый светодиод если функция сравнения// ID вернёт true иначе оставляем всё как естьif(comparisonOfUid(uid, uidFirstCard, uidLength)){ toggleLed(LED_FIRST); Serial.println("FirstTAG");}else{// Переключаем второй светодиод если функция сравнения// ID вернёт true иначе оставляем всё как естьif(comparisonOfUid(uid, uidSecondCard, uidLength)){ toggleLed(LED_SECOND); Serial.println("SecondTAG");}else{// Переключаем третий светодиод если функция сравнения// ID вернёт true иначе оставляем всё как естьif(comparisonOfUid(uid, uidThirdCard, uidLength)){ toggleLed(LED_THIRD); Serial.println("ThirdTAG");}else{ Serial.println("NoTAG");}}} delay(1000);}}
Пример программы для iskrajs
Повторим те же операции, что и для Arduino. Перед загрузкой кода, ранее считанные значения uid перенесём в программу, массивы uidFirstCard, uidSecondCard и uidThirdCard предназначены для хранения ID Карт.
- nfc_rfid_three_led_iskrajs.js
// настраиваем I2C1 для работы модуляI2C1.setup({sda: SDA, scl: SCL, bitrate:400000}); // подключаем модуль к I2C1 и пину прерыванияvar nfc = require('@amperka/nfc').connect({i2c: I2C1, irqPin: P9});// подключаем 3 светодиодаvar ledFirst = require('@amperka/led').connect(A0);var ledSecond = require('@amperka/led').connect(A1);var ledThird = require('@amperka/led').connect(A2); // ID-карт, при поднисенни которых буду переключаться светодиоды.// считываем их примером из console:const uidFirstCard =[4,113,193,218,163,64,129];const uidSecondCard =[4,64,169,218,163,64,128];const uidThirdCard =[4,171,180,218,163,64,128]; // активируем модульnfc.wakeUp(function(error){if(error){ print('wake up error', error);}else{ print('wake up OK');// слушаем новые метки nfc.listen();}}); nfc.on('tag',function(error, data){if(error){ print('tag read error');}else{// выводим в консоль полученные данные print(data.uid);// переводим массив-байт в строку для удобства сравнения// вызываем функцию-обработчик метки factoryLedLight(data.uid);}// каждые 1000 миллисекунд слушаем новую метку setTimeout(function(){ nfc.listen();},1000);}); // функция-обработчик, сравнивает массивы и при совпадении возвращает truefunction comparisonOfUid(uid, card){// переменная хранящая длину массиваvar leng = uid.length;// цикл поэлементно проверяет равенство значенийfor(var i =0; i < leng; i ){// сравнение элементов между собойif(uid[i]!= card[i]){// если элементы не равны прекращаем работу функции и возвращаем falsereturnfalse;}// если все элементы массива равны возвращаем trueif( i == uid.length-1){returntrue;}}} // функция сравнивает ID текущей метки с ID меток в константах// при совпадении переключает светодиодfunction factoryLedLight(id){if(comparisonOfUid(id, uidFirstCard)){ console.log('FirstTAG'); ledFirst.toggle();}else{if(comparisonOfUid(id, uidSecondCard)){ console.log('SecondTAG'); ledSecond.toggle();}else{if(comparisonOfUid(id, uidThirdCard)){ console.log('ThirdTAG'); ledThird.toggle();}else{ console.log('NoTAG');}}}}
Примеры работы
Рассмотрим несколько примеров с работой NFC-сканера.
Схема подключения
К ранее собранной схеме добавим три светодиода Пиранья.

Технология nfc
NFC (англ. Near Field Communication, ближняя бесконтактная связь) — технология беспроводной передачи данных малого радиуса действия, которая дает возможность обмена данными между устройствами, находящимися на расстоянии до 10 сантиметров. NFC работает на частоте 13,56 МГц и является продолжением высокочастотного RFID стандарта.
Технология rfid
RFID (англ. Radio Frequency IDentification, радиочастотная идентификация) — система однонаправленной связи, в которой данные из метки передаются к бесконтактному считывателю. RFID метки могут быть отсканированы на расстоянии до 100 метров, причём метка может находиться вне прямой видимости ридера.
Технология rfid/nfc

Характеристики
- Микросхема: PN532
- Логика: КМОП, 3.3В
- Напряжение питания: 3.3-5В
- Максимальный потребляемый ток: 150 мА
- Потребляемый ток в режиме ожидания: 100 мА
- Потребляемый ток в режиме считывания: 120 мА
- Потребляемый ток в режиме записи: 120 мА
- Дальность считывания: 5 — 7 см
- Антенна: встроенная, на плате
- Размеры: 42.7 х 40.4 мм
- Поддержка интерфейсов: I2C / SPI / HSU (High Speed UART — 115200 kbps);
- Поддерживаемые режимы работы:
- RFID (чтение/запись)
- P2P соединения
- NFC для работы со смартфонами на платформе Android
- Поддержка чипов:
- ISO 14443 Type A — NXP Mifare 1k, 4k, Ultralight, Desfire
- ISO 14443 Type B
- ISO/IEC 14443-4-совместимые чипы
- FeliCa
- Jewel
- TopaZ





