问题描述
整个实验按照 https://www.emqx.cn/blog/esp8266_mqtt_led 进行,
8266 已经可以收到 message 并通过串口监视器输出,可是无论是发送 on 还是 off,
led 小灯都没有反应
已经排除线路问题
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// GPIO 5 D1
#define LED 5
// WiFi
const char *ssid = "emqx"; // Enter your WiFi name
const char *password = "qwertyuiop"; // Enter WiFi password
const char *mqtt_broker = "x.x.x.x";
const char *topic = "esp8266/led";
const char *mqtt_username = "test1";
const char *mqtt_password = "123";
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);
pinMode(LED, OUTPUT);//添加这一行LED常亮,不加常灭
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
digitalWrite(LED, HIGH);
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);
while (!client.connected()) {
String client_id = "esp8266-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
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
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();
}
环境信息
- EMQ X 版本:
- 操作系统及版本:
- 其他