How to Parse Comma Separated Values in Arduino Easily
To parse comma separated values in Arduino, use the
String class with indexOf() and substring() methods to find commas and extract each value. Alternatively, use String::split() if available or manually loop through the string to separate values by commas.Syntax
Parsing comma separated values involves finding commas in a string and extracting parts between them.
Key methods:
indexOf(","): Finds position of next comma.substring(start, end): Extracts part of string between two positions.toInt()ortoFloat(): Converts extracted string to number if needed.
arduino
int commaIndex = input.indexOf(","); String firstValue = input.substring(0, commaIndex); String secondValue = input.substring(commaIndex + 1);
Example
This example reads a CSV string and prints each value separately.
arduino
void setup() { Serial.begin(9600); String csv = "23,45,67"; int startIndex = 0; int commaIndex = csv.indexOf(","); while (commaIndex != -1) { String value = csv.substring(startIndex, commaIndex); Serial.println(value); startIndex = commaIndex + 1; commaIndex = csv.indexOf(",", startIndex); } // Print last value after last comma Serial.println(csv.substring(startIndex)); } void loop() { // Nothing here }
Output
23
45
67
Common Pitfalls
Common mistakes when parsing CSV in Arduino include:
- Not updating the start index after finding a comma, causing infinite loops.
- Forgetting to print or process the last value after the last comma.
- Assuming fixed number of values without checking for missing commas.
- Using
char*functions incorrectly without null termination.
arduino
/* Wrong way: Missing update of startIndex causes infinite loop */ void wrongParse(String csv) { int commaIndex = csv.indexOf(","); while (commaIndex != -1) { String value = csv.substring(0, commaIndex); Serial.println(value); // Missing startIndex update here commaIndex = csv.indexOf(","); } } /* Right way: Update startIndex to move forward */ void rightParse(String csv) { int startIndex = 0; int commaIndex = csv.indexOf(","); while (commaIndex != -1) { String value = csv.substring(startIndex, commaIndex); Serial.println(value); startIndex = commaIndex + 1; commaIndex = csv.indexOf(",", startIndex); } Serial.println(csv.substring(startIndex)); }
Quick Reference
- indexOf(","): Find comma position.
- substring(start, end): Extract value between commas.
- toInt()/toFloat(): Convert string to number.
- Always handle last value after last comma.
Key Takeaways
Use String methods indexOf() and substring() to split CSV strings in Arduino.
Always update the start index after each comma to avoid infinite loops.
Remember to process the last value after the final comma.
Convert extracted strings to numbers with toInt() or toFloat() if needed.
Test with different CSV lengths to ensure robust parsing.