Go Down

Topic: Efficient method to split comma-separated values? (Read 1 time) previous topic - next topic

davivid

The outptut from my PC to the Arduino via Serial is something like <1023,0,511,1023,0,1032> but about 30 values long.

The following code captures complete packets starting with < and ending with >, and then splits the comma-separated values and stores them in array colours.

I am curious as to how other people do this, is my code ok?, how can it be improved?

Code: [Select]
//vars for Serial packet recieve
#define SOP '<'
#define EOP '>'

boolean started = false;
boolean ended = false;

char inData[80];
byte index;

//Vars to process packet
int colours[30] = {0};
char * val;
int count = 0;

void loop()
{
while(Serial.available() > 0)
{
char inChar = Serial.read();

if(inChar == SOP)
{
index = 0;
inData[index] = '\0';
started = true;
ended = false;
}
else if(inChar == EOP)
{
ended = true;
break;
}
else
{
if(index < 79)
{
inData[index] = inChar;
index++;
inData[index] = '\0';
}
}
}
  // We are here either because all pending serial
  // data has been read OR because an end of
  // packet marker arrived. Which is it?
  if(started && ended)
  {
val = strtok (inData,",");

colours[count] = atoi(val);

while ((val = strtok (NULL, ",")) != NULL)
{
colours[++count] = atoi(val);
}

// Reset for the next packet
started = false;
ended = false;
index = 0;
inData[index] = '\0';
  }
}

PaulS

Quote
is my code ok?

Yes, it is.

Quote
how can it be improved?

You could re-implement strtok(). But, why?

davivid

Quote

You could re-implement strtok(). But, why?


Because I more or less guessed to do it that way and would like to improve if I can! in what sort of way would you have done it?

el_supremo

Quote
but about 30 values long

If you have 30 values within < and > then an 80 byte string is too short to hold them all. Assuming that the maximum integer is 4 characters, the whole string can be 152 characters long.
Your code won't blow up if the received string is too long but it throws away everything after the 79th character including the > character, so it won't process the input.



Pete

PaulS

Quote
in what sort of way would you have done it?

I know a little about the development cycle for code, and the amount of testing that goes into functions delivered in the C library, where strtok() is delivered. Knowing that the code was professionally developed, peer reviewed, and extensively tested, I would not begin to think that I could do a better job, using fewer resources, executing faster. I would, therefore, have used the strtok() function.

Go Up