This is a sketch that uses multiple MFRC522 RFID readers to read RFID cards and display the card's ID on the serial monitor. The sketch defines an array of possible SS (Slave Select) pins based on the type of Arduino board used, and initializes each reader with its respective SS and RST (Reset) pin. It then continuously checks for new RFID cards present on each reader and reads their IDs, which are sent to the serial monitor along with the ID of the reader itself. Finally, the sketch halts the card's communication and stops the crypto on each reader.
This sketch allows for seamless integration with JMRI and supports up to 8 RFID readers, enabling efficient card reading and data transmission for model railroad applications.
?
// Import Libraries
#include <SPI.h>? // SPI library for communicating with the MFRC522 reader
#include <MFRC522.h>? // MFRC522 library for reading RFID cards
?
// Define the SS (Slave Select) and RST (Reset) pins for each reader
#if defined(ARDUINO_AVR_UNO) || defined(ARDUINO_AVR_NANO)
const uint8_t possibleSSPins[] = {10, 8, 6, 4, 2, A1, A3};
#elif defined(ARDUINO_AVR_MEGA2560)
const uint8_t possibleSSPins[] = {10, 8, 6, 4, 2, A1, A3, A5};
#endif
?
const int numPossibleReaders = sizeof(possibleSSPins) / sizeof(possibleSSPins[0]);
const char readerID[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
?
struct RFIDReader {
? char id;
? uint8_t ssPin;
? uint8_t rstPin;
? MFRC522 mfrc522;
? byte nuid[7];
?
? RFIDReader() : id(0), ssPin(0), rstPin(0), mfrc522(MFRC522(0, 0)) {}
};
?
RFIDReader readers[numPossibleReaders];
?
void setup() {
? Serial.begin(9600);
? SPI.begin();
?
? for (uint8_t i = 0; i < numPossibleReaders; i++) {
? ? readers[i].ssPin = possibleSSPins[i];
? ? readers[i].rstPin = possibleSSPins[i] - 1;
? ? readers[i].id = readerID[i];
? ? readers[i].mfrc522 = MFRC522(readers[i].ssPin, readers[i].rstPin);
? ? readers[i].mfrc522.PCD_Init();
? ? readers[i].mfrc522.PCD_SetAntennaGain(readers[i].mfrc522.RxGain_max);
? }
}
?
void loop() {
? for (uint8_t i = 0; i < numPossibleReaders; i++) {
? ? if (readers[i].mfrc522.PICC_IsNewCardPresent() && readers[i].mfrc522.PICC_ReadCardSerial()) {
? ? ? for (uint8_t j = 0; j < readers[i].mfrc522.uid.size; j++) {
? ? ? ? readers[i].nuid[j] = readers[i].mfrc522.uid.uidByte[j];
? ? ? }
?
? ? ? byte checksum = readers[i].nuid[0];
? ? ? for (uint8_t j = 1; j < 5; j++) {
? ? ? ? checksum ^= readers[i].nuid[j];
? ? ? }
?
? ? ? Serial.write(readers[i].id);
?
? ? ? for (uint8_t j = 0; j < 5; j++) {
? ? ? ? Serial.print(readers[i].nuid[j] < 0x10 ? "0" : "");
? ? ? ? Serial.print(readers[i].nuid[j], HEX);
? ? ? }
?
? ? ? Serial.print(checksum < 0x10 ? "0" : "");
? ? ? Serial.print(checksum, HEX);
?
? ? ? Serial.write(0x0D);
? ? ? Serial.write(0x0A);
? ? ? Serial.write('>');
?
? ? ? readers[i].mfrc522.PICC_HaltA();
? ? ? readers[i].mfrc522.PCD_StopCrypto1();
? ? }
? }
}