Problem with RFID Timer

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
  }
}

Place some more Serial.println inside the ifs and elses to see where you get wrong and then paste the output on here and tell where you expeczed something else than that happened

Hi @nikl,

BTW: Is your thread correctly placed in the German part of the Forum?

Anyway, here is a tutorial how to detect the removal of a SD card:

https://highvoltages.co/tutorial/arduino-tutorial/arduino-mfrc522-tutorial-is-rfid-tag-present-or-removed/

a further example

https://arduino.stackexchange.com/questions/21619/detect-when-rfid-card-is-absent

and here another example

https://forum.arduino.cc/t/how-to-check-if-a-rfid-card-is-always-touching/1162187/6

If I am not wrong the function

mfrc522.PICC_IsNewCardPresent();

returns "true" only once when a new card is presented. On a second call it returns "false". It will only return "true" again after removal and a further presentation of a card.

Good luck
ec2021

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.