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?

Greenonline
3,1527 gold badges36 silver badges48 bronze badges
asked Mar 29, 2016 at 23:03
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.

answered Mar 29, 2016 at 23:40
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="";
Greenonline
3,1527 gold badges36 silver badges48 bronze badges
answered Mar 30, 2016 at 5:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.