2023年7月9日 星期日

ESP32 MQTT – Publish and Subscribe with Arduino IDE

 ESP32 MQTT – Publish and Subscribe with Arduino IDE













[{"id":"f0d37edca8bd827a","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"濕度","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"65","seg2":"75","className":"","x":370,"y":440,"wires":[]},{"id":"2858a2ae8ebe4d8f","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":140,"y":80,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"9e48ae5668dd1d79","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"off","payloadType":"str","topic":"","topicType":"str","x":140,"y":120,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"f20d6295bed43e34","type":"mqtt out","z":"17c01e65ea7d6deb","name":"Control LED","topic":"alex9ufo/esp32/led","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":390,"y":180,"wires":[]},{"id":"7451665529bc4d94","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開關反向","tooltip":"","color":"blue","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","topicType":"str","x":160,"y":160,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"88929da799604451","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開5秒鐘","tooltip":"","color":"purple","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","topicType":"str","x":150,"y":240,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"1848f7d50b01e54d","type":"comment","z":"17c01e65ea7d6deb","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":270,"y":280,"wires":[]},{"id":"9861fa8e41cac265","type":"ui_button","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":0,"width":"2","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"yellow","bgcolor":"","className":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","topicType":"str","x":140,"y":200,"wires":[["f20d6295bed43e34","4411678fdec67d84","9610c96e24aa9818"]]},{"id":"4411678fdec67d84","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":400,"y":240,"wires":[]},{"id":"9610c96e24aa9818","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":120,"wires":[]},{"id":"b9d0a81d2ded2e3a","type":"ui_audio","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","voice":"en-US","always":"","x":380,"y":320,"wires":[]},{"id":"8d3c364c24da2ae4","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Humidity","topic":"alex9ufo/esp32/humidity","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":160,"y":460,"wires":[["f0d37edca8bd827a","b9d0a81d2ded2e3a","4136d882ef1c9ca1"]]},{"id":"c9459b13380fcebf","type":"mqtt in","z":"17c01e65ea7d6deb","name":"Temperature","topic":"alex9ufo/esp32/temperature","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":170,"y":380,"wires":[["1c1b88400941a7c1","b9d0a81d2ded2e3a","54c0f79e889b0aac"]]},{"id":"1c1b88400941a7c1","type":"ui_gauge","z":"17c01e65ea7d6deb","name":"","group":"d783cb980c3979fc","order":1,"width":"3","height":"2","gtype":"gage","title":"溫度","label":"℃","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"26","seg2":"50","className":"","x":370,"y":360,"wires":[]},{"id":"61b5589a2c26df1d","type":"mqtt in","z":"17c01e65ea7d6deb","name":"LED Status","topic":"alex9ufo/esp32/led","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":150,"y":40,"wires":[["050db70fc3c0868a"]]},{"id":"050db70fc3c0868a","type":"ui_text","z":"17c01e65ea7d6deb","group":"d783cb980c3979fc","order":0,"width":0,"height":0,"name":"","label":"ESP32發行到MQTT的LED狀態","format":"{{msg.payload}}","layout":"row-left","className":"","x":450,"y":40,"wires":[]},{"id":"54c0f79e889b0aac","type":"debug","z":"17c01e65ea7d6deb","name":"debug 91","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":380,"y":400,"wires":[]},{"id":"4136d882ef1c9ca1","type":"debug","z":"17c01e65ea7d6deb","name":"debug 92","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":380,"y":480,"wires":[]},{"id":"d783cb980c3979fc","type":"ui_group","name":"Demo","tab":"0449b3b1fea99d52","order":1,"disp":true,"width":"6","collapse":false},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"6c9116b.b62d4e8","type":"ui_group","name":"Storing IOT Data ","tab":"eeb8e179.a47a4","order":1,"disp":true,"width":"6","collapse":true},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"0449b3b1fea99d52","type":"ui_tab","name":"Demo","icon":"dashboard","disabled":false,"hidden":false},{"id":"eeb8e179.a47a4","type":"ui_tab","name":"eWeLink","icon":"dashboard","disabled":false,"hidden":false}]


Installing the PubSubClient Library

The PubSubClient library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT (basically allows your ESP32 to talk with Node-RED).

  1. Click here to download the PubSubClient library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get pubsubclient-master folder
  3. Rename your folder from pubsubclient-master to pubsubclient
  4. Move the pubsubclient folder to your Arduino IDE installation libraries folder
  5. Then, re-open your Arduino IDE

The library comes with a number of example sketches. See File >Examples > PubSubClient within the Arduino IDE software.

Important: PubSubClient is not fully compatible with the ESP32, but the example provided in this tutorial is working very reliably during our tests.



#include <WiFi.h>
#include <PubSubClient.h>

