Search code examples
arduinomqttpayload

MQTT receiving sensor data from different topics but coming across in one payload


Presently I have 2 sensor readings arriving as one payload from 2 topics( or it looks that way), what would be the recommended way to split this one payload into 2 variables(temp, humidity);

The sensor readings are from different topics.

I have tried all manner of ways a person with little experience would try from for loops to try and write half the data to the serial monitor but to no avail.

I tried to enter the topic into this function but it would not compile.

void messageReceived(MQTTClient*client, char topic[], char payload[], int payload_length) {
  for (byte i=0;i<6;i++){ 
    Serial.print(payload[i]);
 }
}

the output on the serial monitor would be

23.4555.33

if I put a println after the for loop I get

23.45
55.33

Should I have 2 void messageReceived? one for temp and the other for humidity?

say

messageReceivedtemp()

messageReceivedHum()

Solution

  • You are not receiving a single message, you are receiving separate 2 messages.

    You have 2 problems with your code.

    1. First you are not checking the topic that the message is arriving on, so you do not know which value is which.
    2. You are just passing the values directly to the serial port without checking the length. You are using a fixed value of 6, but you should be using the payload_length value.

    The code should read something like this:

    void messageReceived(MQTTClient*client, char topic[], char payload[], int payload_length) {
    
      if (strcmp(topic, "temp") == 0) {
        //message arrived on the 'temp' topic
        Serial.print("temp: ");
      } else if (strcmp(topic, "hum") == 0 {
        //message arrived on the 'hum' topic
        Serial.print("hum: ");
      }
    
      for (int i=0;i<payload_length;i++){ 
        Serial.print(payload[i]);
      }
      Serial.println();
    }