4-Digit 7 Segment LED Display & MQTT
Wokwi 硬體連接指引 (diagram.json)
在 Wokwi 中,請添加一個 TM1637 模組,並按照以下方式連接:
| TM1637 引腳 | ESP32 引腳 |
| GND | GND |
| VCC | 3.3V 或 5V |
| CLK | GPIO 18 |
| DIO | GPIO 19 |
#include <WiFi.h> // ESP32 使用這個
#include <PubSubClient.h>
#include <TM1637Display.h>
// --- 設定區 ---
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "mqtt-dashboard.com";
// ESP32 建議腳位:CLK 用 GPIO 18, DIO 用 GPIO 19
const int CLK = 18;
const int DIO = 19;
TM1637Display display(CLK, DIO);
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(100);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
// --- 接收訊息回呼 ---
void callback(char* topic, byte* payload, unsigned int length) {
String msg = "";
for (int i = 0; i < length; i++) {
msg += (char)payload[i];
}
Serial.print("Command from MQTT [");
Serial.print(topic);
Serial.print("]: ");
Serial.println(msg);
// 如果收到的是數字字串,將其顯示在 TM1637 上
int val = msg.toInt();
display.showNumberDec(val);
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// 訂閱主題
client.subscribe("alex9ufo/tm1637command");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
display.setBrightness(0x0a);
display.clear(); // 清除顯示
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
打開一個 MQTT 客戶端(如
)。HiveMQ Web Client
2. DOS command :
C:\Users\User>mosquitto_pub -h mqtt-dashboard.com -t "alex9ufo/tm1637command" -m "5545"





沒有留言:
張貼留言