NFC reader code help

I have the following python code which continuously listens for NFC tag presence and when detected it prints the UID (ident)

from nfc import ContactlessFrontend
from time import sleep
def connected(tag):
    ident = ''.join('{:02x}'.format(ord(c)) for c in tag.identifier)
    return False
clf = ContactlessFrontend('usb')
while True:
    clf.connect(rdwr={'on-connect': connected})

This works well. However, the problem I face is that if a user holds the NFC tag down then the script reads the same “ident” value over and over again. I want to solve this by possibly temporarily storing the value of “ident” so that it doesn’t print if the value is the same as last scanned for at least X seconds before it is allowed to re-print the same UID (almost like a timeout). Can someone kindly help me modify the code above to do this please?

Thank you.

You can have a global variable (outside any function) last_ident which holds the last value. Then in connected you can do:

ident = ...
if ident == last_ident:
last_ident = ident

You could also add a global variable last_read which saves the time (see the time module) that the last ident was read. And change the if statement to:

if ident == last_ident and last_read + [timeout] > [current_time]:
1 Like

Thank you for that, any chance you can put the code into context in my working code for me please? i’ve tried playing around with that but just cannot get it to work. I’m new to Python and it’s all new to me. Thank you

I got it working, thank you.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.