ESP32学习笔记_Components(1)——使用LED Strip组件点亮LED灯带
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}
}