Strange initial output using Serial.print

核能气质少年 提交于 2019-12-12 17:01:06

问题


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


回答1:


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




回答2:


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:


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



来源:https://stackoverflow.com/questions/11282119/strange-initial-output-using-serial-print

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!