I am trying to detect a RFID card using the NFC-PN532 module and Adafruit_PN532 library.
Initialization code:-
#include <Adafruit_PN532.h>
#include <Wire.h>
#define SCK (13)
#define MISO (12)
#define MOSI (11)
#define SS (10)
Adafruit_PN532 nfc(SCK, MISO, MOSI, SS);
void setup()
{
Serial.begin(9600);
Serial.println("Initializing please wait.......");
delay(3000);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata)
{
Serial.print("Didn't find PN53x board");
while (1); // halt
}
Serial.print("Device Found PN5 Chip");
Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware version > ");
Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.println((versiondata>>8) & 0xFF, DEC);
nfc.SAMConfig(); //Set to read RFID tags
Serial.println("Waiting for RFID Card ...");
}
Main loop:-
void loop()
{
uint8_t success = 0;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success)
{
Serial.println("Card Detected!");
}
else
{
Serial.println("Card Not Detected or Removed!");
}
}
Whenever i place a valid card on the PN532, Card Detected! is printed on the serial monitor.
However, when i remove the card, Card Not Detected or Removed! does not get printed.
How can i make the program to loop in such a way that it can detect when the card is present/removed?
1 Answer 1
The default behaviour of readPassiveTargetID
is to wait "forever" for a card - which is why your code only sees when there is a card present
So, in setup() add nfc.setPassiveActivationRetries(0x10);
as follows - comments came from my own code, but I'm sure they were originally in some example or other :p
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0x10);
// configure board to read RFID tags
nfc.SAMConfig();
As for "detecting" removal
void loop()
{
static bool wasSuccess = false;
uint8_t success = 0;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success)
{
wasSuccess = true;
Serial.println("Card Detected!");
}
else if (wasSuccess)
{
wasSuccess = false;
Serial.println("Card Removed!");
}
else
{
// you may want to remove this, it will flood the output :p
Serial.println("Card Not Detected!");
}
}
-
@Patrick - including the detection of remove? I ask, because I've been meaning to write some code for my PN532 :pJaromanda X– Jaromanda X2019年03月19日 13:29:54 +00:00Commented Mar 19, 2019 at 13:29
loop
after card was present, ... try addingnfc.setPassiveActivationRetries(0x10);
to your setup just beforenfc.SAMConfig();
- this should stop the code waiting for a card :p