2026年4月22日 星期三

ESP32 and Node-RED with MQTT (Publish and Subscribe)

 

ESP32 and Node-RED with MQTT (Publish and Subscribe)

參考來源  https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/



mqtt_server = "broker.mqtt-dashboard.com"

client.publish("alex9ufo/Thinkitive/temp"

client.publish("alex9ufo/Thinkitive/hum"

client.subscribe("alex9ufo/room/lamp");








WOKWI ESP32程式

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

// Uncomment one of the lines bellow for whatever DHT sensor type you're using!
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
const int DHT_PIN = 15;  // DHT 感測器的連接 PIN
const int lamp = 4;
DHTesp dht;
const char* ssid = "Wokwi-GUEST"; // WiFi SSID
const char* password = ""; // WiFi 密碼
const char* mqtt_server = "broker.mqtt-dashboard.com"; // MQTT 服務器地址

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0; // 記錄上一次消息發送的時間
float temp = 0; // 溫度變量
float hum = 0; // 濕度變量

// 設置 WiFi 連接
void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

// MQTT 消息回調函數
// This function is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that
// your ESP8266 is subscribed you can actually do something
//==============================================================
void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  String message = String((char*)payload);
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message: ");
  Serial.println( message);

  if (String(topic) == "alex9ufo/room/lamp") {

  if (message == "on")
    digitalWrite(lamp, HIGH); // LOW to activate

  if (message == "off")
    digitalWrite(lamp, LOW); // LOW to activate
  Serial.println();
  Serial.println("-----------------------");
  }
}
//==============================================================

// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266

// 重連 MQTT 服務器
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected");
     
      // 關鍵修正:必須訂閱你想要接收的主題
      client.subscribe("alex9ufo/room/lamp");
     
      // 這是您原本訂閱的主題(如果沒用到可以移除)
      client.subscribe("alex9ufo/ThinkIOT/Subscribe");
     
      client.publish("alex9ufo/ThinkIOT/Publish", "Welcome");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

// 初始化設置
void setup() {
  pinMode(lamp, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  dht.setup(DHT_PIN, DHTesp::DHT22); // 初始化 DHT22
}

// 主循環
void loop() {
  // 如果未連接 MQTT,則嘗試重新連接
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  unsigned long now = millis();
  if (now - lastMsg > 5000) { // 每 2 秒發布一次數據
    lastMsg = now;
    TempAndHumidity  data = dht.getTempAndHumidity();

    String temp = String(data.temperature, 2);
    client.publish("alex9ufo/Thinkitive/temp", temp.c_str()); // 發布溫度數據
    String hum = String(data.humidity, 1);
    client.publish("alex9ufo/Thinkitive/hum", hum.c_str());   // 發布濕度數據

    Serial.print("Temperature: ");
    Serial.println(temp);
    Serial.print("Humidity: ");
    Serial.println(hum);
  }
}

Node-Red 程式

[{"id":"3322eee9576783df","type":"mqtt in","z":"4b78f7e5d13e6604","name":"濕度","topic":"alex9ufo/Thinkitive/hum","qos":"1","datatype":"auto-detect","broker":"b9efc827e98bf7f9","nl":false,"rap":true,"rh":0,"inputs":0,"x":230,"y":120,"wires":[["c955bb867c3764eb"]]},{"id":"e10e2c7d299e3c2c","type":"mqtt out","z":"4b78f7e5d13e6604","name":"燈泡","topic":"alex9ufo/room/lamp","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"b9efc827e98bf7f9","x":410,"y":180,"wires":[]},{"id":"df3ef8083edb59a3","type":"mqtt in","z":"4b78f7e5d13e6604","name":"溫度","topic":"alex9ufo/Thinkitive/temp","qos":"1","datatype":"auto-detect","broker":"b9efc827e98bf7f9","nl":false,"rap":true,"rh":0,"inputs":0,"x":230,"y":60,"wires":[["88fc71e9f52b3d9e"]]},{"id":"4619b3053d03f1a8","type":"ui_switch","z":"4b78f7e5d13e6604","name":"","label":"switch","tooltip":"","group":"3ac0cc1879cac657","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"topic","topicType":"msg","style":"","onvalue":"on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"off","offvalueType":"str","officon":"","offcolor":"","animate":false,"className":"","x":230,"y":180,"wires":[["e10e2c7d299e3c2c"]]},{"id":"88fc71e9f52b3d9e","type":"ui_chart","z":"4b78f7e5d13e6604","name":"溫度","group":"9cb87f6334be2cce","order":1,"width":0,"height":0,"label":"chart","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"step","nodata":"","dot":false,"ymin":"0","ymax":"40","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"useUTC":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"outputs":1,"useDifferentColor":false,"className":"","x":410,"y":60,"wires":[[]]},{"id":"c955bb867c3764eb","type":"ui_gauge","z":"4b78f7e5d13e6604","name":"濕度'","group":"9cb87f6334be2cce","order":2,"width":0,"height":0,"gtype":"gage","title":"Humidity","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","diff":false,"className":"","x":410,"y":120,"wires":[]},{"id":"b9efc827e98bf7f9","type":"mqtt-broker","name":"broker.mqtt-dashboard.com","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","autoConnect":true,"usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"autoUnsubscribe":true,"birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":"","birthMsg":{},"closeTopic":"","closeQos":"0","closeRetain":"false","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","willMsg":{},"userProps":"","sessionExpiry":""},{"id":"3ac0cc1879cac657","type":"ui_group","name":"Lamp","tab":"0c1ba72ccee260d2","order":2,"disp":true,"width":"6","collapse":false,"className":""},{"id":"9cb87f6334be2cce","type":"ui_group","name":"Sensor","tab":"0c1ba72ccee260d2","order":1,"disp":true,"width":"6","collapse":false,"className":""},{"id":"0c1ba72ccee260d2","type":"ui_tab","name":"Room","icon":"dashboard","disabled":false,"hidden":false}]

沒有留言:

張貼留言

ESP32 and Node-RED with MQTT (Publish and Subscribe)

  ESP32 and Node-RED with MQTT (Publish and Subscribe) 參考來源  https://randomnerdtutorials.com/esp8266-and-node-red-with-mqtt/ mqtt_server = ...