1

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?

1

2 Answers 2

6

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.

2

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="";

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.