Go Down

Topic: serial read garbage problem (Read 432 times) previous topic - next topic

Abubakar022

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.

Code: [Select]
void setup()
{
  Serial.begin(9600);
}

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



majenko

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.
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Nick Gammon

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

Abubakar022

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

majenko


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.
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Nick Gammon

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
http://www.gammon.com.au/electronics

majenko


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?
Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

Go Up