Whierd Serial Communication Problem

Hello there!

Today I got a very weird issue while trying to test the Serial Communication for another project.

First of all: I’m using an Arduino Mega (JOY-IT Clone) hooked up via usb and this is basically my code:

void setup() {
  
  Serial.begin(9600);

  Serial.flush();
  Serial.println("Ready");

}

void loop() {
  
  if (Serial.available() > 0) {
    Serial.println(Serial.available());  //just for debugging
    Serial.println(Serial.parseInt());   //printing the entered number
    Serial.println(Serial.available());  //just for debugging
  }
  
}

I would have expected something like this when I sent for example 4 through the serial monitor:

1
4
0

But If I type in any number I get:

1

1
1

And after a delay of a half to a full second it adds:

0
0

So the total output is:

1

1
1
0
0

I can’t explain to me how this happens and didn’t found anything on the internet like this

Pls reply soon
Xilef

This is because the Serial Monitor is adding some line ending characters to the data you typed into the input field. You can change this behavior via the line ending menu at the bottom of the Serial Monitor. If you set it to "No Line Ending", it will work as you expect.

XilefTech:   Serial.flush();

You might want to read the documentation for Serial.flush() so you will understand what it does: https://www.arduino.cc/reference/en/language/functions/communication/serial/flush

You may find this link useful

Serial Input Basics - simple reliable ways to receive data.

...R

Thanks for the quick replies!

Your suggestions solved my problem!

Thanks a lot!

Xilef

You're welcome. I'm glad to hear it's working now. Enjoy! Per