Strange initial output using Serial.print

2019-07-12 04:49发布

When I'm writing to the serial interface, I'm getting strange and unexpected output when my sketches first run. The output seems to be a variant of what should be printed:

eg:

String text1 = "foobar";

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

  Serial.print("\n");
  Serial.print(text1);
}

void loop() {
}

Results in the output:

fo
foobar

(the new line appears before "fo" but I couldn't work out how to include it).

So some variant of whatever is supposed to be printed, gets printed before the actual text that is supposed to be printed. Changing the output, changes the anomalous text (sometimes it'll be two characters, sometimes three). Making changes that don't affect the output and recompiling has no effect on the anomalous text.

I'm a total Arduino newbie (I only started writing my own code today), but I can only assume this isn't normal. I'm using a Freetronics EtherTen and the 1.0 IDE

thanks in advance

标签: arduino
3条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-12 04:54

Arduino is restarting your sketch when you open its serial port on the computer. so it prints out, and then initialized again.

after

Serial.begin(9600);

try to put either:

delay(500)

or

while (!Serial); // while the serial stream is not open, do nothing:
查看更多
欢心
3楼-- · 2019-07-12 05:01

You should probably terminate your string with a 0. Like: String text1 = "foobar",0;

查看更多
姐就是有狂的资本
4楼-- · 2019-07-12 05:05

This is most likely a Serial communication Reset issue as Eran W pointed out. See my previous answer here.

The Arduino automatically resets when it receives serial communication from most things other than the Arduino IDE. This is why you can send from the IDE but not anything else.

I have an Uno and put a capacitor between Reset and Ground.Here's a page with some good info on the subject.
Good luck. http://arduino.cc/playground/Main/DisablingAutoResetOnSerialConnection

查看更多
登录 后发表回答