2

I want to send text over serial monitor to Arduino and make Arduino return that string back to me over serial monitor.

I have made this function which reads from serial input and returns a string object.

String readSerial() {    String input;    while(Serial.available() > 0)        input.concat(Serial.read());    return input;}

In theloop() I have:

if(Serial.available()) Serial.print(readSerial());

If I just do something likeSerial.print("Hello world!"); everything is fine. But, if I try to return string object I get lot's of numbers.

I guessSerial.print doesn't know how to readString object and returns ASCII codes of characters or something?

[update]I have checked it, and it's indeed outputing ASCII codes. ForHi I get72105.

[update]I have updated myreadSerial function to use this :

input += (char)Serial.read();

But now I'm getting carriage return and new line after every character:

[SEND] HiH(CR)i(CR)

So, how can I make it return my text so that is readable?

askedAug 28, 2014 at 21:09
Reygoch's user avatar

2 Answers2

1

String.concat() takes aString as the second argument.Serial.read() returns anint. The compiler creates code that converts theint into aString similar to this:

input.concat(String(Serial.read()));

This is not what you want.

Let's tell the compiler what you really want instead:

input.concat((char)Serial.read());

This will tell the compiler to do the following:

input.concat(String((char)Serial.read()));

We are now having the compiler call the correctString constructor, and the code will work as we expect.

answeredAug 28, 2014 at 21:38
Ignacio Vazquez-Abrams's user avatar
1
  • Yes, just figured that out. Thanks anyway.CommentedAug 28, 2014 at 21:41
0

Answering the other part of the question:

  • you're getting CRs because your readString is just wrong.

The problem is that you don't wait for receiving a whole line of string. For example, if you press H on the serial monitor, then it is getting received and echoed back as if it would been the whole input, ending with a new line.

You might wish to check my answer atGet strings from Serial.read() that is usehttps://www.arduino.cc/en/Serial/ReadStringUntil which reads you the whole string until a separator (for example the whole string until it ends with a CR when you press Enter on the serial monitor).

answeredMar 30, 2016 at 16:51
Gee Bee's user avatar

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.