// GPIO 2 D1
#define LED 2

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 27     // Digital pin connected to the DHT sensor
// Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 --
// Pin 15 can work but DHT must be disconnected during program upload.

// Uncomment the type of sensor in use:
//#define DHTTYPE    DHT11     // DHT 11
#define DHTTYPE    DHT22     // DHT 22 (AM2302)
//#define DHTTYPE    DHT21     // DHT 21 (AM2301)
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

// WiFi
const char *ssid = "alex9ufo"; // Enter your Wi-Fi name
const char *password = "alex9981";  // Enter Wi-Fi password

// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";
const char *topic1 = "alex9ufo/esp32/led";
const char *topic2 = "alex9ufo/esp32/temperature";
const char *topic3 = "alex9ufo/esp32/humidity";

const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

bool ledState = false;

WiFiClient espClient;
PubSubClient client(espClient);

long lastMsg = 0;
char msg[50];
String json = "";    
char jsonChar1[100];  //client.publish("alex9ufo/Esp32/temperature"
char jsonChar2[100];  //client.publish("alex9ufo/Esp32/humidity"

//===========================================================
void setup() {
    // Set software serial baud to 115200;
    Serial.begin(115200);
    delay(1000); // Delay for stability
    //======================================================
    dht.begin();
    Serial.println(F("DHTxx Unified Sensor Example"));
    // Print temperature sensor details.
    sensor_t sensor;
    dht.temperature().getSensor(&sensor);
    Serial.println(F("------------------------------------"));
    Serial.println(F("Temperature Sensor"));
    Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
    Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
    Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
    Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("°C"));
    Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("°C"));
    Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("°C"));
    Serial.println(F("------------------------------------"));
    // Print humidity sensor details.
    dht.humidity().getSensor(&sensor);
    Serial.println(F("Humidity Sensor"));
    Serial.print  (F("Sensor Type: ")); Serial.println(sensor.name);
    Serial.print  (F("Driver Ver:  ")); Serial.println(sensor.version);
    Serial.print  (F("Unique ID:   ")); Serial.println(sensor.sensor_id);
    Serial.print  (F("Max Value:   ")); Serial.print(sensor.max_value); Serial.println(F("%"));
    Serial.print  (F("Min Value:   ")); Serial.print(sensor.min_value); Serial.println(F("%"));
    Serial.print  (F("Resolution:  ")); Serial.print(sensor.resolution); Serial.println(F("%"));
    Serial.println(F("------------------------------------"));
    // Set delay between sensor readings based on sensor details.
    delayMS = sensor.min_delay / 1000;
  //======================================================
    // Connecting to a WiFi network
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to the WiFi network");

    // Setting LED pin as output
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);  // Turn off the LED initially

    // Connecting to an 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 HiveMQ MQTT broker connected");
        } else {
            Serial.print("Failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }

    // Publish and subscribe
    client.publish(topic1, "hello HiveMQ MQTT broker");
    client.subscribe(topic1);
    client.subscribe(topic2);
    client.subscribe(topic3);
}
//===========================================================
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 += (char) payload[i];  // Convert *byte to string
    }
    Serial.print(message);
    if (message == "on" && !ledState) {
        digitalWrite(LED, HIGH);  // Turn on the LED
        ledState = true;
    }
    if (message == "off" && ledState) {
        digitalWrite(LED, LOW); // Turn off the LED
        ledState = false;
    }
    Serial.println();
    Serial.println("-----------------------");
}
//===========================================================
void loop() {
    client.loop();
    delay(100); // Delay for a short period in each loop iteration
    long now = millis();
    if (now - lastMsg > 15000) {
    lastMsg = now;
    dht.begin();
    // Delay between measurements.
    delay(delayMS);
    // Get temperature event and print its value.
    sensors_event_t event;
    // Temperature in Celsius
    dht.temperature().getEvent(&event);
    if (isnan(event.temperature)) {
      Serial.println(F("Error reading temperature!"));
    }
    else {
      Serial.print(F("Temperature: "));
      Serial.print(event.temperature);
      Serial.println(F("°C"));
         
      String json1 =String(event.temperature);
      // Convert JSON string to character array
      json1.toCharArray(jsonChar1, json1.length()+1);
      client.publish(topic2, jsonChar1);
    }
 
      // Get humidity event and print its value.
    dht.humidity().getEvent(&event);
    if (isnan(event.relative_humidity)) {
      Serial.println(F("Error reading humidity!"));
    }
    else {
      Serial.print(F("Humidity: "));
      Serial.print(event.relative_humidity);
      Serial.println(F("%"));

      String json2=String(event.relative_humidity);  
      // Convert the value to a char array
      json2.toCharArray(jsonChar2, json2.length()+1);
      client.publish(topic3, jsonChar2);
    }  
  }



}
//===========================================================





沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...