TransWikia.com

Arduino split comma separated serial stream

Arduino Asked on December 28, 2021

I’m trying to read serial data into Arduino.

I usually use a Serial to USB cable to connect to the hardware and is sending data like

33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68
33,Z,35.0,F,1073741.824,I,0.0,0x68

At 38400 bound rate.

I have been reading this post Splitting a comma separated string through serial (Arduino) https://www.arduino.cc/reference/en/language/functions/communication/serial/print/

I have tried to write something my own but none return readable data.

Any tips please?

One Answer

The reference article, that you linked to, is about sending data over Serial, not about reading.

You can use the strtok() function, which can split a character buffer into tokens based on a delimiting character (the comma in your case).

First you have a buffer, where your Serial message in saved (I'm not covering the actual receiving/reading of the Serial data here, because there are tons of tutorials on the web):

char buffer[] = "1,2.3,4,0x56";

Then you can get the first token:

char *token1 = strtok(buffer, ",");

token1 is a pointer to the start of the token. strtok() replaces the found delimiter (which you specify with the second parameter) with a null character. That means, that token1 points to a null terminated C string with only the first token in it (Keep in mind that the buffer is changed with that, so it does not make any sense to try printing buffer after you used strtok()). Note, that this does not create a new buffer. It simply points to a specific place inside buffer.

You could also directly process it, for example convert it to an integer:

int token1_value = atoi(strtok(buffer, ",");

To get the next token, you simply again call strtok(), but now you provide NULL instead of buffer in the first parameter. That tells strtok(), that you still want to process the same buffer from the last execution.

float token2_value = atof(strtok(NULL, ",");

You can now do this, until no token is left unprocessed in the buffer. In that case strtok() returns NULL.

char *token = strtok(NULL, ",");
while(token != NULL){
    Serial.println(token);
    token = strtok(NULL, ",");
}

Have a look at the C++ reference for strtok(). It also includes an online editor, where you can run the provided example and play with it.

Answered by chrisl on December 28, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP