TKK_E32232028/esp8266_rfid_slave/esp8266_rfid_slave.ino

101 lines
1.9 KiB
C++

#include <Arduino.h>
#include <SPI.h>
#include <MFRC522.h>
// ==========================
// RC522 wiring (ESP8266)
// ==========================
// Keep your existing pins here.
#define SS_PIN D4
#define RST_PIN D3
MFRC522 rfid(SS_PIN, RST_PIN);
// ==========================
// UART link to ESP32-S3
// ==========================
// Easiest: use Serial at 115200 to talk to ESP32.
// NOTE: This means you can't reliably use the same Serial for USB monitor at the same time.
// If you want USB monitor + ESP32 link simultaneously, switch to SoftwareSerial.
static constexpr uint32_t LINK_BAUD = 115200;
// Set true if you want extra prints on the same UART (will also be received by ESP32).
static constexpr bool DEBUG_UART = false;
String uidToString(const MFRC522::Uid &uid)
{
String s;
for (byte i = 0; i < uid.size; i++)
{
if (uid.uidByte[i] < 0x10)
s += '0';
s += String(uid.uidByte[i], HEX);
if (i < uid.size - 1)
s += ':';
}
s.toUpperCase();
return s;
}
void sendEventToMaster(const String &uid)
{
// Message consumed by ESP32-S3
Serial.println("RFID UID=" + uid);
}
void setup()
{
Serial.begin(LINK_BAUD);
delay(800);
if (DEBUG_UART)
{
Serial.println("ESP8266 RFID SLAVE READY");
}
SPI.begin();
SPI.setFrequency(400000); // more stable for some RC522 boards
rfid.PCD_Init();
delay(50);
byte version = rfid.PCD_ReadRegister(MFRC522::VersionReg);
if (DEBUG_UART)
{
Serial.print("RC522 Version: 0x");
Serial.println(version, HEX);
}
}
void loop()
{
// Poll RFID
if (!rfid.PICC_IsNewCardPresent())
{
delay(20);
return;
}
if (!rfid.PICC_ReadCardSerial())
{
delay(60);
return;
}
String uid = uidToString(rfid.uid);
if (DEBUG_UART)
{
Serial.print("UID: ");
Serial.println(uid);
}
// Always send UID-only event to ESP32.
sendEventToMaster(uid);
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
delay(1500); // debounce
}