Arduino Serial Output Dropping Characters

2019-07-01 20:16发布

问题:

I have a bizarre one here with the serial output when trying to write some code for my Arduino Uno.

I have this proto-code:

MyClass myclass;

void setup()
{
   Serial.Begin(9600);
   Serial.println("Starting...");
}

void loop()
{
   int status = myclass.DoWork();
   Serial.println("Status: " + status);
}

class MyClass 
{
   int DoWork()
   {
      Serial.println("Doing some work...");
      return 1;
   }
}

Now when this runs I get the following output:

Starting...

Doing some work...

atus: 1

So the strange part is the "Status: 1" missing the first few characters. Is this because I am using serial in an object improperly or something?

I have noticed when I reference another library that also uses serial like MyClass does that I get other strange output behavior... so I assume that I am doing something wrong.

EDIT: In the end this turned out to actually be a memory issue. A library I was including was quite large and it was consuming the available memory. I found this by adding a few more debugging statements and found the corruption shifted around based on the string lengths and positions. By using the F() function I moved the strings to flash memory (e.g. I now run Serial.println(F("Starting...")); and it has corrected the strange output.

回答1:

You cannot add strings and integers in C++. It would have been better for you if this failed to compile:

Serial.println("Status: " + status);

Instead the compiler guessed at something. It guessed wrong. Use this:

Serial.print("Status :");
Serial.println(status);

or for complete control of outputting numbers and strings learn to use C string formatting, sprintf()



回答2:

In the end this turned out to actually be a memory issue. A library I was including was quite large and it was consuming the available memory. I found this by adding a few more debugging statements and found the corruption shifted around based on the string lengths and positions. By using the F() function I moved the strings to flash memory (e.g. I now run Serial.println(F("Starting...")); and it has corrected the strange output.



回答3:

One more possible explanation.

I was running minicom to monitor, and I usually like that it auto-reconnects after resetting my device.

Well I minimized a terminal running minicom last night, and today I started a new instance that somehow also got connected to the same serial port (if that is even possible).

I think the two instances of minicom were each reading ~50% of the serial characters roughly at random, leaving me with quite a mess of text.