You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python NFC识别代码为ident相同校验添加7秒超时功能的实现问题

修改方案

核心修改逻辑

  • 导入time模块的time()方法获取秒级时间戳
  • 新增全局变量last_read_time存储上一次打印ident的时间,超时阈值固定为7秒
  • 调整校验规则,满足以下任意条件就触发打印:
    • 当前读取的current_ident和上一次记录的ident值不同
    • 当前时间和上一次打印的时间差超过7秒
  • 每次打印完成后,同步更新存储的ident值和打印时间

完整可运行代码

from nfc import ContactlessFrontend
from time import sleep, time

ident = ''
last_read_time = 0
# 超时阈值单位为秒
TIMEOUT_SECOND = 7

def connected(tag):
    global ident, last_read_time
    current_ident = ''.join('{:02x}'.format(ord(c)) for c in tag.identifier)
    current_time = time()
    # 校验规则:id不同 或 超时后同id也允许打印
    if current_ident != ident or (current_time - last_read_time) > TIMEOUT_SECOND:
        print(current_ident)
        ident = current_ident
        last_read_time = current_time
    return False

clf = ContactlessFrontend('usb')
while True:
    clf.connect(rdwr={'on-connect': connected})
    sleep(1)

内容的提问来源于stack exchange,提问作者John Roberts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 00:06:03