How to write data (text & URL) into NFC NTAG213 by Python & ACR122U?

82 views Asked by At

I want to ask how can I write data into NFC NTAG213? I have researched on YouTube and Google but still don't have any results. I also use ChatGPT but it does not work.

Now I have an ACR122U device and an NTAG213 NFC. I used Python and tried to connect to the NTAG213 and it worked. But the problem is it cannot write data to NTAG213.

Here is the code I use for reading data in NTAG213:

import tkinter as tk
from tkinter import messagebox

import nfc


def read_nfc():
    try:
        clf = nfc.ContactlessFrontend()
        clf.open("usb")
        print("Waiting for a tag...")
        tag = clf.connect(rdwr={"on-connect": lambda tag: read_ndef_data(tag)})
    except Exception as e:
        messagebox.showerror("Error", str(e))

def read_ndef_data(tag):
    print("===== Card Info =====")
    tag_info = tag
    try:
        records = tag.ndef.records
    except Exception:
        pass
    try:
        if "NTAG213" in str(tag_info):
            for record in records:  # type: ignore
                if record.type == "urn:nfc:wkt:U":
                    print("URI Record:", record.uri)
                elif record.type == "urn:nfc:wkt:T":
                    print("Text Record:", record.text)
            print(tag.identifier.hex())
        else:
            print("ID MIFARE:", tag_info.identifier.hex())
        print("---Over---")
    except Exception as e:
        print(e)
        pass

def main():
    def on_enter(event):
        read_nfc()
    root = tk.Tk()
    root.title("NFC Reader")
    button_read = tk.Button(root, text="Read NFC", command=read_nfc)
    button_read.pack()
    root.bind("<Return>", on_enter)
    root.mainloop()

if __name__ == "__main__":
    main()

Hope someone can help me how to write data into NTAG213

I tried to use the smartcard, ndef and nfc python library but it still did not work. Here is the demo:

import ndef
import nfc


def write_text_to_ntag213(text):
    try:
        # Tạo record văn bản
        text_record = ndef.TextRecord(text)

        clf = nfc.ContactlessFrontend()
        clf.open("usb")
        print("Đặt thẻ NTAG213 lên thiết bị...")
        tag = clf.connect(rdwr={"on-connect": lambda tag: False})

        if tag:
            tag_info = clf.target
            if tag_info.type == "Type2Tag":  # Kiểm tra loại thẻ
                tag.send_req([0x30, 0x00])  # Gửi yêu cầu ghi vào thẻ
                tag.ndef.message = [text_record]  # Ghi dữ liệu vào thẻ
                print("Dữ liệu văn bản đã được ghi vào thẻ NTAG213 thành công!")
            else:
                print("Thẻ không phải là NTAG213 hoặc không hỗ trợ ghi NDEF.")
        else:
            print("Không có thẻ được phát hiện.")

    except Exception as e:
        print("Lỗi:", e)


# Gọi hàm để ghi dữ liệu văn bản vào thẻ NTAG213
write_text_to_ntag213("Đây là nội dung văn bản có dung lượng tối đa là 137 byte.")
0

There are 0 answers