2024年7月14日 星期日

ESP32 - Client1 : MQTT Basic (WOKWI ESP32 LED+DHT22) Client2 :MQTT Explorer Broker: test.mosquitto.org

 

ESP32 - MQTT Basic

ESP32 - Client1 : MQTT Basic  (WOKWI  ESP32 LED+DHT22)   Client2 :MQTT Explorer  Broker: test.mosquitto.org



使用免費公開的 test.mosquitto.org  Broker



Windows MQTT Client

免安裝,測試結果正常。

發送 alex9ufo/ESP32/LED {"LED":"on"} 或 {"LED":"off"}  控制WOKWI  ESP32  LED  on ,off

訂閱 alex9ufo/ESP32/TempHumi 從 WOKWI  ESP32  DHT22 上發送json格式的溫度 濕度 

(Json file 格式)








Topic : alex9ufo/ESP32/LED

Payload : {"LED":"on"} 或  {"LED":"off"}





WORWI

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

//
const int DHT_PIN = 15;
const int LED_PIN = 13;

const char* ssid = "Wokwi-GUEST";
const char* password = "";

const char *mqtt_broker = "test.mosquitto.org";
const int mqtt_port = 1883;

DHTesp dhtSensor;
WiFiClient wifi;
PubSubClient client(wifi);

unsigned long previousMillis = 0;
unsigned long interval = 5000;

// 設定用戶端ID
const char clientID[] = "alex9ufo_esp32";
// 設定主題名稱
const char topic[] = "alex9ufo/ESP32/TempHumi";
// 儲存訊息的字串變數
String msgStr = "";
// 儲存字元陣列格式的訊息字串(參閱下文說明)
char json[30];

//==============================================================
void reconnect() {
  // 若目前沒有和伺服器相連,則反覆執行直到連結成功…
  while (!client.connected()) {
    // 指定用戶端ID並連結MQTT伺服器
    // client.connect(clientID, mqtt_username, mqtt_password))
    if (client.connect(clientID)) {
      Serial.println("connected");
 
      // 成功連線訂閱主題
      client.subscribe("alex9ufo/ESP32/LED");
    }
    else {
      // 若連線不成功,則顯示錯誤訊息
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // 等候5秒,再重新嘗試連線。
      delay(5000);
    }
  }
}
//==============================================================
void callback(char *topic, byte *payload, unsigned int length) {
  char inData[256];
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    inData[i] = (char)payload[i];
    Serial.print((char) payload[i]);
  }
 
  DynamicJsonDocument doc(1024);
  deserializeJson(doc, inData);
  JsonObject obj = doc.as<JsonObject>();
  //  Serial.println(obj);
  String led = obj["LED"];

  if (led == "off") digitalWrite(LED_PIN, HIGH);
  if (led == "on") digitalWrite(LED_PIN, LOW);
  Serial.println();
  Serial.print("led -->");
  Serial.println(led);
 
  Serial.println();
  Serial.println("-----------------------");
}
//==============================================================
void setup() {
  Serial.begin(115200);

  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
 
  Serial.println("WiFi connected");
 
  client.setServer(mqtt_broker, mqtt_port);
  client.setCallback(callback);
}
//==============================================================
void loop() {
 
  // 確認用戶端是否已連上伺服器
  if (!client.connected()) {
    // 若沒有連上,則執行此自訂函式。
    reconnect();
  }
  // 更新用戶端狀態
  client.loop();
 
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >=interval) {

  previousMillis = currentMillis;
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  String Temp= String(data.temperature, 2);
  String Humi= String(data.humidity, 1);

  // 建立MQTT訊息(JSON格式的字串)
  msgStr = msgStr + "{\"temp\":" + Temp + ",\"humid\":" + Humi + "}";
  // 把String字串轉換成字元陣列格式
  msgStr.toCharArray(json, 30);
  // 發布MQTT主題與訊息
  client.publish(topic, json);
  // 清空MQTT訊息內容
  msgStr = "";
  }

}












使用 broker.mqttgo.io

修改 mqtt_broker名稱



沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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