1

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
_#&%$"    < some garbage
world
_#&%$"    < 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

3

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.

  • Wouldn't it be better to use Serial.end() to reset the buffer pointer too? – Peter Paul Kiefer Nov 27 '19 at 16:24
  • Why? It's a circular buffer - there's no beginning or end to reset it to. – Majenko Nov 27 '19 at 16:25
  • 1
    You are assuming that is the case everywhere. That functionality is undocumented. Yes, the Arduino core does it, but there are no guarantees that every core does it. Or even every version of the Arduino core does it (for example flush changed from clearing the read buffer to blocking on the write buffer...). Plus disabling and re-enabling the serial port may cause unintended side effects (floating pins) which could cause problems. – Majenko Nov 27 '19 at 17:05
  • 2
    I added a change request for the official documentation: github.com/arduino/reference-en/issues/711 – Thomas Weller Nov 27 '19 at 21:31
  • 1
    @ThomasWeller I wish there were more like you. The documentation really needs a lot of work... – Majenko Nov 27 '19 at 21:56

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.