How to add a delay time to start a new reading?

51 Views Asked by At

I'm trying to develop a smart lock, with an rfid module, an esp8266 and integration with SinricPro (which makes the bridge for the lock to integrate with Alexa and Google Home)

It turns out that I'm having a very annoying problem, and I would like your help to solve it!

In this function, I execute what needs to be executed after the card passes the RFID module:

void handleRFID() {
if (RFID_card_is_not_present()) return;

      String card_id = get_RFID_card_ID();
      bool RFID_card_is_valid = validate_RFID_card(card_id);
    
      if (RFID_card_is_valid) {
          Serial.printf("The RFID card \"%s\" is valid.\r\n", card_id.c_str());
    
          unlock_with_auto_relock();
          send_lock_state(false);
          // Insert a timeout here, to start reading the card again only after TEMP_AUTOLOCK is over
      } else {
          Serial.printf("The RFID card \"%s\" is not valid.\r\n", card_id.c_str());
          // Insert a delay time here, to start reading the card again only after X time (something like 3 seconds)
      }

}

If I run the code as it is, my serial monitor is spammed with a message that the card is valid/not valid, and it sends a shower of requests to the SinricPro api, as I have nothing limiting the reading of cards in the rfid module for X time, as a delay() function

But unfortunately I can't use delay(), so it's already out of the question

So basically what I want to do is limit the speed at which the cards are read by inserting some wait time where I put the comments in the code. Can someone help me?

For better understanding, I'll make my code available, and the RFID module library I'm using!

Project code: https://github.com/ogabrielborges/smartlock-rfid-iot

MRFC522 library: https://github.com/miguelbalboa/rfid

My serial monitor is spammed with messages that inform that the card is registered/not registered because I don't know how to limit the time that the module reads the tag

printscreen of the serial monitor with the message spam when keeping the tag on the sensor

1

There are 1 best solutions below

0
On

There is a "blink without delay" example in the arduino environment (or there used to be?).

You can find a similar example here: https://docs.arduino.cc/built-in-examples/digital/BlinkWithoutDelay

Basically what you do is remember the current time in a global and check if enough time has passed for the next check:

These are your globals:

unsigned long previousMillis = 0;  // will store last time you did your magic
const long interval = 1000;  // interval at which to do your magic (milliseconds, 1000 = 1 sec)

Then do this somewhere in a function:

unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
  // save the last time you did your magic
  previousMillis = currentMillis;
  // Do your magic here
}