Using Serial.begin() twice I'm training kids programming Arduino. We're gonna use Serial for debugging purposes, so we started with a simple HelloWorld program. I let them try various stuff, including changing the speed.

Now, one of the outcomes was as simple as

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.begin(9600);
  Serial.println("world");
}


My expectation was, that the Arduino does exactly as written, but the serial monitor of the Arduino IDE will become a bit consufed. When the monitor is set to 115200 baud, I expected to see

Hello
world
_#&amp;%$"    &lt; some garbage
world
_#&amp;%$"    &lt; garbage again
...


However, the real output is only one line

H⸮⸮⸮⸮C


Why is that? Is it impossible to change the baud rate in between?

The official documentation does not say we can use Serial.begin() only once.

I'm using Arduino Uno and Arduino IDE 1.8.9
This is because the output of the serial is buffered. It's still sending the first bit of data while you change the baud rate - and from then on it's just a complete mess.

You need to force it to finish sending before you can change the baud rate by using Serial.flush():

void setup() {
  Serial.begin(115200);
  Serial.println("Hello");
  Serial.flush();
}

void loop() {
  Serial.begin(115200);
  Serial.println("world");
  Serial.flush();
  Serial.begin(9600);
  Serial.println("world");
  Serial.flush();
}


That will wait after each print until all the data is sent out "onto the wire" before changing the baud rate for the next print.