Serial1 gibberish first character

I have the following test code

unsigned long lastTime = 0;

void setup()          
{
    Serial1.begin(9600);
}

void loop()  
{    
    unsigned long now = millis();     
    if (lastTime == 0 ||  ((now - lastTime) > 5000)){ 
        Serial1.println("!");
        lastTime = now; 
    }
}

This gives the following output in Putty

▒!
!
!

I wrote a test Python program reading from serial and get the same result. This happens every time I reboot the device. First char is 0xff and don't understand where it coming from. I believe it sends from Serail1.begin() call, but I couldn't find anything suspicious in source code of DeviceOS. Has anybody had the same problem?

that’s weird I never seen something like this which device OS you are targeting ?
could you add in your setup
after Serial1.begin(9600); Serial1.flush();
and see if this helps ?

That’s probably some transient signal that radiates into the RX line of your device and hence will be stuck in the input buffer.
You may want to revisit your wiring to see whether you can prevent that from happening at all, otherwise flushing the RX buffer before you are reading data (particularly when you have no control over the sending side) is never a bad idea.

However, @dreamER’s suggestion, while logical won’t help much here as ‘Serial1.flush()’ only ensures that all bytes stored in the TX buffer will be sent before moving on, but it doesn’t flush the RX buffer.

I’m usually using this to flush the RX buffer

  while(Serial1.read() >= 0); 

As long there are bytes in the buffer you’ll read it out and discard it, once the buffer is empty, the function will return (int)-1 and the loop will be broken.

I tested and can confirm that the begin() call cause this. Since no one seems to experience this it must be the wiring as you say.

1 Like

Me and talybin tried to solve it for a while.

When I test with Electron and read serial1 with FTDI cable 3.3V cable connected to GND/TX, we do not get FF.

But when we use same code when Electron is mounted on Shield Shield V3 ( we get this gibberish char FF every time we call begin(). I use same cable connected to GND/TX.

Can we use something to prevent it from happening?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.