Files
led-driver/main/ws2812.h
T
jimmyandClaude Haiku 5.5 89f996096c Add LED web UI with AP, Wi-Fi client, mDNS and patterns
Brings the led_strip example into the cpp app, targeting the ESP32-C3:
- Access point led-XXXXXX (open) plus a Wi-Fi client configured from the
  web Settings tab, with credentials stored in NVS and reconnect backoff
- mDNS as led.local with an HTTP service on port 80
- HTTP server with an embedded web UI and a JSON API for patterns and Wi-Fi
- Pattern runner for solid, rainbow, chase, breathe, blink, pulse,
  transition and circle on a 119-LED WS2812 strip (GPIO 10)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 00:02:49 +13:00

75 lines
2.4 KiB
C++

/*
* 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_ = {};
};