So I started a project with my Arduino UNO where I connected an SD card module and an RFID reader. They share the SPI bus regarding MISO, MOSI and SCK, and therefore the code needed to be tweaked using digitalWrite() and manipulating HIGH and LOW values (I suppose). I have everything wired properly and when running the code the serial monitor shows that both the SD card and the RFID reader are initialized, however the RFID tags are not noticed at all. Both parts work individually with different codes so I suppose it has to do with the SPI connection, but I'm not sure how to fix it. Any ideas? Thanks a lot!
#include <SPI.h>
#include <MFRC522.h>
#include <SD.h>
#define SD_CS 4 // SD card CS pin
#define RFID_CS 10 // RFID CS pin
#define RST_PIN 7 // RFID reset pin
MFRC522 rfid(RFID_CS, RST_PIN);
File logFile;
void setup() {
Serial.begin(9600);
delay(1000);
pinMode(SD_CS, OUTPUT);
pinMode(RFID_CS, INPUT);
digitalWrite(SD_CS, HIGH);
digitalWrite(RFID_CS, HIGH);
SPI.begin();
digitalWrite(RFID_CS, HIGH);
digitalWrite(SD_CS, LOW);
if (SD.begin(SD_CS)) {
Serial.println("SD card initialized.");
} else {
Serial.println("SD card FAILED!");
while (1);
}
digitalWrite(SD_CS, HIGH); // Release SD
// Init RFID
digitalWrite(SD_CS, HIGH);
digitalWrite(RFID_CS, LOW);
rfid.PCD_Init();
Serial.println("RFID reader initialized.");
digitalWrite(RFID_CS, HIGH); // Release RFID
}
void loop() {
// Activate RFID
digitalWrite(SD_CS, HIGH);
digitalWrite(RFID_CS, LOW);
if (rfid.PICC_IsNewCardPresent() && rfid.PICC_ReadCardSerial()) {
Serial.println("RFID tag detected!");
// Read UID
String uid = "";
for (byte i = 0; i < rfid.uid.size; i++) {
if (rfid.uid.uidByte[i] < 0x10) uid += "0";
uid += String(rfid.uid.uidByte[i], HEX);
}
uid.toUpperCase();
Serial.print("UID: ");
Serial.println(uid);
// Release RFID
rfid.PICC_HaltA();
rfid.PCD_StopCrypto1();
digitalWrite(RFID_CS, HIGH);
// Access SD to write
digitalWrite(SD_CS, LOW);
logFile = SD.open("rfid_log.txt", FILE_WRITE);
if (logFile) {
logFile.println(uid);
logFile.close();
Serial.println("UID saved to SD card.");
} else {
Serial.println("Error opening rfid_log.txt");
}
digitalWrite(SD_CS, HIGH);
delay(1000); // Simple debounce
}
// Always release both CS
digitalWrite(SD_CS, HIGH);
digitalWrite(RFID_CS, HIGH);
}