Functions called in loop don't come in order that I wrote after booting!

Hi guys, I'm working on an RFID tags project using esp32, I have two RFID tags and I wrote two functions: the first to read data from the first RFID tag (Task tag) and the second to read data from the second RFID tag (User tag), I called both functions in the loop function and after booting I realized that the functions I called don't come in order that I wrote: readTask() then readUser() but rather it calls randomly, sometimes it calls readTask first sometimes readUser first sometimes it calls readTask twice in a row, WHAT should I do to fix this!

#include <SPI.h>
#include <MFRC522.h>
#include <ThreeWire.h>  
#include <RtcDS1302.h>
#define RST_PIN         22           // Configurable, see typical pin layout above
#define SS_PIN          5          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance
MFRC522::StatusCode status;
MFRC522::MIFARE_Key key;

byte buffer[34];
byte buffer1[18];
byte buffer2[18];
byte buffer3[18];
byte buffer4[18];

String getTaskTypeID;
//byte len = sizeof(buffer);
byte len = 34;
String getCurrentTask;

ThreeWire myWire(27,26,25); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);
String currentTime;

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();  
  // Init MFRC522 card
     Rtc.Begin();
}

void loop() {
  readTask();
  readUser();
}

void blabla(){
  RtcDateTime now = Rtc.GetDateTime();
  currentTime=printDateTime(now);
  //Serial.println(currentTime);
  delay(2000); // ten seconds
  
  if(getTaskTypeID != getCurrentTask){
      // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  currentTime.getBytes(buffer,34);
  writeBlock(4);

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
  }

  //else 

  
}

 void readUser(){
//*****************************************************************************************//
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }


  Serial.println(F("**Card Detected:**"));

  //------------------------------------------- GET TASK ID
  Serial.print(F("User ID: "));
  readBlock(buffer1,1);
  //---------------------------------------- GET TASK TYPE ID
  Serial.print(F("\nUser Role ID: "));
  readBlock(buffer2,2);
  //----------------------------------------
  //---------------------------------------- GET TASK DATA: NB TOURS
  Serial.print(F("\nUser Current Task: "));
  readBlock(buffer3,4);
  getCurrentTask = String((char*)buffer3);

  //----------------------------------------
  //---------------------------------------- GET TASK DATA: NB TOURS
  Serial.print(F("\nUser Last Time: "));
  readBlock(buffer4,5);
  //----------------------------------------
  Serial.println(" ");
        Serial.println("getCurrentTask:");
    Serial.println(getCurrentTask);

  Serial.println(F("\n**End Reading**\n"));
  delay(1000); //change value if you want to read cards faster
  
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}



void readBlock(byte *buffer,byte block){
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT ...
  for (uint8_t i = 0; i < 16; i++){
      Serial.write(buffer[i]);      
  
  }
}   



 void readTask(){
//*****************************************************************************************//
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }


  Serial.println(F("**Card Detected:**"));

  //------------------------------------------- GET TASK ID
  Serial.print(F("Task ID: "));
  readBlock(buffer1,4);
  //getTaskId = String((char*)buffer1);
  //Serial.println(getTaskId);
  //---------------------------------------- GET TASK TYPE ID
  Serial.print(F("\nTask Type ID: "));
  readBlock(buffer2,5);
  getTaskTypeID = String((char*)buffer2);
  //Serial.println(getTaskName);
  //----------------------------------------
  //---------------------------------------- GET TASK DATA: NB TOURS
  Serial.print(F("\nnb de tours: "));
  readBlock(buffer3,6);
  //getTaskDelai = String((char*)buffer3);
  //Serial.println(getTaskDelai);
  //----------------------------------------
    Serial.println(" ");
      Serial.println("getTaskTypeID:");
    Serial.println(getTaskTypeID);
  Serial.println(F("\n**End Reading**\n"));
  delay(1000); //change value if you want to read cards faster
  
  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
#define countof(a) (sizeof(a) / sizeof(a[0]))

String printDateTime(const RtcDateTime& dt)
{
    char datestring[20];
    snprintf_P(datestring, 
            countof(datestring),
            PSTR("%02u:%02u:%02u"),
            dt.Hour(),
            dt.Minute(),
            dt.Second() );
    return datestring;
}

void writeBlock(byte block){

  /**************************************Block*****************************************************/
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));
}

Your assumption is likely wrong…
you have return statements that might cut short some function calls
Add a print and flush at the start of the functions to see what’s going on

Try

void loop() {
  Serial.println("Before readTask");
  readTask();
  Serial.println("Before readUser");
  readUser();
}

I suspect that readTask is returning before you think it is.

Hi again, so this what I got trying what u tell me to do, it loops Before readTask+Before readUser
then it execute sometimes either readTask or readUser
Screenshot 2022-04-26 084332

on the second attempt it shows directly a loop of Before readTask+Before readUser

if I try this :

  Serial.println("Before readTask");
  readTask();
  Serial.println("Before readUser");
  readUser();

It show this :
Screenshot 2022-04-26 084332

and execute either readTask and readUser.. I'm pretty sure

So as you can now see, the functions are executing in the correct order.

So you need to further investigate what is happening within each of the functions.

Try inserting a Serial.print statement before each return statement and at the end of each of the functions so that you can confirm what is going on. This process is known as debugging.

1 Like

Not sometimes, always… the execution might not match your expectations, that is what you need to debug next

In contrast to the process of putting the bugs in, which is known as programming :wink:

4 Likes

Do at least me a favor and make one of the two print statements a bit longer, makes it easier to confirm perfect behaviour of at least the calls to your functions, viz:

    Serial.println("and  before         readUser");

Just a tip from the trenches.

a7

1 Like

that's what i got
Screenshot 2022-04-26 152017

yeah just proves the same point in a visually somewhat easier way (although it's not too difficult to see two consecutive lines are the same if you concentrate on the last letters)

Before readTask
Before readUser
Before readTask
Before readUser
Before readTask
Before readUser
Before readTask
Before readUser
Before readTask
Before readTask
Before readUser
Before readTask
Before readUser

You are calling the functions over and over again. When you hold a task tag to the reader it appears that which ever function is currently executing (readTask() or readUser()) will attempt to read that tag. There is no way for the code to know which card comes first. Can you use the uid to identify the card?

That seems logical, I guess the best choice is to add another RFID reader

OK, spotted.

a7

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