Skip to main content

m5stack_core/driver/
sk6812.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! SK6812 addressable-RGB LED-strip driver (M5GO Battery Bottom light bars).
3//!
4//! The M5GO/FIRE Battery Bottom carries **10 SK6812 3535 RGB LEDs** (two bars of
5//! five) on a single one-wire data line. SK6812 uses the same NRZ bit encoding
6//! as WS2812 — 24 bits per LED in **G,R,B** order, MSB first — so this is driven
7//! by the RMT peripheral, one [`PulseCode`] per bit, like the 1-Wire driver.
8//!
9//! ## Pin (this is the subtle part across boards)
10//!
11//! The bottom's LED data line is wired to a fixed *physical* M-Bus pin (pin 23,
12//! the classic `I2S_OUT` position). That physical pin maps to a different GPIO
13//! per core, so pass the right one:
14//!   - **Fire27 (ESP32):**   `GPIO15`  (M-Bus pin 23)
15//!   - **CoreS3 (ESP32-S3):** `GPIO13`  (M-Bus pin 23)
16//!
17//! On **CoreS3** the bars are also unpowered until the M-Bus 5 V rail is enabled
18//! via the AW9523 — call [`crate::driver::aw9523b::Aw9523bDriver::enable_bus_5v`]
19//! first (see its guard notes). On the Fire that rail is always present.
20//!
21//! ## Timing
22//!
23//! RMT source clock 80 MHz, `clk_divider = 1` → 12.5 ns/tick. SK6812 nominal:
24//! T0H 0.3 µs / T0L 0.9 µs, T1H 0.6 µs / T1L 0.6 µs, reset ≥ 80 µs low.
25//!
26//! Refs: SK6812 datasheet; <https://docs.m5stack.com/en/base/m5go_bottom>
27use esp_hal::{
28    Async,
29    gpio::{AnyPin, Level},
30    peripherals::RMT,
31    rmt::{Channel, PulseCode, Rmt, Tx, TxChannelConfig, TxChannelCreator},
32    time::Rate,
33};
34use thiserror_no_std::Error;
35
36/// Max LEDs this driver will drive in one frame (M5GO bottom uses 10).
37/// Sets the size of the per-frame pulse buffer; bump if you chain more.
38pub const MAX_LEDS: usize = 16;
39
40/// Pulse codes for `N` LEDs: 24 bits each, plus the reset and the end marker.
41pub const fn codes_for(n: usize) -> usize {
42    n * 24 + 2
43}
44/// 24 bits/LED + trailing reset code + end marker.
45const MAX_CODES: usize = codes_for(MAX_LEDS);
46
47// Bit timing in 12.5 ns ticks (80 MHz, divider 1).
48const T0H: u16 = 24; // 0.30 µs
49const T0L: u16 = 72; // 0.90 µs
50const T1H: u16 = 48; // 0.60 µs
51const T1L: u16 = 48; // 0.60 µs
52const RESET_HALF: u16 = 4000; // 2 × 50 µs = 100 µs low latch
53
54/// A single LED colour (8 bits per channel).
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub struct Rgb {
57    pub r: u8,
58    pub g: u8,
59    pub b: u8,
60}
61
62impl Rgb {
63    pub const OFF: Rgb = Rgb { r: 0, g: 0, b: 0 };
64
65    pub const fn new(r: u8, g: u8, b: u8) -> Self {
66        Self { r, g, b }
67    }
68}
69
70#[derive(Debug, Error)]
71pub enum Sk6812Error {
72    #[error("Failed to init RMT")]
73    Rmt(#[from] esp_hal::rmt::Error),
74    #[error("RMT config error")]
75    Config,
76    #[error("Too many LEDs (max {MAX_LEDS})")]
77    TooManyLeds,
78}
79
80/// A whole frame for `leds` LEDs of one colour, built at COMPILE TIME.
81///
82/// For an indicator the colours are known when the firmware is built, so there
83/// is nothing to generate at runtime:
84///
85/// ```ignore
86/// const CODES: usize = codes_for(10);
87/// static GREEN: [PulseCode; CODES] = uniform_frame(Rgb::new(0, 32, 0), 10);
88/// leds.write_frame(&GREEN).await?;
89/// ```
90///
91/// That puts the frame in `.rodata` and costs **no RAM**, which is the point:
92/// the RMT wants a 32-bit code per bit, so ten LEDs are 968 B, and a runtime
93/// frame has to survive the transmit `await` — landing in the caller's future
94/// and so in `.bss`. On a fire27 that is the region with ~1.4 KiB of total
95/// slack, and its link assert rejects it.
96///
97/// `CODES` must be at least [`codes_for`]`(leds)`. Any surplus stays an end
98/// marker, which the RMT stops at.
99pub const fn uniform_frame<const CODES: usize>(color: Rgb, leds: usize) -> [PulseCode; CODES] {
100    assert!(
101        CODES >= codes_for(leds),
102        "frame too small for that many LEDs"
103    );
104    let one = PulseCode::new(Level::High, T1H, Level::Low, T1L);
105    let zero = PulseCode::new(Level::High, T0H, Level::Low, T0L);
106    let mut frame = [PulseCode::end_marker(); CODES];
107    let bytes = [color.g, color.r, color.b]; // SK6812 wire order, MSB first
108    let mut i = 0;
109    let mut led = 0;
110    while led < leds {
111        let mut b = 0;
112        while b < 3 {
113            let mut bit = 0;
114            while bit < 8 {
115                frame[i] = if bytes[b] & (0x80 >> bit) != 0 {
116                    one
117                } else {
118                    zero
119                };
120                i += 1;
121                bit += 1;
122            }
123            b += 1;
124        }
125        led += 1;
126    }
127    // Reset/latch, then the end marker the RMT requires.
128    frame[i] = PulseCode::new(Level::Low, RESET_HALF, Level::Low, RESET_HALF);
129    frame
130}
131
132/// The driver at its default size, for callers that do not care.
133///
134/// A const parameter's default does not take part in inference, so
135/// `Sk6812Driver::new(..)` on its own cannot be resolved — use this alias, or
136/// name a size with `Sk6812Driver::<{ codes_for(10) }>`.
137pub type Sk6812 = Sk6812Driver<MAX_CODES>;
138
139/// `CODES` sizes the pulse buffer: pass [`codes_for`] with the strip length.
140///
141/// It is a parameter because that buffer lives across the transmit `await`, so
142/// it sits in the caller's future — 24 codes per LED at 4 bytes each is 1.5 KiB
143/// for the default 16 LEDs, and a fire27's main-task stack region has about
144/// that much slack in total (its link assert is what found this). A board with
145/// ten LEDs should pay for ten: `Sk6812Driver::<{ codes_for(10) }>`.
146///
147/// It is the code count rather than the LED count because
148/// `generic_const_exprs` is unstable, so the buffer length cannot be computed
149/// from a generic.
150pub struct Sk6812Driver<const CODES: usize = MAX_CODES> {
151    channel: Channel<'static, Async, Tx>,
152}
153
154impl<const CODES: usize> Sk6812Driver<CODES> {
155    /// Claim the WHOLE RMT peripheral (TX channel 0) and drive `pin` as the LED
156    /// data line.
157    ///
158    /// Convenience for an app that uses RMT for nothing else. If it also reads
159    /// DS18B20 sensors, use [`Self::with_channel`] and
160    /// [`crate::driver::ds18b20::Ds18b20Driver::with_channels`] with channels
161    /// from [`crate::board::rmt::RmtChannels`].
162    pub fn new(rmt: RMT<'static>, pin: AnyPin<'static>) -> Result<Self, Sk6812Error> {
163        let rmt = Rmt::new(rmt, Rate::from_mhz(80))
164            .map_err(|_| Sk6812Error::Config)?
165            .into_async();
166        Self::with_channel(rmt.channel0, pin, crate::board::rmt::ALL_TX_BLOCKS)
167    }
168
169    /// Drive `pin` as the LED data line using the given RMT TX channel, which
170    /// claims `blocks` of channel RAM from that channel upwards.
171    ///
172    /// Leaves the rest of the peripheral free — which is the whole point: the
173    /// 1-Wire driver needs a TX and an RX channel of its own, and both drivers
174    /// used to take the peripheral by value, so a board could have temperature
175    /// sensing or light bars but not both.
176    ///
177    /// `blocks` decides whether a frame transmits straight out of channel RAM
178    /// or is refilled by the CPU mid-stream, which is a visible correctness
179    /// matter rather than a tuning knob — [`crate::board::rmt::LED_BLOCKS`] is
180    /// the board's answer, and its module docs carry the reasoning. The claim
181    /// must not reach another channel in use, or `configure_tx` rejects it.
182    pub fn with_channel(
183        tx: impl TxChannelCreator<'static, Async>,
184        pin: AnyPin<'static>,
185        blocks: u8,
186    ) -> Result<Self, Sk6812Error> {
187        let channel = tx
188            .configure_tx(
189                &TxChannelConfig::default()
190                    .with_clk_divider(1)
191                    .with_idle_output(true)
192                    .with_idle_output_level(Level::Low)
193                    .with_memsize(blocks),
194            )
195            .map_err(|_| Sk6812Error::Config)?
196            .with_pin(pin);
197        Ok(Self { channel })
198    }
199
200    /// Push a frame of colours to the strip (LED 0 first). Holds the line low
201    /// afterwards to latch. Errors if the frame needs more than `CODES` pulse
202    /// codes, i.e. more LEDs than this instance was sized for.
203    pub async fn write(&mut self, colors: &[Rgb]) -> Result<(), Sk6812Error> {
204        if codes_for(colors.len()) > CODES {
205            return Err(Sk6812Error::TooManyLeds);
206        }
207        let one = PulseCode::new(Level::High, T1H, Level::Low, T1L);
208        let zero = PulseCode::new(Level::High, T0H, Level::Low, T0L);
209
210        let mut buf: heapless::Vec<PulseCode, CODES> = heapless::Vec::new();
211        for c in colors {
212            // SK6812 wire order is G, R, B, MSB first.
213            for byte in [c.g, c.r, c.b] {
214                for bit in 0..8 {
215                    let code = if byte & (0x80 >> bit) != 0 { one } else { zero };
216                    // Buffer holds MAX_LEDS*24 + 2 and we checked the LED count.
217                    let _ = buf.push(code);
218                }
219            }
220        }
221        // Trailing low pulse → reset/latch (≥ 80 µs), then the required end
222        // marker (RMT errors with `EndMarkerMissing` without a final zero-length
223        // code; the marker idles the line low, holding the latch).
224        let _ = buf.push(PulseCode::new(
225            Level::Low,
226            RESET_HALF,
227            Level::Low,
228            RESET_HALF,
229        ));
230        let _ = buf.push(PulseCode::end_marker());
231
232        self.channel.transmit(&buf).await?;
233        Ok(())
234    }
235
236    /// Transmit a frame built elsewhere — typically a `const` one from
237    /// [`uniform_frame`], living in flash.
238    ///
239    /// The only path that needs no frame storage in RAM.
240    pub async fn write_frame(&mut self, frame: &[PulseCode]) -> Result<(), Sk6812Error> {
241        self.channel.transmit(frame).await?;
242        Ok(())
243    }
244
245    /// Convenience: set every LED in a strip of `len` to the same colour.
246    pub async fn fill(&mut self, color: Rgb, len: usize) -> Result<(), Sk6812Error> {
247        let len = len.min(MAX_LEDS);
248        let mut frame: heapless::Vec<Rgb, MAX_LEDS> = heapless::Vec::new();
249        // `write` rejects a frame longer than `CODES` allows, so a strip
250        // sized for ten LEDs cannot be asked to light sixteen.
251        for _ in 0..len {
252            let _ = frame.push(color);
253        }
254        self.write(&frame).await
255    }
256}