Not able to print the entire string

Hello,

I'm reading a QR code and printing the string from it in the serial monitor but the string is not complete for some reason, my code is the following:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 4); 
 
void setup()
{
  Serial.begin(9600);  
  mySerial.begin(9600); 
}
 
void loop()
{
  if (mySerial.available()) 
  {
 
    while (mySerial.available()) 
    {
      char input = mySerial.read(); 
      Serial.print(input); 
 
      delay(5);
    }
    Serial.println();
  }
}

My output is the following:
A:500829993*B:251385507*C:PT*D:FS*E:N*F:20220816*G:FS 08710022201010618/026208*021I4:*31Q06

And the correct one should be: A:500829993*B:251385507*C:PT*D:FS*E:N*F:20220816*G:FS 08710022201010618/026208*H:0-026208*I1:PT*I7:1.46*I8:0.33*N:0.33*O:1.79*Q:VDX0*R:369

I get the correct value if I just use the following code:

void loop()
{
   if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
}

The thing is that I would like to store the entire string in order to print it later in the code.

Get rid of this completely useless delay. It results in the serial input buffer being overrun.

To store a string, accumulate it in a zero-terminated character array (C-string). For the details, see the Serial Input Basics tutorial.

At 9600 baud, you will receive a character about every 1ms.

Your delay means you only read a character every 5ms.

The serial buffer is 64 bytes... so as @jremington has said you will quickly fill it up and then data is lost.

Use a char array to hold the data and read it as it comes in.

char myData[256];
uint8_t idx = 0;
. . .
myData[idx++] = Serial.read();

I would suggest to study Serial Input Basics to understand how to deal with an asynchronous data input

Why???

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