Arduino MQTT发布不起作用

时间:2017-10-25 15:35:31

标签: arduino mqtt arduino-uno arduino-ide

我的Arduino有问题。我正在尝试学习MQTT,但它不适用于我的代码。我正在使用shiftr.io来查看MQTT操作。通过Mac终端发布实现,但我没有看到Arduino的任何动作。

我在Arduino Uno上使用WiFi盾牌。

这是我的代码:

#include <WiFi.h>
#include <MQTTClient.h>

const char ssid[] = "  /* Filed in in the code */ ";
const char pass[] = "  /* Filed in in the code */ ";

WiFiClient net;
MQTTClient client;

unsigned long lastMillis = 0;

void setup() {
  Serial.begin(9600);
  WiFi.begin(ssid, pass);

  // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  // You need to set the IP address directly.
  client.begin("broker.shiftr.io", net);
  client.onMessage(messageReceived);

  connect();
}

void connect() {
  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect("arduino", "try", "try")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe("/hello");
  // client.unsubscribe("/hello");
}

void loop() {
  client.loop();

  if (!client.connected()) {
    connect();
    Serial.print("not");
  }

  // publish a message roughly every second.
  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    client.publish("/hello", "world");
  }
}

void messageReceived(String &topic, String &payload) {
  Serial.println("incoming: " + topic + " - " + payload);
}

我觉得奇怪的是第二种包含颜色不同 看看这个截图:

enter image description here

我不知道自己做错了什么。如果你能帮助我那会很好。

0 个答案:

没有答案