String reserves a lot of memory for it self. Avoiding string type variables is a good idea. This example is good for debugging purposes when you don’t know how long strings you are sending to arduino. when your code becomes longer and you know how long strings you are sending, use char[20].
String inData;
void setup()
{
Serial.begin(115200);
}
void loop(){
inData="";if (Serial.available() > 0) {
int h=Serial.available();
// if you are getting escape -characters try h--; here
for (int i=0;i<h;i++){inData += (char)Serial.read();
}
// if you are getting escape -characters try Serial.read(); here
}
//print it out
Serial.println(inData);
}
do not works
ReplyDeleteThanks for sharing, it was very helpful! The code worked for me, here's my function:
ReplyDeleteString readSerial() {
inData = "";
if (Serial.available() > 0) {
int h = Serial.available();
for (int i = 0; i < h; i++) {
inData += (char)Serial.read();
}
return inData;
}
else {
return "No connection";
}
}
Good work! Thank you.
DeleteIt worked for me :D Never thought we can use string datatype in arduino. Thanks for sharing
ReplyDeleteThanks, It worked for me.
ReplyDelete