1

Hello I found an Arduino project that works with serial port parsing and it had very interesting parsing code. I am trying to use it in my project but I still don't understand some lines and what is going there. (I marked them with ???).

char inData[82]; //create 82 char array
byte index = 0; //index byte (0 - 255)
String string_convert; //String
int PCdata[20]; //int array

void setup() {
  Serial.begin(9600); //init port
}

void loop() {
  parsing(); //loop the function
}

void parsing() {
  while (Serial.available() > 0) {
    //while there is data in serial buffer (128 bytes)
    char aChar = Serial.read(); //aChar - current symbol in buffer
    if (aChar != 'E') {
      //if aChar isnt the 'E' (End) symbol do:
      inData[index] = aChar;
      //(inData - array, index - loop № counter) write all Buffer to the array
      index++; //index + 1 - loop count
      inData[index] = '\0';
      //set the next position to '\0' or null symbol
    } else {
      //if aChar or current buffer symbol is 'E' (End) do:
      char *p = inData; //create inData address pointer
      char *str; //create pointer
      index = 0; //set counter to 0
      String value = ""; //create string
      while ((str = strtok_r(p, ";", &p)) != NULL) { //???
        string_convert = str; //???
        PCdata[index] = string_convert.toInt(); //???
        index++; //counter + 1 - loop count
      }
      index = 0; //counter to 0
    }
  }
}

Thank you for help!

1

It's parsing a bunch of semi-colon separated data, like "12;34;45;". In each iteration, it converts one value from character representation to its integer value.

strtok_r is the reentrant version of strtok. On Arduino you simply use strtok. Every time you have to parse a string having a list of values separated by some char, you use strtok.

Name

strtok, strtok_r - extract tokens from strings

Synopsis

#include <string.h>

char *strtok(char *str, const char *delim);

char *strtok_r(char *str, const char *delim, char **saveptr);

The strtok() function parses a string into a sequence of tokens (sub-strings). On the first call to strtok() the string to be parsed should be specified in str. In each subsequent call that should parse the same string, str should be NULL.

Each call to strtok() returns a pointer to a null-terminated string containing the next token. This token does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.