I have the following problem: I am trying to build a machine in Arduino that measures the time when no RFID card is on the reader. However, I am encountering the following issue: when I place the card on the reader, the timer starts, but it should only start when the user removes the card from the reader. Can someone help me with this?
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN D4 // SDA Pin (Slave Select)
#define RST_PIN D3 // Reset Pin
MFRC522 mfrc522(SS_PIN, RST_PIN); // RFID-Instanz
unsigned long startTime;
bool timerActive = false;
bool cardDetected = false;
void setup() {
Serial.begin(115200); // Initialisiere die serielle Kommunikation
SPI.begin(); // Initialisiere den SPI-Bus
mfrc522.PCD_Init(); // Initialisiere den RFID-Leser
Serial.println("RFID-Leser bereit. Halten Sie eine Karte an den Leser.");
}
void loop() {
bool cardPresent = mfrc522.PICC_IsNewCardPresent();
if (cardPresent) {
if (mfrc522.PICC_ReadCardSerial()) {
// Karte wird erkannt
if (timerActive) {
// Timer stoppen und Zeit ausgeben
unsigned long elapsedTime = millis() - startTime;
Serial.print("Zeit gemessen: ");
Serial.print(elapsedTime);
Serial.println(" ms");
timerActive = false; // Timer zurücksetzen
}
cardDetected = true; // Karte wurde erkannt
mfrc522.PICC_HaltA(); // Halt das Leseverfahren
mfrc522.PCD_StopCrypto1();
}
} else {
// Wenn keine Karte mehr vorhanden ist
if (cardDetected && !timerActive) {
// Timer starten, wenn der Timer nicht aktiv ist
startTime = millis();
timerActive = true;
Serial.println("Timer gestartet.");
}
cardDetected = false; // Karte wurde entfernt
}
}