How to receive message in array? Convert byte to String array?

How to convert from byte to string array.
I am using mqtt to send the message (data array) from raspberry pi to esp8266. This is how esp8266 receive. So I need help to receive the array. I try to convert but it's still error.
Here is a part in my code:

String abc, dfs, rer, fdfs;

String Data[ ]={abc, dfs, rer, fdfs};

void callback(String topic, byte* message , unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
topic == "submit
if messageTemp == Data){
Serial.print( abc );
}
}

Not really sure what you are trying to do but this sketch works

BUT it assumes that in the callback the argument
byte* message
is '\0' terminated.
What library are you using for the MQTT?
You need to check the library code to see if the byte* message is '\0' terminated

//https://forum.arduino.cc/t/how-to-receive-message-in-array-convert-byte-to-string-array/878663
String abc("abc"), dfs("dfs"), rer("rer"), fdfs("fdsf");
String Data[ ] = {abc, dfs, rer, fdfs};

void setup() {
  Serial.begin(115200);
  for (int i = 10; i > 0; i--) {
    Serial.print(i); Serial.print(' ');
    delay(500);
  }
  Serial.println();
  //void callback(String topic, byte* message , unsigned int length) {
  for (size_t i=0; i<sizeof(Data)/sizeof(String); i++) {
    Serial.println(Data[i]);
  }
  const char message[] = "abc";
  Serial.print("Message arrived on topic: ");
  String topic = "submit";
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
  messageTemp = message;
  Serial.println();
  Serial.print("Got msg:");Serial.println(messageTemp);
  if (messageTemp == Data[0]) {
    Serial.print( abc );
  }
}
void loop() {
}
1 Like

Oops

I use <PubSubClient.h> and <ESP8266WiFi.h>

if the message array is ASCII, just print it

1 Like

...assuming it is correctly terminated.

1 Like

Can we receive a whole array at the same time and take each of them to Serial.print.

I also try this with arrays of integer and float. :sweat_smile: :confused:

Looks like it is terminated
this->buffer[llen+2+tl] = 0; /* end the topic as a 'C' string with \x00 */
in PubSubClient.cpp

So you can just assign to a String

  String messageTemp;
  messageTemp = message;

and work from there.

1 Like

Thanks a lot everyone.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.