I new in Arduino! I have two topics on MQTT server, "arduino/temp" and "arduino/humid". On Arduino, I want to store in a two diferent variable, payload of this topics("arduino/temp" and "arduino/humid")
My code is here:
char myTemp[5];
char myHum[5];
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
// if(strcmp(topic, "arduino/temp") == 0) {
if (String(topic) == "arduino/temp") {
Serial.println(strcmp(topic, "arduino/temp") == 0);
Serial.print("Message:");
for (int i = 0; i < length; i ) {
Serial.print((char) payload[i]);
myTemp[i] = (char) payload[i];
}
Serial.println();
Serial.println(myTemp);
Serial.println("-----------------------");
}
else {
Serial.println(strcmp(topic, "arduino/humid") == 0);
Serial.print("Message:");
for (int i = 0; i < length; i ) {
Serial.print((char) payload[i]);
myHum[i] = (char) payload[i];
}
Serial.println();
Serial.println(myHum);
Serial.println("-----------------------");
}
}
I get correct payload, but i can't asign corectlly to an variablle. This is the result:
13:08:34.741 -> Message arrived in topic: arduino/temp
13:08:34.741 -> 1
13:08:34.741 -> Message: 21.30
13:08:34.741 -> 21.30
13:08:34.741 -> -----------------------
13:08:35.670 -> Message arrived in topic: arduino/humid
13:08:35.670 -> 1
13:08:35.670 -> Message: 43.30
13:08:35.670 -> 43.3021.30
13:08:35.670 -> -----------------------
Can you help me, please?
CodePudding user response:
A quick fix is adding one more char to both and setting its value to '\0'
. This character you are missing is called the null terminator which will let the println()
function know that your string has ended.
char myTemp[6];
char myHum[6];
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
if (String(topic) == "arduino/temp") {
Serial.println(strcmp(topic, "arduino/temp") == 0);
Serial.print("Message:");
for (int i = 0; i < length; i ) {
Serial.print((char) payload[i]);
myTemp[i] = (char) payload[i];
}
myTemp[5] = '\0';
Serial.println();
Serial.println(myTemp);
Serial.println("-----------------------");
}
else {
Serial.println(strcmp(topic, "arduino/humid") == 0);
Serial.print("Message:");
for (int i = 0; i < length; i ) {
Serial.print((char) payload[i]);
myHum[i] = (char) payload[i];
}
myHum[5] = '\0';
Serial.println();
Serial.println(myHum);
Serial.println("-----------------------");
}
}
Note: you can also test by adding the extra char only and not setting the value up as some compilers will set it to 0 by default.