代码未连接到MQTT本地服务器

时间:2017-10-26 18:17:22

标签: arduino mqtt

我正在尝试将我的Arduino Uno与WiFi盾连接到我的MQTT服务器。我在Mac上本地运行它。它似乎停留在while循环中。我认为它没有连接到经纪人。这是我的代码。循环可能有什么问题?或者还有其他问题吗?

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

const char ssid[] = " : /*filed in*: ";
const char pass[] = " /*filed in*/ ";

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("10.0.1.5", net);
  client.onMessage(messageReceived);

  connect();
}

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

  Serial.print("\nconnecting...");
  while (!client.connect("Arduino test")) {
    Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");
  Serial.println("connected");

  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);
}

0 个答案:

没有答案