Changing Serial baud rate inside setup code causes core freezing afterwards

Hello.
Why does this simple code freeze core after a few loop iterations? I see nothing except “38400” string (or some garbage on 57600 terminal speed) and led stop switching colors after few seconds.

void setup()
{
    
    RGB.control(true);   
    RGB.color(255, 255, 255);
    
    Serial.begin(9600);   // open serial over USB
    while(!Serial.available()) SPARK_WLAN_Loop();

    Serial1.begin(38400);  // open Serial1 over TX and RX pins 38400 baud
    delay(100);    
    Serial1.println("38400");

    Serial1.end();  // close Serial1
    delay(100);

    Serial1.begin(57600);   // open Serial1 over TX and RX pins 57600 baud
    delay(100);
    Serial1.println("57600");
}

void loop() {
    RGB.color(255, 0, 0);
    delay(1000);

    Serial1.println("test");

    RGB.color(0, 255, 0);
    delay(1000);
}

Without changing baud rate to 57600 (Serial1.end(); Serial1.begin()) loop runs indefinitely and i see “test” strings in serial terminal on 38400 baud.

try doing it without Serial1.end()

Thanx. It helped.
Maybe you can explain why I can't reopen port with different baud rate? What is .end() function application?

according to this:

Disables serial communication, allowing the RX and TX pins to be used for general input and output. To re-enable serial communication, call Serial1.begin().

I can reopen (re-enable) serial port after .end() .
This confuses me a bit.

Not sure if it’s a bug here so i’ll prefer others to chime in :wink:

@shax, you are calling end() right after a print() while data is still transmitting. Either do a delay() or call Serial1.flush() which will wait for all bytes to transmit before returning. :smile:

2 Likes

Neither delay(1000) nor .flush() doesn’t change anything. Still freezing if .end() call exist.

...    
Serial1.println("38400");
Serial1.flush();
Serial1.end();  // close Serial1
...

Got this fixed in PR: https://github.com/spark/firmware/pull/446

1 Like