ESP32 教學 38/55 - 用手機控制 RGB LED | SunFounder 嘅 ESP32 IoT 學習套件
喺呢個教學入面,我哋會探討點樣用SunFounder ESP32學習套件入面嘅ESP32模組嚟控制一粒RGB LED。透過你嘅流動裝置發送指令,你就可以改變LED嘅顏色或者完全熄咗佢。呢個項目充分利用咗ESP32嘅能力,運用內置嘅Wi-Fi同藍牙功能嚟實現無縫連接同控制。

RGB LED由三粒獨立嘅LED組成:紅色、綠色同藍色,可以混合出各種顏色。喺呢個項目入面,你會學到點樣正確咁接線RGB LED,同埋點樣編寫程式令ESP32回應藍牙指令。教學亦會指導你實現呢個功能所需嘅程式碼組成部分(喺影片02:15位置)。
硬件講解
呢個項目嘅主要組件包括ESP32微控制器同RGB LED。ESP32係一個功能強大嘅模組,內置Wi-Fi同藍牙,好適合用喺物聯網應用。喺呢個項目入面,佢會充當伺服器,接收嚟自流動裝置嘅指令,並相應咁控制RGB LED。
RGB LED有四個引腳:一個公共引腳(無論係陽極定陰極)同三個用於個別顏色嘅引腳。公共引腳連接去電源或者接地,而其餘三個引腳就透過電阻連接去ESP32嘅GPIO引腳,用嚟限制電流同保護LED。呢個設置容許精確控制每種顏色嘅亮度,從而產生廣泛嘅顏色範圍。
數據手冊詳情
| 製造商 | SunFounder |
|---|---|
| 零件編號 | RGB LED |
| 公共引腳類型 | 共陽極 / 共陰極 |
| 正向電壓(V) | 2.0 - 3.2 V |
| 最大正向電流(A) | 20 mA |
| 典型電流(A) | 15 mA |
| 顏色解析度 | 8位元(0-255) |
| 封裝 | 通孔 / SMD |
- 確保使用合適嘅電阻值(通常係220歐姆)嚟限制流經每個LED通道嘅電流。
- 接線之前檢查公共引腳配置(陽極定陰極)。
- 使用PWM嚟做調光同混色,透過調整發送畀每粒LED嘅訊號。
- 接線時要小心避免短路;逐個引腳連接。
- 設置完成後逐粒顏色測試,確認接線正確。
接線說明

