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