Split message from mqtt topic


I work on a project where I subscribe to mqtt topic using arduino due.

What I did so far and is working is this

void callback(char* topic, byte* payload, unsigned int length) {
  if ((char)payload[0] == '1') {
if ((char)payload[0] == '0') {

If I send 1 to the topic then I power a led and if I send 0 then I turn it off.

My question is how can I read a message like : "s01|2350" ? Where s01 is a senzor and 2350 is a value for tare it?


My question is how can I read a message like : "s01|2350" ?

"Read" it from where? Is that the contents of payload?

If it is, you know the length of the "string". It's the value in length.

The difference between payload and a string is that a string is a NULL terminated array of chars and payload is a non-NULL terminated array of bytes. Well, bytes and chars are the same size, and any valid char value will fit in a byte or a char. So, the type doesn't matter. And, adding a NULL is trivial.

So, your question is really "How can I parse payload?". There are plenty of sites on the internet that discuss string parsing. strtok() is function to use.

Now, the compiler will probably complain that payload is not a char *, but it is safe to lie to the compiler, and tell it that payload IS a char * by using

   char *token = strtok((char *)payload, ...

Thanks a lot