arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
187 stars 73 forks source link

Var type error #17

Closed Antonzlo closed 4 years ago

Antonzlo commented 4 years ago

Hello! I want to create smart IoT lamp. But, if I try to use if() function, I do not understand results. My loop function:

void loop() {
  int messageSize = mqttClient.parseMessage();
  if (messageSize) {
    // we received a message, print out the topic and contents
    Serial.print("Received a message with topic '");
    Serial.print(mqttClient.messageTopic());
    Serial.print("', length ");
    Serial.print(messageSize);
    Serial.println(" bytes:");

    // use the Stream interface to print the contents
    while (mqttClient.available()) {
      Serial.print(String(mqttClient.read()));
    }
    if (String(mqttClient.read()) == String(48)){
      digitalWrite(ledPin, HIGH);
      Serial.println(" tru");
      } else {
      digitalWrite(ledPin, LOW);
      Serial.println(" fals");
    }
    Serial.println();

    Serial.println();
  }
}

In serial, I do receive values, but cant compare them in if(): image

sandeepmistry commented 4 years ago

Hi @Antonzlo,

// use the Stream interface to print the contents
    while (mqttClient.available()) {
      Serial.print(String(mqttClient.read()));
    }
    if (String(mqttClient.read()) == String(48)){

This won't work, because when you loop though the data, the first time, mqttClient.read() will return -1 because the data is all read.

I would suggest:

String data = mqttClient.readString();

if (data.length() == 1 &&  data[0] == 48){
  // ...
} else {
  // ...

Please let us know if you still have issues. I'll close this issue for now, as I think I've answered your concerns.