ESP32 教學 47/55 - 使用 MQTT 透過互聯網嘅 WS2812 CheerLights | SunFounder 嘅 ESP32 IoT 套件
喺呢個教學入面,我哋會用ESP32同WS2812 LED整一個同步燈光系統,可以透過MQTT遠端控制。呢個系統容許多位用戶同時改變燈光顏色,無論喺邊度都可以創造一個連繫嘅體驗。呢個項目用咗SunFounder ESP32 IoT套件,佢包含一個有Wi-Fi功能嘅強大微控制器,好適合IoT應用。
成條片入面,我哋會逐步講解所需嘅設定、接線同程式碼實現,嚟達到呢個效果。如果你需要進一步嘅澄清,記得喺特定時間點(片入面mm:ss)睇返條片。
硬件解釋
呢個項目嘅主要組件包括ESP32微控制器、WS2812 LED燈帶同一個MQTT代理伺服器。ESP32係一個多功能微控制器,內置Wi-Fi同藍牙功能,可以輕鬆連接到互聯網。佢係我哋項目嘅大腦,負責處理通訊同控制LED燈帶。
WS2812 LED燈帶由獨立可尋址嘅RGB LED組成,可以控制嚟顯示各種顏色。每個LED都可以用一條數據線開關同設定任何顏色,非常適合動態燈光效果。MQTT代理伺服器促進唔同客戶端之間嘅通訊,容許用戶發佈同訂閱控制LED顏色嘅主題。
數據表詳情
| 製造商 | Adafruit |
|---|---|
| 零件編號 | WS2812B |
| 邏輯/IO電壓 | 3.5 - 5.5 V |
| 供電電壓 | 5 V |
| 輸出電流(每通道) | 20 mA |
| 峰值電流(每通道) | 60 mA |
| PWM頻率指引 | 400 Hz |
| 輸入邏輯閾值 | 0.2Vcc(低),0.7Vcc(高) |
| 電壓降 / RDS(on) / 飽和 | 0.5 V |
| 熱限制 | 工作溫度:-25至85 °C |
| 封裝 | 獨立5050 SMD |
| 備註 / 變體 | 有多種長度同配置可供選擇 |
- 確保WS2812燈帶有足夠嘅電源供應,以避免電壓降。
- 喺ESP32同LED燈帶之間使用共同接地。
- 保持數據線短,以防止信號衰減。
- 考慮喺電源供應上加一個電容(1000μF)嚟平滑電壓尖峰。
- 喺數據線上使用適當嘅電阻,以防止信號反射。
- 注意LED燈帶嘅總電流消耗;必要時使用外部電源。
接線說明
要將ESP32同WS2812 LED燈帶接線,首先連接電源供應。將LED燈帶嘅紅線連接到5V電源,黑線連接到接地。跟住,將WS2812燈帶嘅數據線(黃線)連接到ESP32嘅引腳14。確保ESP32同LED燈帶連接到同一個接地,以保持共同參考點。
設定好電源同數據連接之後,用micro USB線將ESP32連接到電腦進行編程。你需要確保喺編程時ESP32已開機,以建立連接。接好線之後,你就可以上傳程式碼並測試設定。

程式碼示例同講解
程式碼首先包含Wi-Fi同MQTT功能所需嘅函式庫。識別碼ssid同password用嚟儲存你嘅Wi-Fi憑證,而mqtt_server就保存MQTT代理伺服器嘅地址。
const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_server = "mqtt.cheerlights.com";
跟住,我哋用陣列定義支援嘅CheerLights顏色同佢哋對應嘅RGB值。咁樣程式就可以根據用戶輸入輕鬆存取顏色設定。
String colorName[] = {"red", "pink", "green", "blue", "cyan", "white", "warmwhite", "oldlace", "purple", "magenta", "yellow", "orange"};
int colorRGB[][3] = { 255, 0, 0, // "red"
255, 192, 203, // "pink" ...};
setup()函數初始化串列通訊、設定Wi-Fi連接,並準備MQTT客戶端。佢亦都啟動LED燈帶。
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
pixels.begin();
pixels.show();
}
主循環持續檢查MQTT連接,並處理控制LED顏色嘅傳入訊息。callback()函數喺訂閱嘅主題收到訊息時觸發。
示範 / 預期效果
一切設定好並上傳程式碼之後,你應該可以透過向MQTT主題發送訊息嚟改變WS2812 LED嘅顏色。如果另一個用戶改變顏色,所有連接嘅設備都會同時反映呢個變化。要小心潛在問題,例如極性反轉或連接不當,呢啲可能會阻止LED正常運作(片入面mm:ss)。
影片時間戳
- 00:00 開始
- 2:00 簡介
- 3:48 文檔頁面
- 6:33 接線說明
- 7:35 Arduino 代碼說明
- 15:03 喺 Arduino IDE 度選擇 ESP32 開發板同 COMP 埠
- 16:46 CheerLighs 示範
/*********
:ref: https://randomnerdtutorials.com/esp32-mqtt-publish-subscribe-arduino-ide/
https://docs.sunfounder.com/projects/kepler-kit/en/latest/iotproject/5.mqtt_pub.html
*********/
#include <WiFi.h>
#include <PubSubClient.h>
//#include <Wire.h>
#include <Adafruit_NeoPixel.h>
// Replace the next variables with your SSID/Password combination
const char* ssid = "SSID";
const char* password = "PASSWORD";
// Add your MQTT Broker address:
const char* mqtt_server = "mqtt.cheerlights.com";
const char* unique_identifier = "sunfounder-client-sdgvsasdda";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
int value = 0;
// Define the supported CheerLights colors and their RGB values
String colorName[] = {"red", "pink", "green", "blue", "cyan", "white", "warmwhite", "oldlace", "purple", "magenta", "yellow", "orange"};
int colorRGB[][3] = { 255, 0, 0, // "red"
255, 192, 203, // "pink"
0, 255, 0, // "green"
0, 0, 255, // "blue"
0, 255, 255, // "cyan"
255, 255, 255, // "white"
255, 223, 223, // "warmwhite"
255, 223, 223, // "oldlace"
128, 0, 128, // "purple"
255, 0, 255, // "magenta"
255, 255, 0, // "yellow"
255, 165, 0}; // "orange"
// init rgb strip
#define LED_PIN 13
#define NUM_LEDS 8
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
void setup() {
Serial.begin(115200);
// wifi default settings
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
// rgb strip begin
pixels.begin();
pixels.show();
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
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());
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String messageTemp;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
messageTemp += (char)message[i];
}
Serial.println();
// If a message is received on the topic, you will check this message.
// Changes the output state according to the message
if (String(topic) == "cheerlights") {
Serial.print("Changing color to ");
Serial.println(messageTemp);
setColor(messageTemp);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(unique_identifier)) {
Serial.println("connected");
// Subscribe
client.subscribe("cheerlights");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setColor(String color) {
// Loop through the list of colors to find the matching color
for (int colorIndex = 0; colorIndex < 12; colorIndex++) {
if (color == colorName[colorIndex]) {
// Set the color of each NeoPixel on the strip
for (int pixel = 0; pixel < NUM_LEDS; pixel++) {
pixels.setPixelColor(pixel, pixels.Color (colorRGB [colorIndex][0], colorRGB [colorIndex][1], colorRGB [colorIndex][2]));
}
pixels.show();
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Common Course Links
Common Course Files
資源與參考資料
-
文件记录ESP32 Tutorial 47/55 - SunFounder doc page for cheer lightdocs.sunfounder.com
文件📁
冇文件可用。