2017年10月28日 星期六

NODEMCU (ESP32) Subscribing to MQTT 3-topic



#include <ESP8266WiFi.h>
#include <PubSubClient.h>

//const char* ssid = "yourNetworkName";
//const char* password =  "yourNetworkPassword";
const char* ssid = "My ASUS";
const char* password =  "alex9981";
//const char* mqttServer = "m11.cloudmqtt.com";
const char* mqttserver = "broker.mqtt-dashboard.com";
const int mqttPort = 1883;
//const char* mqttUser = "yourMQTTuser";
//const char* mqttPassword = "yourMQTTpassword";
const char* mqttUser = "";
const char* mqttPassword = "";

WiFiClient espClient;
PubSubClient client(espClient);

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }

  Serial.println();
  Serial.println("-----------------------");

}

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");

  client.setServer(mqttserver, mqttPort);
  client.setCallback(callback);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client", mqttUser, mqttPassword )) {

      Serial.println("connected");  

    } else {

      Serial.print("failed with state ");
      Serial.println(client.state());
      delay(1000);

    }
  }

  client.subscribe("alex9ufo-DHT11-RaspiData");
  delay(200);
  client.subscribe("alex9ufo-temp-RaspiData");
  delay(200);
  client.subscribe("alex9ufo-humi-RaspiData");
  delay(200);

}

void loop() {
  client.loop();
}

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...