My code only works when observing!

#include <SoftwareSerial.h>

SoftwareSerial rfid = SoftwareSerial(5, 6);

void setup()
{
  Serial.begin(9600);
  pinMode(2,OUTPUT);
  
  rfid.begin(9600);
  Serial.println("RFID Ready");
}
char c;
String msg;

void loop()
{
  int hold = 0;
  digitalWrite(2,HIGH);
  
  while(rfid.available())
  {
    hold = hold +1;
    //Serial.write(rfid.read());
    c = rfid.read();
    //Serial.write(c);
    msg =msg +c;
  //Serial.print(hold);
    
    if(hold>=14)
    {
      Serial.println(" ");
    Serial.println("1-1:"+msg);
     Serial.println(" ");
    }
  }
  
  msg = "";
  
  digitalWrite(2,LOW);
}

The code above will only print if I include

Serial.print(hold);

Otherwise it will Never print!
My output when working looks like this:

RFID Ready
1
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
1-1:36008AAA0214

but without printing my hold variable every loop, the IF statement never evaluates to true. Please help!

I can't see what your problem is. Your desired output includes printing the hold variable in every loop.

I would like to NOT print the hold variable everyloop, but if I don't include it, it doesn't work =( .
I would like my output to be:

RFID Ready
1-1:36008AAA0214

No hold variable included

while(rfid.available())
  {
    hold = hold +1;
    //Serial.write(rfid.read());
    c = rfid.read();
    //Serial.write(c);
    msg =msg +c;
  //Serial.print(hold)

As you can see I have the Serial.print(Hold) commented out because I do not want to include it, but if I dont then the Arduino never prints the RFID.

OK. What happens if you close the while loop before the if statement?

I hadn't thought of that, but alas still nothing :frowning:

Printing the value of hold slows down reading of data from rfid. Currently you check if any data, even just one character, is available from rfid but as soon as you read it there is nothing more to read as it has not arrived yet so the while loop exits. To prove this, replace the Serial.print of hold with a short delay. If this works then fix the code properly by ensuring that there is a character to read each time before you do it.

NOTE - adding the delay IS NOT THE WAY TO DO IT IN PRACTICE, only a diagnostic test.

My code only works when observing!

I have colleagues like that.

If this works then fix the code properly by ensuring that there is a character to read each time before you do it.

And, of course, hold should be either global or static (static is better). Otherwise, a pass through loop when there aren't 14 characters to read will cause you to reset hold next pass.

For a while there I thought this might be a case of Schrödinger's cat.

JimboZA:

My code only works when observing!

I have colleagues like that.

LOL! A Karma point is due for that.
I'm retired, but I know what you mean.