问题
I am working on project where I need to read ID of NFC tag, and then perform some action based on that ID. So far I am able to read it once (object with tag is on the reader whole time), but I also need to have some feedback when object is taken off. I am using MFRC522 reader with RPi and SimpleMFRC522 library.
I've tried poking around code in that, but without any success. Do you have any directions / ideas? I have following code:
reader = SimpleMFRC522.SimpleMFRC522()
buffor = 0
while continue_reading:
try:
id, text = reader.read()
if(buffor != id):
print id
udp_send(id)
buffor = id
finally:
time.sleep(0.5)
回答1:
Based on the code at the link you provided, it looks like the reader.read
method blocks while there is no ID to read. Instead, it just continues to try to read until it sees an ID.
However, there is another method called reader.read_no_block
which seems to return None
if there is no ID to read, so you could use that instead.
reader = SimpleMFRC522.SimpleMFRC522()
last_id = None
def exit_event():
print('tag has left the building')
while continue_reading:
id, text = reader.read_no_block()
if id and id != last_id:
# process new tag here
last_id = id
continue
elif not id and last_id:
# if there's no id to read, and last_id is not None,
# then a tag has left the reader
exit_event()
last_id = None
You will probably want to do some debouncing so that exit_event
doesn't get called in error when the reader mistakenly misses a read on a tag.
来源:https://stackoverflow.com/questions/54370052/how-to-detect-removed-card-with-mfrc522