# emqx控制led小灯

**URL:** <https://askemq.com/t/topic/293>\
**Category:** EMQX\
**Created:** [2021 年4 月 22 日 13:35 UTC](https://askemq.com/t/topic/293 "2021-04-22T13:35:51Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

作者： ![496062195](https://askemq.com/letter_avatar/496062195/32/6_449c533f586939b6e5f246632a46421f.png) [@496062195](https://askemq.com/u/496062195)\
发布日期： [2021 年4 月 22 日 13:35 UTC](https://askemq.com/t/topic/293/1 "2021-04-22T13:35:51Z")

</div>

### 问题描述

整个实验按照 [https://www.emqx.cn/blog/esp8266\_mqtt\_led](https://www.emqx.cn/blog/esp8266_mqtt_led) 进行，  
8266 已经可以收到 message 并通过串口监视器输出，可是无论是发送 on 还是 off，  
led 小灯都没有反应

已经排除线路问题

```auto
#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 版本：
- 操作系统及版本：
- 其他

---

<div class="post-metadata">

作者： ![wwhai](https://askemq.com/user_avatar/askemq.com/wwhai/32/1295_2.png) [@wwhai](https://askemq.com/u/wwhai)\
发布日期： [2021 年4 月 23 日 01:01 UTC](https://askemq.com/t/topic/293/2 "2021-04-23T01:01:41Z")

</div>

。。你得根据你的实际开发板来接线啊，检查一下IO口？

---

<div class="post-metadata">

作者： ![496062195](https://askemq.com/letter_avatar/496062195/32/6_449c533f586939b6e5f246632a46421f.png) [@496062195](https://askemq.com/u/496062195)\
发布日期： [2021 年4 月 23 日 01:09 UTC](https://askemq.com/t/topic/293/3 "2021-04-23T01:09:34Z")

</div>

![image](https://askemq.com/uploads/default/original/1X/479cbd29cf8c26007450e0af76217a98cbb2f9d1.jpeg)  
确实是GPIO5

另外我试了下程序能够进入  
if (message == “on”) { digitalWrite(LED, LOW); } // LED on  
if (message == “off”) { digitalWrite(LED, HIGH); } // LED off  
执行if里面的语句，但是小灯就是没反应，  
我单片机知识很有限，点亮小灯这种做不出来确实有点尴尬。。。。

---

<div class="post-metadata">

作者： ![wwhai](https://askemq.com/user_avatar/askemq.com/wwhai/32/1295_2.png) [@wwhai](https://askemq.com/u/wwhai)\
发布日期： [2021 年4 月 23 日 01:10 UTC](https://askemq.com/t/topic/293/4 "2021-04-23T01:10:37Z")

</div>

有没有示波器或者是欧姆表？接上去检查一下

---

<div class="post-metadata">

作者： ![wwhai](https://askemq.com/user_avatar/askemq.com/wwhai/32/1295_2.png) [@wwhai](https://askemq.com/u/wwhai)\
发布日期： [2021 年4 月 23 日 01:13 UTC](https://askemq.com/t/topic/293/5 "2021-04-23T01:13:32Z")

</div>

```auto
#include <AsyncMqttClient.h>

#include "config.h"
#include "util.cpp"
#include <WiFi.h>
#include <WiFiType.h>
#include <esp_event.h>
#include <string.h>
// 全局MQTT客户端
AsyncMqttClient asyncMqttClient;

void connectToWifi()
{
  Serial.print("Try to connect Wi-Fi:");
  Serial.println(WIFI_SSID);
  sleep(3);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}

void connectToMqtt()
{
  if (WiFi.isConnected())
  {
    Serial.print("Try to connect mqtt server:");
    Serial.println(MQTT_HOST.toString());
    sleep(3);
    asyncMqttClient.setServer(MQTT_HOST, MQTT_PORT);
    asyncMqttClient.setClientId(clientId);
    asyncMqttClient.setCredentials(username, password);
    asyncMqttClient.connect();
  }
}
// 初始化
void init()
{
  connectToWifi();
}
void setup()
{

  Serial.begin(115200);
  Serial.println();
  sleep(1);

  // 监控WIFI事件
  WiFi.onEvent([](WiFiEvent_t event) {
    switch (event)
    {
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.print("WiFi connected success IP is :");
      Serial.println(WiFi.localIP());
      sleep(1);
      connectToMqtt();
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("WiFi lost connection");
      connectToWifi();
      break;
    default:
      break;
    }
  });
  // 连接WIFI
  asyncMqttClient.onConnect([](bool sessionPresent) {
    Serial.print("Success to connect mqtt server:");
    Serial.println(MQTT_HOST);
    asyncMqttClient.subscribe(s2cTopic, 2);
  });
  // 离线回调
  asyncMqttClient.onDisconnect([](AsyncMqttClientDisconnectReason reason) {
    Serial.println("Disconnected from mqtt server.");
    // 当WIFI连接成功以后再连接MQTT
    if (WiFi.isConnected())
    {
      connectToMqtt();
    }
    else
    {
      connectToWifi();
    }
  });
  // 消息到达回调
  asyncMqttClient.onMessage([](char *topic, char *payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
    Serial.print("Message received:");
    Serial.println(payload);
  });
  // 发送成功回调
  asyncMqttClient.onPublish([](uint16_t packetId) {

  });
  // 上面配置好以后，初始化连接
  init();
}

void loop()
{
}

```

---

<div class="post-metadata">

作者： ![496062195](https://askemq.com/letter_avatar/496062195/32/6_449c533f586939b6e5f246632a46421f.png) [@496062195](https://askemq.com/u/496062195)\
发布日期： [2021 年4 月 23 日 01:22 UTC](https://askemq.com/t/topic/293/6 "2021-04-23T01:22:33Z")

</div>

这会在上课，不是很方便测试，  
等我测试完尽快回复，谢谢

---

<div class="post-metadata">

作者： ![wwhai](https://askemq.com/user_avatar/askemq.com/wwhai/32/1295_2.png) [@wwhai](https://askemq.com/u/wwhai)\
发布日期： [2021 年4 月 23 日 01:26 UTC](https://askemq.com/t/topic/293/7 "2021-04-23T01:26:40Z")

</div>

😳ok

---

<div class="post-metadata">

作者： ![mousse](https://askemq.com/user_avatar/askemq.com/mousse/32/33_2.png) [@mousse](https://askemq.com/u/mousse)\
发布日期： [2021 年4 月 23 日 01:35 UTC](https://askemq.com/t/topic/293/8 "2021-04-23T01:35:41Z")

</div>

下发指令为 on 时使用电压表测一下 GPIO5 引脚

---

<div class="post-metadata">

作者： ![496062195](https://askemq.com/letter_avatar/496062195/32/6_449c533f586939b6e5f246632a46421f.png) [@496062195](https://askemq.com/u/496062195)\
发布日期： [2021 年4 月 24 日 04:33 UTC](https://askemq.com/t/topic/293/9 "2021-04-24T04:33:04Z")

</div>

问题解决了，程序是对的。  
错误的原因是 webSocket 工具向8266发送的消息是 `{ "msg": "on" }`  
所以程序中 `message="on"` 是进不去的，所以应该发送 on  
或者判断条件改为 `message={ \"msg\":\ "on\" } ` //显然不是很有必要

感谢两位的帮助
