获得NFC卡价值的更好方法?

2024-05-14 13:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了一个小python脚本来获取NFC卡的值,但是我经常遇到一些小的恼人的问题,我想知道是否有更好的方法来实现这一点。现在我的代码如下所示:

import serial
ser = serial.Serial('/dev/tty.usbserial-AH02MAUE', 9600)

def rfidResponse(responseID):
    rID = responseID.strip();
    print repr(responseID)
    print rID
    if rID == "750047FB76BF":
        print "This one"
    else:
        print "other one"

while True:
    try:
        response = ser.readline()
        stringResponse = str(response)
        rfidResponse(stringResponse)
    except KeyboardInterrupt:
        break

ser.close()

我试图将读卡与特定的sting进行比较(在本例中是750047FB76BF)。问题是当我看rID我得到750047FB76BF,当我看print repr(responseID)我得到'\x02750047FB76BF\r\n'。更令人沮丧的是,输出只发生在第一次刷卡时,每次刷卡后都会输出'\x03\x02750047FB76BF\r\n',所以即使是做一些切片也不会每次都起作用。你知道吗

有没有更好的办法?或者理想情况下能够实际使用rID作为比较值(让我避免切片等)。你知道吗


Tags: 脚本responseserial切片onenfcserprint
1条回答
网友
1楼 · 发布于 2024-05-14 13:21:26

显然,当您从serial读取时,会得到NON-ASCII字符,因此我认为您可能希望尝试使用re模块来解析从串行端口读取的内容并检索NFC ID,但是我将在这里假设,当您从串行端口读取时,您将在行尾得到NFC ID,就在EOL(\r\n)之前,所以最好只打印从串行端口接收的任何内容,以确保这是“NFC IDis the last thing you get and if it's more than that, then we have to change there”表达式。你知道吗

我们开始吧:

import serial
import re

ser = serial.Serial('/dev/tty.usbserial-AH02MAUE', 9600)

def rfidResponse(responseID):
    #rID = responseID.strip() #no need for stripping, instead do the next line:
    #print responseID #you can print without `repr`.
    print responseID
    if responseID == "750047FB76BF":
        print "This one"
    else:
        print "other one"

while True:
    try:
        responseID = ser.readline()
        #stringResponse = str(response) # you don't need this line
        response = re.search('[A-Z0-9]{12}(?=\s+)', responsID) #your NFC ID should be of fixed length
        if response:
            rfidResponse(response.group(0))
        else:
            print 'No NFC ID received'
    except KeyboardInterrupt:
        ser.close() #better also close `serial` communication in case of exception
        break

ser.close()

相关问题 更多 >

    热门问题