- admin3小时前管理员1
#include <PN532_SWHSU.h> #include <PN532.h> #include <SoftwareSerial.h> #include <EEPROM.h> // 包含EEPROM库 SoftwareSerial uart1(PD5, PD6); // 链接nfc PN532_SWHSU pn532swhsu(uart1); PN532 nfc(pn532swhsu); const int MAX_TAGS = 5; // 最多存储5个卡号 const int TAG_SIZE = 16; // 每个卡号的最大长度(包括结束符) const int EEPROM_START = 0; // EEPROM存储的起始地址 void setup() { Serial.begin(115200); uart1.begin(115200); nfc.begin(); nfc.SAMConfig(); } void loop() { readNFC(); delay(500); } void readNFC() { boolean success; uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID uint8_t uidLength = 7; // Length of the UID String nfcre = ""; success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength); if (success) { for (uint8_t i = 0; i < uidLength; i++) { nfcre += String(uid[i], HEX); Serial.print(uid[i], DEC); Serial.print(" "); } Serial.println(" "); Serial.println(nfcre); // 检查是否与EEPROM中存储的卡号匹配 if (checkTag(nfcre)) { // 卡号匹配,点亮板载LED digitalWrite(LED_BUILTIN, HIGH); delay(500); // 亮500ms digitalWrite(LED_BUILTIN, LOW); } else { // 卡号不匹配,存储新的卡号 saveTag(nfcre); } } else { // PN532 probably timed out waiting for a card // Serial.println("Timed out! Waiting for a card..."); } } // 检查卡号是否匹配 bool checkTag(String tagId) { for (int i = 0; i < MAX_TAGS; i++) { String storedTag = readFromEEPROM(i); if (storedTag == tagId) { return true; // 找到匹配的卡号 } } return false; // 没有找到匹配的卡号 } // 将卡号存储到EEPROM void saveTag(String tagId) { for (int i = 0; i < MAX_TAGS; i++) { if (readFromEEPROM(i) == "") { // 找到空的存储位置 writeToEEPROM(i, tagId); Serial.println("Tag ID saved to EEPROM."); return; } } Serial.println("EEPROM is full. Cannot save new tag."); } // 写入卡号到EEPROM void writeToEEPROM(int index, String tagId) { int startAddress = EEPROM_START + index * TAG_SIZE; for (size_t i = 0; i < tagId.length(); i++) { EEPROM.write(startAddress + i, tagId[i]); } EEPROM.write(startAddress + tagId.length(), '\0'); // 添加字符串结束符 } // 从EEPROM读取卡号 String readFromEEPROM(int index) { int startAddress = EEPROM_START + index * TAG_SIZE; String storedTag = ""; char c; for (int i = 0; i < TAG_SIZE; i++) { c = EEPROM.read(startAddress + i); if (c == '\0') break; // 遇到字符串结束符停止 storedTag += c; } return storedTag; }主楼 - 暂无回复