Split string datetime from bluetooth read

Hello im trying to split this string "2022,12,7,6,33" from bluetooth serial but the output is splitting it all

char c[] = {bluetoothSerial.read()};
    char *strings[6];
    char *ptr = NULL;

    byte index = 0;
    ptr = strtok(c, ",");  // delimiter
    while (ptr != NULL)
    {
        strings[index] = ptr;
        index++;
        ptr = strtok(NULL, ",");
    }
    for (int n = 0; n < index; n++)
    {
        Serial.print(n);
        Serial.print("  ");
        Serial.println(strings[n]);
    }

OUTPUT

0 2
0 0
0 2
0 2
0 1
0 2
0 7
0 6
0 3
0 3

This is what i need to achieve

0 2022
1 12
2 7
3 6
4 33

Hello

Currently, your code is reading only one character, then doing strtok, then reading another character, etc, hence why n is always 0 and the string is only one character.

You must store characters until the end of the string, which is probably delimited by a \n character, before using strtok

Hello still cant figure it out how to store the char to string

The easiest way is to use readStringUntil and then use c_str in strtok

There are better ways : Serial Input Basics - updated

consider

output:

2022,12,7,6,33
2022
12
7
6
33

code:


char  buf [80];
char *toks [20];
int   nToks;

void loop()
{
    if (Serial.available ())  {
        int n = Serial.readBytesUntil ('\n', buf, sizeof(buf)-1);
        buf [n] = '\0';

        Serial.println (buf);

        nToks = 0;
        toks [nToks++] = strtok (buf, ",");
        for ( ; NULL != (toks [nToks] = strtok (NULL, ",")); nToks++)
            ;

        for (int n = 0; n < nToks; n++)
            Serial.println (toks [n]);
    }
}

void setup()
{
    Serial.begin (9600);
}

It works thank you, but can you please explain what buf[80] and toks [20] do? or the whole code, id really appreciate it

Read link in #4 for background.

buf [] is a char array used to captured the received input chars into . toks [] is an array of char pointers.

readBytesUntil() captures input chars up to the '\n' and returns the # of the received chars. buf [n] = '\0' replaces the last char, the '\n' with a NULL making is a properly terminated c-string

strtok() is given an c-string and a delimiter string, ",", and returns char pointers into that c-string for sub-strings delimited by the delimiter string. it replaces the delimiter string with NULL(s)

strtok() is unusual in that it remembers the c-string it was initially called with and continues to operate on when subsequently called with a NULL. it returns a char pointer the next sub-string following the last delimiter string until it gets to the end of the original c-string and returns NULL

tok [] contains the char pointers to each of the sub-strings in the original c-string/char array which now has several NULLs.

Thank you so much :clap: