RPi Quadcopter blog

RPi Quadcopter blog
Click to open

May 25, 2011

Arduino: How to read serial to string

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);
}

5 comments:

  1. Thanks for sharing, it was very helpful! The code worked for me, here's my function:

    String 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";
    }
    }

    ReplyDelete
  2. It worked for me :D Never thought we can use string datatype in arduino. Thanks for sharing

    ReplyDelete