Unable to read RFID tag info unless serial monitor is opened

I am using the MFRC522 library and I have custom logic based on the UID of the tag. The issue is that the custom code runs only if the serial monitor is open. If I upload the code and the serial monitor is closed, the RFID does not detect the tag (the custom code is not run). This is my code:

#include <MFRC522.h>

#define RST_PIN         9
#define SS_PIN          10 
#define BLUELED        4

MFRC522 mfrc522(SS_PIN, RST_PIN);
boolean isOnRoad;
int bluelightOn;
unsigned long previousMillis, currentMillis;
unsigned long blueLightInterval = 1000;

void setup() {

  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  pinMode(BLUELED, OUTPUT);

  previousMillis = 0;

}

void loop() {

  currentMillis = millis();

  if (!isOnRoad) {
    normalTrafficLights();
  } else {
    onRoad();
  }

  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  byte block;
  byte len;
  MFRC522::StatusCode status;

  // if ( ! mfrc522.PICC_IsNewCardPresent()) {
  //   return;
  // }

  // if ( ! mfrc522.PICC_ReadCardSerial()) {
  //   return;
  // }

  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {

      if ((mfrc522.uid.uidByte[0] == 0x72 && 
        mfrc522.uid.uidByte[1] == 0xE5 &&
        mfrc522.uid.uidByte[2] == 0x23 &&
        mfrc522.uid.uidByte[3] == 0xD9) || (
        mfrc522.uid.uidByte[0] == 0x25 && 
        mfrc522.uid.uidByte[1] == 0xC4 &&
        mfrc522.uid.uidByte[2] == 0xF5 &&
        mfrc522.uid.uidByte[3] == 0xC2) || (
        mfrc522.uid.uidByte[0] == 0x82 && 
        mfrc522.uid.uidByte[1] == 0x82 &&
        mfrc522.uid.uidByte[2] == 0x94 &&
        mfrc522.uid.uidByte[3] == 0xDC)) {

             isOnRoad = false;

      }

  }

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

void onRoad() {

  if (currentMillis - previousMillis >= blueLightInterval) {

    previousMillis = currentMillis;
    
    bluelightOn = !bluelightOn;

    digitalWrite(BLUELED, bluelightOn);
    
  }
  
}

Any idea what might be happening?

What exactly is this mysterious custom code that you did not post ?

@UKHeliBob LED blinking. I did not want to crowd the code, so I didn't add it

Please add it so that we can see what you are doing and how. Does it by any chance make use of the delay() function ?

@UKHeliBob I have updated the question to include the custom code. And no, I am not using the delay() function

@UKHeliBob any help?

Sorry, but I can see nothing wrong with the sketch

Which Arduino board are you using ?

@UKHeliBob Hi sorry I'm not sure but it suddenly started working

Are you saying that you don't know which tyoe of Arduino board you are using ?

Which board is selected in the IDE ?

@UKHeliBob it's an Arduino UNO. But what I meant was that it started working and I'm unsure how.

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