要將RGB LED接線到ESP32,首先將RGB LED放喺麵包板上。較長嘅引腳就係公共引腳,你要將佢連接去正電壓(如果係共陽極)或者接地(如果係共陰極)。如果你用緊共陽極,就將長引腳連接去ESP32嘅3.3V引腳。如果係共陰極,就將佢連接去GND引腳。
跟住,攞三粒220歐姆電阻,將每粒電阻嘅一端連接去LED嘅相應RGB引腳。將電阻嘅另一端連接去ESP32嘅GPIO引腳:將LED嘅紅色引腳連接去GPIO 27,綠色引腳連接去GPIO 26,藍色引腳連接去GPIO 25。最後,確保公共引腳根據你嘅配置(陽極定陰極)正確咁連接。
程式碼示例同講解
呢個項目嘅程式碼首先定義連接RGB LED嘅引腳。以下摘錄顯示咗點樣宣告引腳:
const int redPin = 27;
const int greenPin = 26;
const int bluePin = 25;
呢度,redPin、greenPin同bluePin被指派咗ESP32上RGB LED每個顏色通道嘅特定GPIO號碼。
喺setup函數入面,藍牙會被初始化,同時應用PWM設置。呢個摘錄示範咗呢個初始化過程:
void setup() {
Serial.begin(115200); // 初始化串行端口
setupBLE(); // 初始化藍牙BLE
ledcAttach(redPin, freq, resolution);
ledcAttach(greenPin, freq, resolution);
ledcAttach(bluePin, freq, resolution);
}
呢段程式碼初始化串行通訊,同時設置藍牙功能,並將RGB LED引腳連接到PWM通道以作控制。
最後,loop函數檢查收到嘅藍牙訊息,並相應咁調整LED顏色:
if (value == "red") {
setColor(255, 0, 0); // 紅色
Serial.println("red");
}
喺呢個部分,如果收到嘅值係「red」,LED就會用setColor函數設定為全紅色亮度。
如果想完整理解程式碼,建議觀看影片教學,完整程式碼會載入喺文章下面。
示範 / 預期效果
當所有嘢接好線並且上載咗程式碼之後,你應該可以透過藍牙從流動裝置控制RGB LED。透過發送好似「red」、「green」、「blue」等指令,你就會見到LED相應咁變色。如果你發送「LED_off」,RGB LED就會熄滅。記得檢查串行監視器有冇任何除錯訊息,以確認指令係咪正確咁收到(喺影片10:45位置)。
影片時間戳
- 00:00 開始
- 1:59 咩係RGB LED?
- 6:01 RGB顏色解釋
- 10:01 文檔頁面
- 11:19 接線解釋
- 13:34 喺Arduino IDE度選擇ESP32板同COM埠
- 15:15 Arduino代碼
- 18:02 示範用手機控制RGB LED
#include "BLEDevice.h"
#include "BLEServer.h"
#include "BLEUtils.h"
#include "BLE2902.h"
// Define RGB LED pins
const int redPin = 27;
const int greenPin = 26;
const int bluePin = 25;
// Define PWM frequency and resolution
const int freq = 5000;
const int resolution = 8;
// Define the Bluetooth device name
const char *bleName = "ESP32_Bluetooth";
// Define the received text and the time of the last message
String receivedText = "";
unsigned long lastMessageTime = 0;
// Define the UUIDs of the service and characteristics
#define SERVICE_UUID "8785d8b3-9d23-473b-aee5-3fabe2ba9583"
#define CHARACTERISTIC_UUID_RX "b2bcd13b-aab6-4660-92ae-40abf6941fce"
#define CHARACTERISTIC_UUID_TX "4219d86a-d701-4fd2-bd84-04db50f70fe2"
// Define the Bluetooth characteristic
BLECharacteristic *pCharacteristic;
void setup() {
Serial.begin(115200); // Initialize the serial port
setupBLE(); // Initialize the Bluetooth BLE
ledcAttach(redPin, freq, resolution);
ledcAttach(greenPin, freq, resolution);
ledcAttach(bluePin, freq, resolution);
}
void loop() {
// When the received text is not empty and the time since the last message is over 1 second
// Send a notification and print the received text
if (receivedText.length() > 0 && millis() - lastMessageTime > 1000) {
Serial.print("Received message: ");
Serial.println(receivedText);
pCharacteristic->setValue(receivedText.c_str());
pCharacteristic->notify();
receivedText = "";
}
// Read data from the serial port and send it to BLE characteristic
if (Serial.available() > 0) {
String str = Serial.readStringUntil('\n');
const char *newValue = str.c_str();
pCharacteristic->setValue(newValue);
pCharacteristic->notify();
}
}
// Define the BLE server callbacks
class MyServerCallbacks : public BLEServerCallbacks {
// Print the connection message when a client is connected
void onConnect(BLEServer *pServer) {
Serial.println("Connected");
}
// Print the disconnection message when a client is disconnected
void onDisconnect(BLEServer *pServer) {
Serial.println("Disconnected");
}
};
// Define the BLE characteristic callbacks
class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string value = std::string(pCharacteristic->getValue().c_str());
if (value == "led_off") {
setColor(0, 0, 0); // turn the RGB LED off
Serial.println("RGB LED turned off");
} else if (value == "red") {
setColor(255, 0, 0); // Red
Serial.println("red");
}
else if (value == "green") {
setColor(0, 255, 0); // green
Serial.println("green");
}
else if (value == "blue") {
setColor(0, 0, 255); // blue
Serial.println("blue");
}
else if (value == "yellow") {
setColor(255, 150, 0); // yellow
Serial.println("yellow");
}
else if (value == "purple") {
setColor(80, 0, 80); // purple
Serial.println("purple");
}
}
};
// Initialize the Bluetooth BLE
void setupBLE() {
BLEDevice::init(bleName); // Initialize the BLE device
BLEServer *pServer = BLEDevice::createServer(); // Create the BLE server
// Print the error message if the BLE server creation fails
if (pServer == nullptr) {
Serial.println("Error creating BLE server");
return;
}
pServer->setCallbacks(new MyServerCallbacks()); // Set the BLE server callbacks
// Create the BLE service
BLEService *pService = pServer->createService(SERVICE_UUID);
// Print the error message if the BLE service creation fails
if (pService == nullptr) {
Serial.println("Error creating BLE service");
return;
}
// Create the BLE characteristic for sending notifications
pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
pCharacteristic->addDescriptor(new BLE2902()); // Add the descriptor
// Create the BLE characteristic for receiving data
BLECharacteristic *pCharacteristicRX = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
pCharacteristicRX->setCallbacks(new MyCharacteristicCallbacks()); // Set the BLE characteristic callbacks
pService->start(); // Start the BLE service
pServer->getAdvertising()->start(); // Start advertising
Serial.println("Waiting for a client connection..."); // Wait for a client connection
}
void setColor(int red, int green, int blue) {
// For common-anode RGB LEDs, use 255 minus the color value
ledcWrite(redPin, red);
ledcWrite(greenPin, green);
ledcWrite(bluePin, blue);
}
Common Course Links
Common Course Files
資源與參考資料
-
文件记录ESP32 Tutorial 38/55 - SunFounder doc page for Bluetooth RGB LEDdocs.sunfounder.com
文件📁
冇文件可用。