1

I'm making a NodeMCU based home automation. I adapted code I found on internet for controlling a device (say LED) via MQTT broker hosted on a Raspberry Pi. It works fine. But when I try to scale it up for more than one device, I'm hitting a wall.

void callback(char* topic, byte* payload, unsigned int length)
{
  
  const char* t_bedroom_light1 = "/home/bedroom/light1";
  
  Serial.print("Topic from MQTT broker is : ");
  Serial.print(topic);
  char p = payload[0];

  // if MQTT comes a 0 turn OFF pin D4
  if (topic == "/home/bedroom/light1" && p == '0')
  {
    digitalWrite(LIGHT_PIN, LOW);
    Serial.println(" Turn Light Off! ");
  }

  // if MQTT comes a 1, turn ON pin D4
  if (topic == "/home/bedroom/light1" && p == '1')
  {
    digitalWrite(LIGHT_PIN, HIGH);
    Serial.println(" Turn Light On! " );
  }
}

Serial monitor receives and prints the topic correctly from MQTT server. But topic == "/home/bedroom/light1" never returns true. If I delete that part then p =='0' or p=='1' works fine by itself. I've tried comparing the topic with the locally declared char array, tried converting it into String and doing strcmp. Nothing. What am I doing wrong? Here is the Serial monitor output

12:43:20.346 -> .......
12:43:24.187 -> WiFi connected
12:43:24.187 -> IP address: 
12:43:24.187 -> 192.168.1.5
12:43:24.187 -> Attempting MQTT connection...connected
12:43:30.752 -> Topic from MQTT broker is : /home/bedroom/light1

1 Answer 1

1

That's not how you compare C strings.

When you write

if (topic == "/home/bedroom/light1")

you're comparing whether the character pointer topic is the same value as the address of the string "/home/bedroom/light1", which of course it is not in this case.

To compare C strings, use the strcmp() function, which returns 0 if they're identical.

if (strcmp(topic, "/home/bedroom/light1") == 0 && p == '0')
3
  • Ty, that worked! The noob in me didn't know char arrays were Strings. I had actually tried casting the char array to a new String and used strcmp on that but for some reasons that didn't work. Commented Feb 20, 2021 at 10:51
  • 1
    Actually, char arrays are not Strings (note the capital S), but c-strings, which is a significant difference. Strings shouldonly not be used in devices, with limited memory (or only verys sparingly) while c-strings (char arrays) do not exhibit the same problems. Commented Feb 20, 2021 at 16:40
  • What @StarCat said. Unfortunately C strings also let you shoot yourself in the foot very easily. It's definitely one of the less intuitive parts of C unless you're coming to C from assembly language programming :) Commented Feb 20, 2021 at 16:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.