I’m trying to pass multiple parameters into a spark function and I’m having trouble parsing the String class to extract each of the parameters. I’ve been trying to make the function parse the parameters passed in CSV format, but I’m flexible on how this gets done. Here is the code I’ve worked up so far:
//Ramp mode controls
int setRampMode(String args) {
//Expected parameters in CSV format
// 1. Ramp Start Temp
// 2. Ramp End Temp
// 3. Ramp Time (days)
args.trim();
String delimit = ",";
String empty = "";
//this will keep track of where we are in the argument list
int arg_position = 1;
for (int i = 1; i <= 3; i++) {
String val = args.substring(0,args.indexOf(delimit));
args.replace(val,empty);
args.substring(1,args.length());
args.trim();
if (arg_position == 1) {
rampStart = atof(val.c_str());
} else if (arg_position == 2) {
rampEnd = atof(val.c_str());
} else if (arg_position == 3) {
rampDays = atof(val.c_str());
}
arg_position++;
}
//modeSta = 2;
rampSta = millis();
return 1;
}
A sample call to this function with ‘args=77,68,1’, parses as 7.0, 0.0 and 81.0.
Here is some similar code that I wrote for another project here in the forum that copies to C char * array and uses C string functions to parse the format “08:56:05*6000” into the parts 8, 56, 5, and 6000, storing these away in arrays and noting that this entry is now valid (isSet[] set to true).
// Parse the format: 08:56:05*6000 or 18:59:00*10
// hh:mm:ss*duration
char copyStr[64];
command.toCharArray(copyStr,64);
char *p = strtok(copyStr, ":");
startHours[relay] = (uint8_t)atoi(p);
p = strtok(NULL,":");
startMinutes[relay] = (uint8_t)atoi(p);
p = strtok(NULL,":");
startSeconds[relay] = (uint8_t)atoi(p);
p += 3;
duration[relay] = atoi(p);
isSet[relay] = true;
If you change this to use “,” as the delimiter and change the last section (p+=3;…) you could easily get your result. You can also put a loop around it, testing p for NULL to end the loop.
What this does in English is look for the first “:” and convert the characters between the start of the string and that first “:” to an uint_8 integer, then look for the next “:” etc. finally skipping the the final “05*” to point to the last part of my string, “6000” in the example. strtok “remembers” where you left off and you call it with NULL the second and third times to get the next delimiter.
I know this is a bit complicated but I hope this helps.