serial read garbage problem

i am a newbie and i want to send a simple integer to arduino via serial communication, i get the value but there is also garbage valuse i don’t understand to reslove it… a little help will be appreciated.

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

void loop()
{
  while (Serial.available() == 0);
  int val = Serial.read() - '0';
  Serial.flush();
  Serial.println(val);
  
}

You have newline sending enabled.

When you send the number '7' for instance, you are actually sending the string "7\n", which is characters 55 and 10. '0' is character 48, so 55 - 48 yeilds 7. However, 10 - 48 yields -38.

thanks it make sense can you tell me how to resolve the new line?

Abubakar022:
thanks it make sense can you tell me how to resolve the new line?

By selecting the option not to send a newline in the serial monitor. The drop-down box that says "Newline" at the moment. Change it.

I hope you aren’t going to want to send more than “9” to the serial port, or you may have to rethink your approach. And you may have to read this:

http://www.gammon.com.au/serial

I'm sure that URL looks somewhat familiar... Haven't I seen it somewhere before?