Serial.read() function reading additional data

Hello everyone,

So I just got my first Arduino yesterday and have been trying out hello world kind of applications on it (I got an Arduino Uno).

I decided to try out the serial functionalities of the board. I wrote the following code:

void setup() {

  Serial.begin(9600);
  
}

void loop() {

  while(Serial.available() == 0); // Waits for serial to be available

  int x = Serial.read(); // Reads an input

  Serial.println(x);
  
}

I then ran this code and everything was compiled and uploaded fine.

However every time I input a number (from 0 to 9), the number 10 gets printed on a new line.

Here is an example:

  • Input: 1

Output: 49 // This one is expected, it's the decimal value of the char '1'
10 // Where does this come from?

  • Input: 2

Output: 50
10

  • Input: 3

Output: 51
10

I then tried to print a normal String using the Serial.print("Hello") but this time everything was printed right.

Does anyone know where this problem comes from? I have no idea.

Thanks for your help.

The 10 is coming from the Line Feed Character that's being sent by the serial monitor.

What you should do instead is change Serial.println(x); to Serial.write(x); and you should be good to go!

Thanks a lot

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R