arduino / esp8266

arduino PN532 NFC RFID

ESP8266 i2c接線

D1 <–> SCL
D2 <–> SDA
3V <–> VCC
G <–> GND

程式碼

#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);

NfcAdapter nfc = NfcAdapter(pn532_i2c);

//D8=15接腳,異常蜂鳴器
int buzzer = 15;


void setup() {
  Serial.begin(115200);
  
  nfc.begin();
  Serial.println("b");
  pinMode( buzzer, OUTPUT);
  digitalWrite( buzzer, LOW);//通電時預設關閉
  
}


void loop() {

Serial.println("c");
  
  if (nfc.tagPresent()) {

    NfcTag tag = nfc.read();
    String cardUid = tag.getUidString();
    int cardUid_2H4D_1 = get_2H4D_1(cardUid);
    Serial.println(cardUid_2H4D_1);
    int cardUid_2H4D_2 = get_2H4D_2(cardUid);
    Serial.println(cardUid_2H4D_2);
    digitalWrite( buzzer, HIGH);
    delay(100);
    digitalWrite( buzzer, LOW);
  }
  delay(1000);
}

unsigned int get_2H4D_1(String cardUid) {
  int cardStrCt = cardUid.length();
  //B4 3C CD 01
  //123456789AB
  if(cardStrCt == 11){
    String id1 = cardUid.substring(9,11);
    String id2 = cardUid.substring(6,8);
    return hexToDec(id1 + id2);
  }
  return 0;
}

unsigned int get_2H4D_2(String cardUid) {
  int cardStrCt = cardUid.length();
  //B4 3C CD 01
  //123456789AB
  if(cardStrCt == 11){
    String id3 = cardUid.substring(3,5);
    String id4 = cardUid.substring(0,2);
    return hexToDec(id3 + id4);
  }
  return 0;
}

unsigned int hexToDec(String hexString) {
  unsigned int decValue = 0;
  int nextInt;
  for (int i = 0; i < hexString.length(); i++) {
    nextInt = int(hexString.charAt(i));
    if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
    if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
    if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
    nextInt = constrain(nextInt, 0, 15);
    decValue = (decValue * 16) + nextInt;
  }
  return decValue;
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。