1

After I take a char* variable from serial communication, I use strtok to split variables with " ". But when I do that it acts like there is a " " after every character. I dont know why. How can I fix this ?

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  char* a = "The quick brown fox jumped over the lazy dog.";
  char* c = a3;
  char* b;
  b = strtok(c, " ");
  while (b != NULL) {
    Serial.println(b);
    b = strtok(NULL, " ");
  }
}

void loop() {
}

outcome:

The
quick
brown
...

This parsing code works perfectly, until I take it from serial ports. Serial code here, like this:

#include <SoftwareSerial.h>
#define bRSerial 9600
#define bRmY 9600

char vD[45];
int i = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  Serial.begin(bRSerial);
  while (!Serial) {
    ;
  }
  mySerial.begin(bRmY);
}

void loop() {
  if (mySerial.available()) {
    //Serial.write(mySerial.read());
    vD[i]=mySerial.read();
    i++;
    if (i = 46) {
      char* a = vD;
      char* b;
      
      b = strtok(a, " ");
      while (b != NULL) {
        Serial.println(b);
        b = strtok(NULL, " ");
      }
      i=0;
    }
  }
}

outcome:

T
h
e
q
u
i
c
k
b
r
o
w
...

Is there a way to fix this? i need to get it from serial and split on " ".

6
  • 2
    if ( i == 46 ) {
    – Juraj
    May 4, 2018 at 12:56
  • yep that was it. :D simply 1 mistake that i couldnt see thanks. May 4, 2018 at 13:01
  • is this how you plan to use it or only a test? it would be simpler to detect the delimiter when it is read
    – Juraj
    May 4, 2018 at 13:05
  • i dont know how to use it simplier. May 4, 2018 at 13:10
  • if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0 else vD[i] = c
    – Juraj
    May 4, 2018 at 13:17

2 Answers 2

3

only a syntax typo. the condition should be if ( i == 46 ) {

if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0

and I do not see where you set the terminating 0 of vD a.k.a. a

0

As @Juraz mentioned, in the case you have a typo. Also I'd have suggestions as one who had spent a while coding reading process in terminal. When you need to read something from a serial port it is good to use the while() loop, instead of if(), so I recommend changing:

while (mySerial.available()) {
  //Serial.write(mySerial.read());
  vD[i]=mySerial.read();
  i++;
  if (i == 46) {
    char* a = vD;
    char* b;

    b = strtok(a, " ");
    while(b != NULL) {
      Serial.println(b);
      b = strtok(NULL, " ");
    }
    i=0;
  }
}
1
  • 1
    the if is in loop()
    – Juraj
    Jul 24, 2022 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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