2

I have encountered this several times before and I would like it if someone was able to give an explanation. In almost any sketch that I've ever created with Serial communication involved, I notice that I will get text that seemingly appears before the void setup() function has run. For example, I have the simplest sketch below where this occurs.

void setup(){
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Welcome");
}

void loop(){
// put your main code here, to run repeatedly:
}

If I upload this to one of my Arduino Megas, I will often get the output in the serial monitor:

WelcWelcome

When I open the serial monitor to view the output, the "Welc" is already written and then the rest of the "Welcome" come in a few moments later. If I close and re-open the serial monitor or reselect the baudrate setting within the serial monitor, the serial monitor clears, restarting the Arduino, and printing only "Welcome" to the screen without the "Welc", as I would expect.

However, if I upload the sketch, then disconnect-reconnect the Arduino-USB cable from the computer, and open the serial monitor, there is no leftover bytes printed to the screen like before.

The exact bytes leftover that appear before the void setup() function is called varies from upload to upload. Can anyone give me an explanation and is there a way to avoid the leftover bytes ? Thank you.

5

It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.

It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.

You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.

As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.

0

Because as soon as you start the serial monitor, it picks whats on the serial buffers and then resets the arduino connected and also it would reset again when you try to upload code but luckily serial monitor is cleared in this instance;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.