I'm using the well known (though old) RFID library for ESP32. It works fine, I've used it for several projects.
Now I'm having hard time to do a simple thing: I need to detect when a TAG is available and when is not.
I wrote this code:
void loop()
{
bool tag = PICC_IsNewCardPresent() && PICC_ReadCardSerial();
switch (state)
{
case NFC_STATE_IDLE:
if (tag)
{
Serial.println("TAG detected");
// do something
// if uncommented will stop the communication
// PICC_HaltA();
// PCD_StopCrypto1();
state = NFC_STATE_TAG_OK;
}
break;
case NFC_STATE_TAG_OK:
if (!tag)
{
Serial.println("TAG removed");
state = NFC_STATE_IDLE;
}
break;
}
delay(250);
}
Here the behavior I observe when I place a tag near the antenna:
TAG detected
TAG removed
TAG detected
TAG removed
TAG detected
TAG removed
TAG detected
TAG removed
...
This is because the tag value is true on the, say, first call and false on the next, true again, and so on.
if I uncomment the PICC_HaltA() and PCD_StopCrypto1() lines after the detection it print "TAG removed" until I actually remove the tag and place it again.
Instead, I just want it stays in the related state:
- from
NFC_STATE_IDLEtoNFC_STATE_TAG_OKwhen a tag is placed near the antenna - and from
NFC_STATE_TAG_OKtoNFC_STATE_IDLEwhen the tag is removed
what should I change in my code to be able to continuously detect the tag avoiding the odd alternate result?