Go Down

Topic: Program works only for the first time!! (Read 89 times) previous topic - next topic


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!

Code: [Select]
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:

void loop() {

            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);


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
If you understand an example, use it.
If you don't understand an example, don't use it.

Electronics engineer by trade, software engineer by profession. Trying to get back into electronics after 15 years absence.


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
greg - somerset, nj
seeing well written code is the best way to learn to write well written code.

Go Up