Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to read strings from Serial.read() to send them later.

To get the data from the Serial monitor I'm doing this:

String stringOne  = "";
int  incomingByte; 

if (Serial.available() > 0) {   

  while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

  Serial.println(stringOne);
  stringOne = "";

The issue is that when I type:

'a'

I got:

'97'

for 'abc'

I got

'979899'

so on and so forth.

What should I do in order to get the same string I type?

share|improve this question
1  
up vote 6 down vote accepted

You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at: https://www.arduino.cc/en/Tutorial/StringConstructors

Either cast the read byte to a char:

stringOne = String(stringOne + String((char)incomingByte));

or consider receiving characters as chars, instead of ints:

char incomingByte; 

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil

Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.

share|improve this answer

Instead of using:

while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

Use the following to cast them to character:

while(Serial.available() > 0)
  {
     char incomingByte= Serial.read();
     stringOne.concat(incomingByte));
  }
Serial.println(stringOne);
stringOne="";
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.