Serial.print doesn't print concatenated strings properly

Hi,
I am having a basic issue with printing a concatenated string (I am running this is on an Arduino Nano)

String hexMessage = "2656426174746572792031332E3738562C20322E3331412C2034332E3536572C20393225";
String command = "R7+WHNC=" + hexMessage + ",ID=10\r";
Serial.println(command);

This code only prints ,ID=10

However, if I break it down it works fine:

Serial.print("R7+WHNC=");
Serial.print(hexMessage);
Serial.print(",ID=10\r")

I never had issues with a string that was too long, not sure what’s going on.
I tried a few casts to String, for example like
command = String("R7+WHNC=") + hexMessage

just don't concatenate Arduino Strings (Strings).
At least use .reserve()
Better, avoid Strings at all.
In your example you want to use the buffer for an output to Serial which is a stream.

Use the Streaming.h library and just stream the output.

for example

Serial << "R7+WHNC=" << hexMessage << ",ID=10\r";

Furthermore, also read about the F-Makro and put fix text blocks into the F-Makro.

i see the following output

R7+WHNC=2656426174746572792031332E3738562C20322E3331412C2034332E3536572C20393225,ID=10

Issues with the String class are common, especially with the Classic Nano, which has very little dynamic memory.

String class memory management is poor and using it leads to program crashes and other unexpected behavior. Best to avoid Strings.

Just like @gcjr states your code snippet prints correctly. You can run the following test script to prove it

void setup()
{
  Serial.begin(115200);

  String hexMessage = "2656426174746572792031332E3738562C20322E3331412C2034332E3536572C20393225";
  String command = "R7+WHNC=" + hexMessage + ",ID=10\r";
  Serial.println(command);
}

void loop()
{
}

So your problem is not that part of the program. I suggest that you post the full program. You might be running low on memory without realising it or have a bug elsewhere causing the symptoms that you experience.

1 Like

why a carrage return? println() appends a new-line

Not sure where that came from. I thought thsy I literally copied OP's snippet. Obviously not :frowning:

you did. the OP added a \r

EOL character. Maybe String uses strcpy() and not strncpy()

or … the \r is needed on the receiving end …

What happens if you instead

Serial.println(command.length());

If it's 7, then the issue is not with print, but with the concatenation.

(A quick glance at the source says that once you have an invalid String, further calls to concat, either directly or the StringSumHelper, should just fail and not "add", so it's interesting if the result is just the last part.)

Thank you everybody for the replies and your help. I finally had some time to test your solutions. The problem seemed to be that I was low on memory like @sterretje suggested.
I removed a couple of extra functions/instructions, and it works fine