LED strip
ESP32-S3 的 RMT(Remote Control Transceiver,遠程控制收發器)外設最初設計用于紅外收發,但由于其數據格式的靈活性,RMT 可以擴展為通用的信號收發器,能夠發送或接收多種類型的信號;RMT 硬件包含物理層和數據鏈路層,最小數據單元為 RMT 符號,每個通道可獨立配置為發送或接收模式,常用于紅外遙控、通用序列發生器、多通道同步發送等場景
RMT 之所以可以用于 LED 控制,主要是因為其能夠精確地生成特定時序的波形信號,例如,WS2812 等數字 LED 燈帶對輸入信號的時序要求非常嚴格,RMT 可以將用戶的數據編碼為 RMT 格式,通過硬件生成精確的高低電平脈沖,從而驅動 LED 燈帶
參考資料:
led strip 庫
led strip 庫使用說明
led strip 官方示例
在 ESP-IDF 終端中輸入以下指令,執行 fullclean 再進行編譯,組件管理器會自動下載相應組件
idf.py add-dependency "espressif/led_strip^3.0.1~1"
#include <stdio.h>
#include <inttypes.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_chip_info.h"
#include "esp_flash.h"
#include "esp_system.h"
#include "led_strip.h"#define WS2812B_GPIO GPIO_NUM_18void app_main(void)
{led_strip_config_t strip_config = {.strip_gpio_num = WS2812B_GPIO,.max_leds = 2, // 兩個 LED.led_model = LED_MODEL_WS2812,.color_component_format = LED_STRIP_COLOR_COMPONENT_FMT_GRB, // 使用 GRB 格式.flags ={.invert_out = 0, // 不反轉輸出信號},};led_strip_rmt_config_t rmt_config = {.clk_src = RMT_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption.resolution_hz = 10 * 1000 * 1000, // RMT counter clock frequency: 10MHz.mem_block_symbols = 64, // the memory size of each RMT channel, in words (4 bytes).flags = {.with_dma = false, // DMA feature is available on chips like ESP32-S3/P4}};led_strip_handle_t strip_handle = NULL;ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &strip_handle)); // 創建 LED 條設備esp_err_t ret = led_strip_clear(strip_handle); // 清除 LED 條上的所有顏色if (ret != ESP_OK) {printf("Failed to initialize LED strip: %s\n", esp_err_to_name(ret));return;}ret = led_strip_set_pixel(strip_handle, 0, 255, 0, 0); // 設置第一個 LED 為紅色if (ret != ESP_OK) {printf("Failed to set pixel color: %s\n", esp_err_to_name(ret));return;}ret = led_strip_set_pixel(strip_handle, 1, 0, 255, 0); // 設置第一個 LED 為綠色if (ret != ESP_OK) {printf("Failed to set pixel color: %s\n", esp_err_to_name(ret));return;}ret = led_strip_refresh(strip_handle); // 刷新 LED 條以顯示顏色if (ret != ESP_OK) {printf("Failed to refresh LED strip: %s\n", esp_err_to_name(ret));return;}while (true) {vTaskDelay(pdMS_TO_TICKS(1000)); // Delay to allow system to stabilize}
}