I am trying to control LED via mqtt
I am following this link https://www.emqx.com/en/blog/esp8266-connects-to-the-public-mqtt-broker
Here is my code
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// GPIO 5 D1
#define LED 0
// WiFi
const char *ssid = "vi"; // Enter your WiFi name
const char *password = "12345"; // Enter WiFi password
// MQTT Broker
const char *mqtt_broker = "192.168.43.23";
const char *topic = "esp8266/led";
const int mqtt_port = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
// Set software serial baud to 115200;
Serial.begin(115200);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
if (client.connect(" ")) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// publish and subscribe
client.publish(topic, "hello emqx");
client.subscribe(topic);
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
String message;
for (int i = 0; i < length; i++) {
message = message + (char) payload[i]; // convert *byte to string
}
Serial.print(message);
if (message == "on") { digitalWrite(LED, LOW); } // LED on
if (message == "off") { digitalWrite(LED, HIGH); } // LED off
Serial.println();
Serial.println("-----------------------");
}
void loop() {
client.loop();
}
I have tested broker connection successfully. I tested to subscribe message that I was publishing from ESP01
I don't know why My led doesn't turn on or off when I publish message from broker (PC)