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?
-
1Read this: hackingmajenkoblog.wordpress.com/2016/02/01/…Majenko– Majenko2016年03月29日 23:10:52 +00:00Commented Mar 29, 2016 at 23:10
2 Answers 2
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.
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="";