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.