123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- #include <SPI.h>
- #include <MFRC522.h>
- #include "NfcAdapter.h"
- // 定义RC522模块的引脚
- #define SS_PIN 7 // SDA
- #define RST_PIN 3 // RST
- String errorValue = "r:rfid error";
- String notRfid = "r:not rfid";
- String writeValue = "r:write ok";
- // 创建MFRC522对象
- MFRC522 mfrc522(SS_PIN, RST_PIN);
- NfcAdapter nfc = NfcAdapter(&mfrc522);
- void ndefSetup(void) {
- SPI.begin(); // Init SPI bus
- mfrc522.PCD_Init(); // Init MFRC522
- nfc.begin();
- }
- void readRFID(){
- String str = errorValue;
- if(nfc.tagPresent()){
- Serial.println("Reading NFC tag");
- NfcTag tag = nfc.read();
- Serial.println(tag.getTagType());
- Serial.print("UID: ");Serial.println(tag.getUidString());
- NdefMessage message = tag.getNdefMessage();
- Serial.print("\nThis NFC Tag contains an NDEF Message with ");
- Serial.print(message.getRecordCount());
- Serial.print(" NDEF Record");
- int recordCount = message.getRecordCount();
- for (int i = 0; i < recordCount; i++){
- Serial.print("\nNDEF Record ");Serial.println(i+1);
- NdefRecord record = message.getRecord(i);
- Serial.print(" TNF: ");Serial.println(record.getTnf());
- String type((char*)record.getType());
- Serial.println(" Type: " + type);
- int payloadLength = record.getPayloadLength();
- const byte *payload = record.getPayload();
- String payloadHEX((char*)payload);
- Serial.println(" Payload (HEX): " + payloadHEX);
- String payloadAsString = "";
- for (int c = 0; c < payloadLength; c++) {
- payloadAsString += (char)payload[c];
- }
- Serial.print(" Payload (as String): ");
- Serial.println(payloadAsString);
- if (record.getIdLength() > 0) {
- String ID((char*)record.getId());
- Serial.println(" ID: " + ID);
- }
- str = payloadAsString;
- }
- }
- pCharacteristic->setValue(str.c_str());
- }
- void writeRFID(String data){
- String str = errorValue;
- if(nfc.tagPresent()){
- Serial.println("Writing multiple records to NFC tag");
- NdefMessage message = NdefMessage();
- message.addTextRecord(data.c_str());
- // message.addUriRecord("https://arduino.cc");
- boolean success = nfc.write(message);
- if (success)str = writeValue;
- }
-
- pCharacteristic->setValue(str.c_str());
- }
- //0:开头字符串读取 1:开头字符串写入
- void ndefCommand(){
- String command = pCharacteristic->getValue().c_str();
- if (command.startsWith("0:")) {
- readRFID();
- } else if (command.startsWith("1:")) {
- String data = command.substring(2);
- writeRFID(data);
-
- }
- }
- int loopNdefSize=1000; //loop间隔
- int ndefMillisTime;
- void ndefLoop(void) {
- //1秒读取一次指令
- int ndefTimeCurrent = millis();
-
- if(ndefTimeCurrent<=0)ndefMillisTime = ndefTimeCurrent;
- if((ndefTimeCurrent - ndefMillisTime)>loopNdefSize){
- ndefMillisTime = ndefTimeCurrent;
- ndefCommand();
- }
- }
|