Add WS2812 driver library and C++ LED strip example

Move the LED strip example to C++ and split the driver into a WS2812
class (ws2812.h/.cpp). The class takes the GPIO and LED count in its
constructor and provides set(), fill(), write(), setBrightness() and a
static hsv2rgb(). The RMT encoder is now internal to ws2812.cpp.

Also adds a top-level Makefile wrapping idf.py for Linux, macOS and
Windows, and a .gitignore for build output.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-10 22:22:50 +13:00
1 parent 0c80638647
commit d6cf56f105
9 files changed
+2626

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
build/
sdkconfig.old
+8
View File
@@ -0,0 +1,8 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
idf_build_set_property(MINIMAL_BUILD ON)
project(led_strip)
+56
View File
@@ -0,0 +1,56 @@
| Supported Targets | ESP32 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-H2 | ESP32-H21 | ESP32-H4 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 |
| ----------------- | ----- | -------- | -------- | -------- | -------- | --------- | -------- | -------- | -------- | -------- | --------- |
# RMT Transmit Example -- LED Strip
(See the README.md file in the upper level 'examples' directory for more information about examples.)
Almost any waveform can be generated by RMT peripheral, as long as a proper encoder is implemented. The RMT encoder is used to encode user data (e.g. RGB pixels) into format that can be recognized by hardware.
This example shows how to drive an addressable LED strip [WS2812](https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf) by implementing the encoder in [ws2812.cpp](main/ws2812.cpp).
## How to Use Example
### Hardware Required
* A development board with any supported Espressif SOC chip (see `Supported Targets` table above)
* A USB cable for Power supply and programming
* A WS2812 LED strip
Connection :
```
--- 5V
|
+
RMT_LED_STRIP_GPIO_NUM +------ +---|>| (WS2812 LED strip)
DI +
|
--- GND
```
The GPIO number used in this example can be changed according to your board, by the macro `RMT_LED_STRIP_GPIO_NUM` defined in the [source file](main/main.cpp). The number of LEDs can be changed as well by `EXAMPLE_LED_NUMBERS`.
### Build and Flash
Run `idf.py -p PORT flash monitor` to build, flash and monitor the project.
(To exit the serial monitor, type ``Ctrl-]``.)
See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
## Console Output
```
I (302) cpu_start: Starting scheduler on PRO CPU.
I (0) cpu_start: Starting scheduler on APP CPU.
I (323) example: Create RMT TX channel
I (343) example: Install led strip encoder
I (353) example: Start LED rainbow chase
```
After you seeing this log, you should see a rainbow chasing demonstration pattern. To change the chasing speed, you can update the `EXAMPLE_CHASE_SPEED_MS` value in [source file](main/main.cpp).
## Troubleshooting
For any technical queries, please open an [issue] (https://github.com/espressif/esp-idf/issues) on GitHub. We will get back to you soon.
+3
View File
@@ -0,0 +1,3 @@
idf_component_register(SRCS "main.cpp" "ws2812.cpp"
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio
INCLUDE_DIRS ".")
+42
View File
@@ -0,0 +1,42 @@
/*
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
#include <cstdint>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "ws2812.h"
#define RMT_LED_STRIP_GPIO_NUM GPIO_NUM_10
#define EXAMPLE_LED_NUMBERS 119
#define EXAMPLE_CHASE_SPEED_MS 1000
static const char *TAG = "example";
extern "C" void app_main(void)
{
ESP_LOGI(TAG, "Create LED strip");
WS2812 strip(RMT_LED_STRIP_GPIO_NUM, EXAMPLE_LED_NUMBERS);
ESP_LOGI(TAG, "Start LED rainbow chase");
uint16_t start_rgb = 0;
strip.setBrightness(16);
while (true) {
for (size_t i = 0; i < 3; i++) {
for (size_t j = i; j < strip.size(); j += 3) {
// Build RGB pixels
uint32_t hue = (j * 360 / strip.size() + start_rgb) % 360;
uint32_t red = 0, green = 0, blue = 0;
WS2812::hsv2rgb(hue, 100, 100, &red, &green, &blue);
strip.set(j, red, green, blue);
}
// Flush RGB values to LEDs
ESP_ERROR_CHECK(strip.write());
vTaskDelay(pdMS_TO_TICKS(EXAMPLE_CHASE_SPEED_MS));
}
start_rgb += 60;
}
}
+237
View File
@@ -0,0 +1,237 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "ws2812.h"
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "esp_check.h"
#include "esp_log.h"
static const char *TAG = "ws2812";
/* ---- RMT encoder: turns RGB bytes into WS2812 waveform symbols ---- */
typedef struct {
rmt_encoder_t base;
rmt_encoder_t *bytes_encoder;
rmt_encoder_t *copy_encoder;
int state;
rmt_symbol_word_t reset_code;
} rmt_ws2812_encoder_t;
RMT_ENCODER_FUNC_ATTR
static size_t rmt_encode_ws2812(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder;
rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder;
rmt_encode_state_t session_state = RMT_ENCODING_RESET;
rmt_encode_state_t state = RMT_ENCODING_RESET;
size_t encoded_symbols = 0;
switch (led_encoder->state) {
case 0: // send RGB data
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state);
if (session_state & RMT_ENCODING_COMPLETE) {
led_encoder->state = 1; // switch to next state when current encoding session finished
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
goto out; // yield if there's no free space for encoding artifacts
}
// fall-through
case 1: // send reset code
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code,
sizeof(led_encoder->reset_code), &session_state);
if (session_state & RMT_ENCODING_COMPLETE) {
led_encoder->state = RMT_ENCODING_RESET; // back to the initial encoding session
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_COMPLETE);
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_MEM_FULL);
goto out; // yield if there's no free space for encoding artifacts
}
}
out:
*ret_state = state;
return encoded_symbols;
}
static esp_err_t rmt_del_ws2812_encoder(rmt_encoder_t *encoder)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
rmt_del_encoder(led_encoder->bytes_encoder);
rmt_del_encoder(led_encoder->copy_encoder);
free(led_encoder);
return ESP_OK;
}
RMT_ENCODER_FUNC_ATTR
static esp_err_t rmt_ws2812_encoder_reset(rmt_encoder_t *encoder)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
rmt_encoder_reset(led_encoder->bytes_encoder);
rmt_encoder_reset(led_encoder->copy_encoder);
led_encoder->state = RMT_ENCODING_RESET;
return ESP_OK;
}
static esp_err_t new_ws2812_encoder(uint32_t resolution, rmt_encoder_handle_t *ret_encoder)
{
// Declared up front: the error path jumps forward to `err`, which C++ forbids
// across initialised declarations.
esp_err_t ret = ESP_OK;
rmt_ws2812_encoder_t *led_encoder = NULL;
rmt_bytes_encoder_config_t bytes_encoder_config = {};
rmt_copy_encoder_config_t copy_encoder_config = {};
uint32_t reset_ticks = 0;
ESP_GOTO_ON_FALSE(ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
led_encoder = static_cast<rmt_ws2812_encoder_t *>(rmt_alloc_encoder_mem(sizeof(rmt_ws2812_encoder_t)));
ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for ws2812 encoder");
led_encoder->base.encode = rmt_encode_ws2812;
led_encoder->base.del = rmt_del_ws2812_encoder;
led_encoder->base.reset = rmt_ws2812_encoder_reset;
// WS2812 timing
bytes_encoder_config.bit0.level0 = 1;
bytes_encoder_config.bit0.duration0 = 0.3 * resolution / 1000000; // T0H=0.3us
bytes_encoder_config.bit0.level1 = 0;
bytes_encoder_config.bit0.duration1 = 0.9 * resolution / 1000000; // T0L=0.9us
bytes_encoder_config.bit1.level0 = 1;
bytes_encoder_config.bit1.duration0 = 0.9 * resolution / 1000000; // T1H=0.9us
bytes_encoder_config.bit1.level1 = 0;
bytes_encoder_config.bit1.duration1 = 0.3 * resolution / 1000000; // T1L=0.3us
bytes_encoder_config.flags.msb_first = 1; // WS2812 transfer bit order: G7...G0R7...R0B7...B0
ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed");
ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(&copy_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed");
reset_ticks = resolution / 1000000 * 50 / 2; // reset code duration defaults to 50us
led_encoder->reset_code.level0 = 0;
led_encoder->reset_code.duration0 = reset_ticks;
led_encoder->reset_code.level1 = 0;
led_encoder->reset_code.duration1 = reset_ticks;
*ret_encoder = &led_encoder->base;
return ESP_OK;
err:
if (led_encoder) {
if (led_encoder->bytes_encoder) {
rmt_del_encoder(led_encoder->bytes_encoder);
}
if (led_encoder->copy_encoder) {
rmt_del_encoder(led_encoder->copy_encoder);
}
free(led_encoder);
}
return ret;
}
/* ---- WS2812 strip ---- */
WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz)
: num_leds_(num_leds), pixels_(num_leds * 3, 0), tx_pixels_(num_leds * 3, 0)
{
rmt_tx_channel_config_t tx_chan_config = {};
tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
tx_chan_config.gpio_num = gpio;
tx_chan_config.mem_block_symbols = 64; // larger blocks reduce flicker
tx_chan_config.resolution_hz = resolution_hz;
tx_chan_config.trans_queue_depth = 4;
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &channel_));
ESP_ERROR_CHECK(new_ws2812_encoder(resolution_hz, &encoder_));
ESP_ERROR_CHECK(rmt_enable(channel_));
tx_config_.loop_count = 0; // send once per write()
ESP_LOGI(TAG, "Strip ready: %zu LEDs on GPIO %d", num_leds_, (int)gpio);
}
WS2812::~WS2812()
{
if (channel_) {
rmt_tx_wait_all_done(channel_, portMAX_DELAY);
rmt_disable(channel_);
rmt_del_channel(channel_);
}
if (encoder_) {
encoder_->del(encoder_);
}
}
void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
{
if (index >= num_leds_) {
return;
}
uint8_t *p = &pixels_[index * 3];
p[0] = g;
p[1] = r;
p[2] = b;
}
void WS2812::fill(uint8_t r, uint8_t g, uint8_t b)
{
for (size_t i = 0; i < num_leds_; i++) {
set(i, r, g, b);
}
}
esp_err_t WS2812::write()
{
for (size_t i = 0; i < pixels_.size(); i++) {
tx_pixels_[i] = static_cast<uint8_t>(pixels_[i] * brightness_ / 255);
}
esp_err_t ret = rmt_transmit(channel_, encoder_, tx_pixels_.data(), tx_pixels_.size(), &tx_config_);
if (ret != ESP_OK) {
return ret;
}
return rmt_tx_wait_all_done(channel_, portMAX_DELAY);
}
void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
{
h %= 360; // h -> [0,360]
uint32_t rgb_max = v * 2.55f;
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
uint32_t i = h / 60;
uint32_t diff = h % 60;
// RGB adjustment amount by hue
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
switch (i) {
case 0:
*r = rgb_max;
*g = rgb_min + rgb_adj;
*b = rgb_min;
break;
case 1:
*r = rgb_max - rgb_adj;
*g = rgb_max;
*b = rgb_min;
break;
case 2:
*r = rgb_min;
*g = rgb_max;
*b = rgb_min + rgb_adj;
break;
case 3:
*r = rgb_min;
*g = rgb_max - rgb_adj;
*b = rgb_max;
break;
case 4:
*r = rgb_min + rgb_adj;
*g = rgb_min;
*b = rgb_max;
break;
default:
*r = rgb_max;
*g = rgb_min;
*b = rgb_max - rgb_adj;
break;
}
}
+74
View File
@@ -0,0 +1,74 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
#include "driver/gpio.h"
#include "driver/rmt_encoder.h"
#include "driver/rmt_tx.h"
#include "esp_err.h"
/**
* @brief WS2812-style addressable LED strip driven through the RMT peripheral.
*
* Pixel data is kept in a local buffer. set() and fill() only update that buffer;
* call write() to push the buffer out to the strip.
*/
class WS2812 {
public:
/**
* @param gpio GPIO connected to the strip's data input (DI)
* @param num_leds Number of LEDs in the strip
* @param resolution_hz RMT tick resolution; 10 MHz gives 0.1 us ticks, which WS2812 needs
*/
WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz = 10000000);
~WS2812();
WS2812(const WS2812 &) = delete;
WS2812 &operator=(const WS2812 &) = delete;
/** @brief Set one pixel in the buffer. Out-of-range indices are ignored. */
void set(size_t index, uint8_t r, uint8_t g, uint8_t b);
/** @brief Set every pixel in the buffer to the same colour. */
void fill(uint8_t r, uint8_t g, uint8_t b);
/**
* @brief Transmit the buffer to the strip and wait until the transfer finishes.
* @return ESP_OK on success, or an error from the RMT driver.
*/
esp_err_t write();
/** @brief Number of LEDs in the strip. */
size_t size() const { return num_leds_; }
/**
* @brief Set the output brightness, 0 (off) to 255 (full). Applied in write();
* the pixel buffer keeps its full-colour values. Defaults to 255.
*/
void setBrightness(uint8_t level) { brightness_ = level; }
/** @brief Current output brightness, 0-255. */
uint8_t brightness() const { return brightness_; }
/**
* @brief Convert HSV to RGB.
*
* h is the hue in degrees (wrapped to [0, 360)); s and v are 0-100 percent.
* Wiki: https://en.wikipedia.org/wiki/HSL_and_HSV
*/
static void hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b);
private:
size_t num_leds_;
std::vector<uint8_t> pixels_; // GRB byte order, 3 bytes per LED, as WS2812 expects
std::vector<uint8_t> tx_pixels_; // pixels_ scaled by brightness_, sent by write()
uint8_t brightness_ = 255;
rmt_channel_handle_t channel_ = nullptr;
rmt_encoder_handle_t encoder_ = nullptr;
rmt_transmit_config_t tx_config_ = {};
};
+15
View File
@@ -0,0 +1,15 @@
# SPDX-FileCopyrightText: 2021-2026 Espressif Systems (Shanghai) CO LTD
# SPDX-License-Identifier: CC0-1.0
import pytest
from pytest_embedded import Dut
from pytest_embedded_idf.utils import idf_parametrize
from pytest_embedded_idf.utils import soc_filtered_targets
@pytest.mark.generic
@idf_parametrize('target', soc_filtered_targets('SOC_RMT_SUPPORTED == 1'), indirect=['target'])
def test_led_strip_example(dut: Dut) -> None:
dut.expect_exact('example: Create RMT TX channel')
dut.expect_exact('example: Install led strip encoder')
dut.expect_exact('example: Enable RMT TX channel')
dut.expect_exact('example: Start LED rainbow chase')
+2189
View File
File diff suppressed because it is too large. Load diff