Arduino (C language) parsing string with delimiter (input through serial interface) Arduino (C language) parsing string with delimiter (input through serial interface) c c

Arduino (C language) parsing string with delimiter (input through serial interface)


To answer the question you actually asked, String objects are very powerful and they can do exactly what you ask. If you limit your parsing rules directly from the input, your code becomes less flexible, less reusable, and slightly convoluted.

Strings have a method called indexOf() which allows you to search for the index in the String's character array of a particular character. If the character is not found, the method should return -1. A second parameter can be added to the function call to indicate a starting point for the search. In your case, since your delimiters are commas, you would call:

int commaIndex = myString.indexOf(',');//  Search for the next comma just after the firstint secondCommaIndex = myString.indexOf(',', commaIndex + 1);

Then you could use that index to create a substring using the String class's substring() method. This returns a new String beginning at a particular starting index, and ending just before a second index (Or the end of a file if none is given). So you would type something akin to:

String firstValue = myString.substring(0, commaIndex);String secondValue = myString.substring(commaIndex + 1, secondCommaIndex);String thirdValue = myString.substring(secondCommaIndex + 1); // To the end of the string

Finally, the integer values can be retrieved using the String class's undocumented method, toInt():

int r = firstValue.toInt();int g = secondValue.toInt();int b = thirdValue.toInt();

More information on the String object and its various methods can be found int the Arduino documentation.


Use sscanf;

const char *str = "1,20,100"; // assume this string is result read from serialint r, g, b;if (sscanf(str, "%d,%d,%d", &r, &g, &b) == 3) {    // do something with r, g, b}

Use my code here if you want to parse a stream of string ex: 255,255,255 0,0,0 1,20,100 90,200,3Parsing function for comma-delimited string


Simplest, I think, is using parseInt() to do this task:

void loop(){    if (Serial.available() > 0){        int r = Serial.parseInt();        int g = Serial.parseInt();        int b = Serial.parseInt();    }}

does the trick.