Random character in serial Monitor at beginning of Serial.begin

Dear all,
I am following the example : Basics/ReadAnalogVoltage

However, when the serial monitor starts, it sometimes writes the random characters (or something my computer does not recognise).

This harms the ability that I use Python (pyserial) to read my serial port..

I realise setting a delay after Serial.begin helps, but this does not fully prevent it to happen.

Wondering whether anyone has a fix for this.

When you start the monitor it resets your Arduino.

If your Arduino was in the middle of sending data when it was reset, the last bits of data might make it through to the monitor.

As the monitor could have started in the middle of a byte transfer, the bits are in the wrong position and the monitor sees bytes which represent the characters you are seeing.

You should implement some error control, like packets with a known preamble, so your python app can discard data until it sees a known pattern.

or just flush the serial monitor before reading the data.
Serial.flush();

I'm quite sure that flush will do nothing as the serial TX buffer is indicated as being empty in the HardwareSerial code after reset.

I agree with pyRo_65 to implement a simple protocol. Like explained in the Serial Input Basics - updated thread.

Send e.g <3.01> from Arduino to PC. Your Python app should discard all data till it receives '<', read the other data till it receives '>'

tiantianisfox:
Wondering whether anyone has a fix for this.

I'm wondering which Arduino board you are using to create the problem.

jurs:
I'm wondering which Arduino board you are using to create the problem.

Hi I am using Arduino Nano for the project

tiantianisfox:
Hi I am using Arduino Nano for the project

Please make sure that the USB serial adapter pins on the board (pin-0 / pin-1) are not connected to anything!

Instead of a delay within the setup

 Serial.begin(19200);
  delay(1000);

I'd more likely try to close and reopen Serial immediately:

 Serial.begin(19200);
  Serial.end();
 Serial.begin(19200);

Does that make a difference or not?

This might do the job! :slight_smile:
For now it stop giving me random characters. However, the problem does not always occur. I will give it some time to see whether this is the right hack.

Cheers!

Why don't you precede each valid message to the monitor with a known preamble, even one character like '*' that otherwise does not occur in your data stream. Then only grab data from the monitor starting past the preamble symbol.