2

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

Mike
  • 33
  • 1
  • 5

3 Answers3

3

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:
Eran W
  • 1,696
  • 15
  • 20
  • delay() had to go as high as 2000 before it fix the problem. Neither `while(!Serial)` or wrapping the output in `if(Serial)` made any difference. – Mike Jul 02 '12 at 00:06
0

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

Jeff
  • 1,364
  • 1
  • 8
  • 17
  • That example wouldn't compile, but escaping the null terminator by using `String text1 = "foobar\0";` didn't fix the problem. – Mike Jul 01 '12 at 23:57
  • Strings are automatically null-terminated, there's no need to do it yourself. – Alex Ozer Jul 25 '15 at 16:29
0

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

Community
  • 1
  • 1
ZnArK
  • 1,533
  • 1
  • 12
  • 23
  • 1
    Monitoring the serial output and pressing the hardware reset button causes it to restart without the unintended output at the start. Thanks – Mike Jul 18 '12 at 03:53