RFID RC522 how to detect TAGs with stable states

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:

  1. from NFC_STATE_IDLE to NFC_STATE_TAG_OK when a tag is placed near the antenna
  2. and from NFC_STATE_TAG_OK to NFC_STATE_IDLE when the tag is removed

what should I change in my code to be able to continuously detect the tag avoiding the odd alternate result?

I think use only

for tag.
Because tag become false in next iteration. New card is not present so it will be false

see the Useful code snippets, there is code for tag removal detection. it works well on AVR at least, never tried on ESP32.

1 Like