Program works only for the first time!!

Hello to all , hope have good day.
The last to days I have stack with my following code. I illustrate a part of my code that I face the problem.
The following part of the code it's a simple example of strtok() function that I found on this website.

If I run this code only for one time on Arduino everything seems to work fine. The problem is that is I try to run it continuously on void loop then I only get only the first value. Also it doesn't even print the array message. Does it need to malloc any size of memory and then free it? Because it seems to me like the array loose it's position. I also attach a screenshot of Serial monitor;

Thanks' in advance!

char receivedChars[100] = {"34R3,144326.00,H,5107.0017737,H,11402.3291611,A20"};
char* token;
const char s[2] = ",";

void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
}

void loop() {
  
            Serial.print(receivedChars);Serial.println();

            token = strtok(receivedChars,s);
            Serial.print("Token is: ");Serial.println(token);
            while( token != NULL)
            {
              token = strtok(NULL,s);
              Serial.print("Token is: ");Serial.println(token);
            }
            delay(100);
}

strtok() is destructive; it replaces the characters that you search for by '\0'. So if loop()is called again, i will only find the first part.

As you usually only process receivedChars once a new message is received, you can ignore the problem. Else you can write your own implementation that doesn't destroy the original. Or make a copy first as is done in Serial Input Basics

a common approach it to capture the locations of each token found by strtok() in an array of char ptrs and that array processed subsequently. yes, strtok() must be passed a NULL pointer after the first invocation

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.