I am trying to parse multiple characters using "," as a delimiter, but when i read serial data it takes each character one at a time, here is the code:
if(Serial.available()){
while(Serial.available()){
// clear the serial buffer
char sz[] = {Serial.read()};
char *str;
char *p = sz;
while ((str = strtok_r(p, ",", &p)) != NULL) // Don't use \n here it fails
{
Serial.println(str);
Serial.println("Location");
}}
while (Serial.available() > 0){ junk = Serial.read() ; }
}
it returns the below output when the input is (will,4,7)
w
Location
i
Location
l
Location
l
Location
4
Location
7
Location
strtok() operates on a string, not a char and the string ptr argument needs to be set to NULL on subsequent calls. for your case, the re-entrant version isn't needed.
consider the following code that produces the following with "1,2,3,4" as input and the serial monitor configured to terminate strings with \n
Location 1
Location 2
Location 3
Location 4
char s [80];
int idx = 0;
void
loop ()
{
if (Serial.available ()) {
char c = Serial.read ();
s [idx++] = c;
if ('\n' == c) {
s [idx-1] = '\0';
idx = 0;
char *str;
char *p = s;
for (p = s; (str = strtok (p, ",")); p = NULL) {
Serial.print ("Location ");
Serial.println (str);
}
}
}
}
void
setup ()
{
Serial.begin (9600);
}
yes, you code reads one character at a time.
so your code needs to append each received character onto a string and once a complete string is received (i.e. terminated with \n), strtok() can process it.
actually i have this code that works but without a serial readout, can you please explain to me how it works, i don't really know much about these topics
works on my Uno using the serial monitor. i see your doing something with SoftwareSerial.
in the code with "will,this,work", strtok() is passed a string.
in your original code, you read a single character from the serial port, read(), into a char variable, sz, (not a string). the code then invokes strtok() with a ptr to the single character and it does this for each character received from the serial interface. strtok() never see a string, just a char
as you know, the first argument to strtok() is a ptr to the string to tokenize. the first part of the for initializes the ptr.
and as you know, strtok() should be called again as long as it returns a non-null value, the 2nd part of the for loop.
but that ptr should be set to null after the first call to strtok, and that's the 3rd part of the for loop. (obviously i've had to think about this before)