Toggle Swith in EasyBuilderPro HMI 控制Wokwi 的 LED ON / OFF
參考來源 https://bermainwokwi.blogspot.com/p/1-koneksi-mqtt.html#delapan
const char* mqtt_server = "mqtt-dashboard.com"; // 設定 MQTT Broker 伺服器位址
const char* mqtt_topic = "alex9ufo/ebpro_wokwi/led/status"; // 設定訂閱的 MQTT 主題(Topic)名稱
Download EasyBuilder Pro (EBPro) EasyBuilderPro_download
WOKWI程式
#include <WiFi.h> // 引入 ESP32 的 WiFi 模組函式庫,用於處理無線網路連線
#include <PubSubClient.h> // 引入 MQTT 協定函式庫,用於傳輸與接收 MQTT 訊息
#define BUILTIN_LED 2 // 定義板載 LED 所連接的引腳(GPIO 2)
const char* ssid = "Wokwi-GUEST"; // 設定 WiFi 的 SSID(名稱)
const char* password = ""; // 設定 WiFi 的密碼(此處為無密碼)
const char* mqtt_server = "mqtt-dashboard.com"; // 設定 MQTT Broker 伺服器位址
const char* mqtt_topic = "alex9ufo/ebpro_wokwi/led/status"; // 設定訂閱的 MQTT 主題(Topic)名稱
WiFiClient espClient; // 建立 ESP32 的網路客戶端物件
PubSubClient client(espClient); // 將網路客戶端傳入 MQTT 函式庫,建立 MQTT 客戶端實例
// 自定義函式:負責連接 WiFi
void setup_wifi() {
Serial.print("Connecting to WiFi..."); // 在序列埠監控器輸出提示字串
WiFi.begin(ssid, password); // 開始連線至指定 SSID 與密碼的 WiFi
// 檢查連線狀態,若尚未成功連線就每隔 0.5 秒印出一個點
while (WiFi.status() != WL_CONNECTED) {
delay(500); // 延遲 500 毫秒
Serial.print("."); // 輸出點點表示進度
}
// 連線成功後,顯示訊息並印出取得的局域網 IP 位址
Serial.println("\nWiFi connected! IP: " + WiFi.localIP().toString());
}
// MQTT 回呼函式:當訂閱的主題收到新訊息時會自動執行
void callback(char* topic, byte* payload, unsigned int length) {
String message; // 宣告一個字串變數用來儲存接收到的訊息內容
// 將 byte 陣列類型的 payload 逐字轉成字串
for (unsigned int i = 0; i < length; i++) {
message += (char)payload[i];
}
// 印出訊息發生的主題與具體內容
Serial.printf("Message arrived [%s]: %s\n", topic, message.c_str());
// 判斷 JSON 內容:若字串中包含 "true" (忽略大小寫) 則點亮 LED,否則關閉
if (message.indexOf("true") != -1) {
digitalWrite(BUILTIN_LED, HIGH); // 點亮 LED
} else if (message.indexOf("false") != -1) {
digitalWrite(BUILTIN_LED, LOW); // 熄滅 LED
}
}
// 自定義函式:負責 MQTT 斷線重連
void reconnect() {
// 當 MQTT 處於未連線狀態時持續嘗試
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// 產生一個隨機的 Client ID(例如 ESP32Client-A3F1),避免多台裝置使用相同 ID 斷線
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
// 嘗試連線至 MQTT Broker
if (client.connect(clientId.c_str())) {
Serial.println("connected"); // 連線成功提示
client.subscribe(mqtt_topic); // 重新訂閱指定主題以接收訊息
} else {
// 連線失敗時印出錯誤代碼(rc)並等待 5 秒後重試
Serial.printf("failed, rc=%d try again in 5 seconds\n", client.state());
delay(5000); // 等待 5000 毫秒
}
}
}
// ESP32 初始化設定函式(只會在開機或重置時執行一次)
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // 設定 BUILTIN_LED 引腳為輸出模式
Serial.begin(115200); // 初始化序列埠通訊,波特率設定為 115200
setup_wifi(); // 呼叫 setup_wifi 連接網路
client.setServer(mqtt_server, 1883); // 設定 MQTT 伺服器位址與 Port(預設 1883)
client.setCallback(callback); // 指定接收訊息時處理的回呼函式
}
// 主程式無窮迴圈(持續重複執行)
void loop() {
// 檢查 MQTT 連線狀態,若斷開則呼叫 reconnect() 重連
if (!client.connected()) reconnect();
client.loop(); // 保持 MQTT 客戶端的運作,處理心跳包(Keep-Alive)與接收新訊息
}




























