0
1

More than 1 year has passed since last update.

Python:NFC

Last updated at Posted at 2022-02-12

1.準備

1-1.Windows

ここを参考に準備

1-1.Mac

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

fetchがうまくいかない場合は一度、アンイストールしてからもう一度インストール

lsusbをインストール(ターミナル)

brew tap jlhonora/lsusb
brew install lsusb

1-2.ライブラリのインストール(ターミナル)

pip install nfcpy

1-3.NFCリーダー

NFCリーダーはsonyのRC-S380/Sでうまくいきました。
RC-S300だとうまくいかなかった。(原因はちゃんとしらべていない)

1-4.接続

NFCリーダーをパソコンに接続しましょう。

1-5.確認

PyCharm等で下記のプログラムを実行してみましょう。

import nfc

clf = nfc.ContactlessFrontend('usb')
print(clf)

2.プログラム

下記のプログラムをコピペして実行してみてください。
NFCタグや学生証などをカードリーダーにかざすと
【 Touched 】
離すと
【 Released 】
と表示されるはずです。このプログラムで読み取りはできません。

import nfc

class CardReader(object):
    def on_connect(self, tag):
        #タッチ時の処理
        print("【 Touched 】")
        return True

    def read(self):
        clf = nfc.ContactlessFrontend('usb')
        try:
            clf.connect(rdwr={'on-connect': self.on_connect})
        finally:
            clf.close()


cr = CardReader()
while True:
    #最初に表示
    print("Please Touch")
    #タッチ待ち
    cr.read()
    #リリース時の処理
    print("【 Released 】")

FeliCaカードの内容を読み取る

FeliCaカードの内容を読み取るプログラム

import binascii
import nfc

def connected(tag):
  print (tag)

  if isinstance(tag, nfc.tag.tt3.Type3Tag):
    try:
      print('  ' + '\n  '.join(tag.dump()))

    except Exception as e:
      print ("error: %s" % e)
  else:
    print ("error: tag isn't Type3Tag")


clf = nfc.ContactlessFrontend('usb')
clf.connect(rdwr={'on-connect': connected})

NFCタグの内容を読み取る

NFCタグのレコードの内容を読み取るプログラム

import binascii
import nfc

def connected(tag):
    print(tag)
    records = tag.ndef.records
    for record in records:
        print(record.text)


clf = nfc.ContactlessFrontend('usb')
clf.connect(rdwr={'on-connect': connected})
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1