-
-
Save farshid616/760ac82a46254e2b2f0c06a5fc8b3ea0 to your computer and use it in GitHub Desktop.
Splitting strings by a delimiter for Arduino
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// This is tested and works! | |
// | |
String input = "123,456"; | |
int firstVal, secondVal; | |
for (int i = 0; i < input.length(); i++) { | |
if (input.substring(i, i+1) == ",") { | |
firstVal = input.substring(0, i).toInt(); | |
secondVal = input.substring(i+1).toInt(); | |
break; | |
} | |
} | |
// | |
// I tested a similar version in JS and it worked | |
// No guarantees!! | |
// | |
// Define number of pieces | |
const int numberOfPieces = 4; | |
String pieces[numberOfPieces]; | |
// This will be the buffered string from Serial.read() | |
// up until you hit a \n | |
// Should look something like "123,456,789,0" | |
String input = ""; | |
// Keep track of current position in array | |
int counter = 0; | |
// Keep track of the last comma so we know where to start the substring | |
int lastIndex = 0; | |
void setup(){ | |
Serial.begin(9600); | |
} | |
void loop() { | |
// Check for data coming in from serial | |
if (Serial.available() > 0) { | |
// Read the first byte and store it as a char | |
char ch = Serial.read(); | |
// Do all the processing here since this is the end of a line | |
if (ch == '\n') { | |
for (int i = 0; i < input.length(); i++) { | |
// Loop through each character and check if it's a comma | |
if (input.substring(i, i+1) == ",") { | |
// Grab the piece from the last index up to the current position and store it | |
pieces[counter] = input.substring(lastIndex, i); | |
// Update the last position and add 1, so it starts from the next character | |
lastIndex = i + 1; | |
// Increase the position in the array that we store into | |
counter++; | |
} | |
// If we're at the end of the string (no more commas to stop us) | |
if (i == input.length() - 1) { | |
// Grab the last part of the string from the lastIndex to the end | |
pieces[counter] = input.substring(lastIndex, input.length()); | |
} | |
} | |
// Clear out string and counters to get ready for the next incoming string | |
input = ""; | |
counter = 0; | |
lastIndex = 0; | |
} | |
else { | |
//if we havent reached a newline character yet, add the current character to the string | |
input += ch; | |
} | |
} | |
// Data is now available in pieces array | |
// pieces[0] is first item | |
// pieces[1] is second item, and so on | |
// You can call toInt() on the data to convert it to an int | |
// ex. int value = pieces[0].toInt(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment