esp-hal-smartled 0.16.0

RMT peripheral adapter for smart LEDs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! This adapter allows for the use of an RMT output channel to easily interact
//! with RGB LEDs and use the convenience functions of the
//! [`smart-leds`](https://crates.io/crates/smart-leds) crate.
//!
//! This is a simple implementation where every LED is adressed in an
//! individual RMT operation. This is working perfectly fine in blocking mode,
//! but in case this is used in combination with interrupts that might disturb
//! the sequential sending, an alternative implementation (addressing the LEDs
//! in a sequence in a single RMT send operation) might be required!
//!
//! ## Example
//!
//! ```rust
//! #![no_std]
//! #![no_main]
//!
//! use esp_backtrace as _;
//! use esp_hal::{rmt::Rmt, time::Rate, Config};
//! use esp_hal_smartled::{smartLedBuffer, SmartLedsAdapter};
//! use smart_leds::{brightness, colors::RED, SmartLedsWrite as _};
//!
//! #[esp_hal::main]
//! fn main() -> ! {
//!     let p = esp_hal::init(Config::default());
//!     let mut led = {
//!         let frequency = Rate::from_mhz(80);
//!         let rmt = Rmt::new(p.RMT, frequency).expect("Failed to initialize RMT0");
//!         SmartLedsAdapter::new(rmt.channel0, p.GPIO2, smartLedBuffer!(1))
//!     };
//!     let level = 10;
//!     led.write(brightness([RED].into_iter(), level)).unwrap();
//!     loop {} // loop forever
//! }
//! ```
//!
//! ## Feature Flags
#![doc = document_features::document_features!()]
#![doc(html_logo_url = "https://avatars.githubusercontent.com/u/46717278")]
#![deny(missing_docs)]
#![no_std]

use core::{fmt::Debug, marker::PhantomData, slice::IterMut};

use esp_hal::{
    Async, Blocking,
    clock::Clocks,
    gpio::{Level, interconnect::PeripheralOutput},
    rmt::{
        Channel, Error as RmtError, PulseCode, RawChannelAccess, TxChannel, TxChannelAsync,
        TxChannelConfig, TxChannelCreator, TxChannelInternal,
    },
};
use rgb::Grb;
use smart_leds_trait::{SmartLedsWrite, SmartLedsWriteAsync};

// Required RMT RAM to drive one LED.
// number of channels (r,g,b -> 3) * pulses per channel 8)
const RMT_RAM_ONE_LED: usize = 3 * 8;
const RMT_RAM_ONE_RBGW_LED: usize = 4 * 8;

const SK68XX_CODE_PERIOD: u32 = 1250; // 800kHz
const SK68XX_T0H_NS: u32 = 400; // 300ns per SK6812 datasheet, 400 per WS2812. Some require >350ns for T0H. Others <500ns for T0H.
const SK68XX_T0L_NS: u32 = SK68XX_CODE_PERIOD - SK68XX_T0H_NS;
const SK68XX_T1H_NS: u32 = 850; // 900ns per SK6812 datasheet, 850 per WS2812. > 550ns is sometimes enough. Some require T1H >= 2 * T0H. Some require > 300ns T1L.
const SK68XX_T1L_NS: u32 = SK68XX_CODE_PERIOD - SK68XX_T1H_NS;

/// All types of errors that can happen during the conversion and transmission
/// of LED commands
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum LedAdapterError {
    /// Raised in the event that the provided data container is not large enough
    BufferSizeExceeded,
    /// Raised if something goes wrong in the transmission,
    TransmissionError(RmtError),
}

impl From<RmtError> for LedAdapterError {
    fn from(e: RmtError) -> Self {
        LedAdapterError::TransmissionError(e)
    }
}

fn led_pulses_for_clock(src_clock: u32) -> (u32, u32) {
    (
        PulseCode::new(
            Level::High,
            ((SK68XX_T0H_NS * src_clock) / 1000) as u16,
            Level::Low,
            ((SK68XX_T0L_NS * src_clock) / 1000) as u16,
        ),
        PulseCode::new(
            Level::High,
            ((SK68XX_T1H_NS * src_clock) / 1000) as u16,
            Level::Low,
            ((SK68XX_T1L_NS * src_clock) / 1000) as u16,
        ),
    )
}

fn led_config() -> TxChannelConfig {
    TxChannelConfig::default()
        .with_clk_divider(1)
        .with_idle_output_level(Level::Low)
        .with_carrier_modulation(false)
        .with_idle_output(true)
}

fn convert_to_pulses(
    value: &[u8],
    mut_iter: &mut IterMut<u32>,
    pulses: (u32, u32),
) -> Result<(), LedAdapterError> {
    for v in value {
        convert_rgb_channel_to_pulses(*v, mut_iter, pulses)?;
    }
    Ok(())
}

fn convert_rgb_channel_to_pulses(
    channel_value: u8,
    mut_iter: &mut IterMut<u32>,
    pulses: (u32, u32),
) -> Result<(), LedAdapterError> {
    for position in [128, 64, 32, 16, 8, 4, 2, 1] {
        *mut_iter.next().ok_or(LedAdapterError::BufferSizeExceeded)? =
            match channel_value & position {
                0 => pulses.0,
                _ => pulses.1,
            }
    }

    Ok(())
}

/// Function to calculate the required RMT buffer size for a given number of RGB LEDs when using
/// the blocking API.
///
/// For RGBW leds use [buffer_size_rgbw].
///
/// This buffer size is calculated for the synchronous API provided by the [SmartLedsAdapter].
/// [buffer_size_async] should be used for the asynchronous API.
pub const fn buffer_size(num_leds: usize) -> usize {
    // 1 additional pulse for the end delimiter
    num_leds * RMT_RAM_ONE_LED + 1
}

/// Function to calculate the required RMT buffer size for a given number of RGBW LEDs when using
/// the blocking API.
///
/// For RGB leds use [buffer_size_rgb].
///
/// This buffer size is calculated for the synchronous API provided by the [SmartLedsAdapter].
/// [buffer_size_async] should be used for the asynchronous API.
pub const fn buffer_size_rgbw(num_leds: usize) -> usize {
    // 1 additional pulse for the end delimiter
    num_leds * RMT_RAM_ONE_RBGW_LED + 1
}

/// Macro to allocate a buffer sized for a specific number of LEDs to be
/// addressed.
///
/// For RGBW leds, use `[smart_led_buffer!(NUM_LEDS, RGBW)]` where `NUM_LEDS` is your number of leds.
///
/// Attempting to use more LEDs that the buffer is configured for will result in
/// an `LedAdapterError:BufferSizeExceeded` error.
#[macro_export]
macro_rules! smart_led_buffer {
    ( $num_leds: expr ) => {
        [0u32; $crate::buffer_size($num_leds)]
    };
    ( $num_leds: expr; RGBW ) => {
        [0u32; $crate::buffer_size_rgbw($num_leds)]
    };
}

/// Deprecated alias for [smart_led_buffer] macro.
#[macro_export]
#[deprecated]
macro_rules! smartLedBuffer {
    ( $num_leds: expr ) => {
        smart_led_buffer!($num_leds);
    };
}

/// Adapter taking an RMT channel and a specific pin and providing RGB LED
/// interaction functionality using the `smart-leds` crate
pub struct SmartLedsAdapter<TX, const BUFFER_SIZE: usize, Color = Grb<u8>>
where
    TX: RawChannelAccess + TxChannelInternal + 'static,
{
    channel: Option<Channel<Blocking, TX>>,
    rmt_buffer: [u32; BUFFER_SIZE],
    pulses: (u32, u32),
    color: PhantomData<Color>,
}

impl<'d, TX, const BUFFER_SIZE: usize> SmartLedsAdapter<TX, BUFFER_SIZE, Grb<u8>>
where
    TX: RawChannelAccess + TxChannelInternal + 'static,
{
    /// Create a new adapter object that drives the pin using the RMT channel.
    pub fn new<C, O>(channel: C, pin: O, rmt_buffer: [u32; BUFFER_SIZE]) -> Self
    where
        O: PeripheralOutput<'d>,
        C: TxChannelCreator<'d, Blocking, Raw = TX>,
    {
        Self::new_with_color(channel, pin, rmt_buffer)
    }
}

impl<'d, TX, const BUFFER_SIZE: usize, Color> SmartLedsAdapter<TX, BUFFER_SIZE, Color>
where
    TX: RawChannelAccess + TxChannelInternal + 'static,
    Color: rgb::ComponentSlice<u8>,
{
    /// Create a new adapter object that drives the pin using the RMT channel.
    pub fn new_with_color<C, O>(
        channel: C,
        pin: O,
        rmt_buffer: [u32; BUFFER_SIZE],
    ) -> SmartLedsAdapter<TX, BUFFER_SIZE, Color>
    where
        O: PeripheralOutput<'d>,
        C: TxChannelCreator<'d, Blocking, Raw = TX>,
    {
        let channel = channel.configure_tx(pin, led_config()).unwrap();

        // Assume the RMT peripheral is set up to use the APB clock
        let src_clock = Clocks::get().apb_clock.as_mhz();

        Self {
            channel: Some(channel),
            rmt_buffer,
            pulses: led_pulses_for_clock(src_clock),
            color: PhantomData,
        }
    }
}

impl<TX, const BUFFER_SIZE: usize, Color> SmartLedsWrite
    for SmartLedsAdapter<TX, BUFFER_SIZE, Color>
where
    TX: RawChannelAccess + TxChannelInternal + 'static,
    Color: rgb::ComponentSlice<u8>,
{
    type Error = LedAdapterError;
    type Color = Color;

    /// Convert all items of the iterator to the RMT format and
    /// add them to internal buffer, then start a singular RMT operation
    /// based on that buffer.
    fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
    where
        T: IntoIterator<Item = I>,
        I: Into<Self::Color>,
    {
        // We always start from the beginning of the buffer
        let mut seq_iter = self.rmt_buffer.iter_mut();

        // Add all converted iterator items to the buffer.
        // This will result in an `BufferSizeExceeded` error in case
        // the iterator provides more elements than the buffer can take.
        for item in iterator {
            convert_to_pulses(item.into().as_slice(), &mut seq_iter, self.pulses)?;
        }

        // Finally, add an end element.
        *seq_iter.next().ok_or(LedAdapterError::BufferSizeExceeded)? = 0;

        // Perform the actual RMT operation. We use the u32 values here right away.
        let channel = self.channel.take().unwrap();
        match channel.transmit(&self.rmt_buffer)?.wait() {
            Ok(chan) => {
                self.channel = Some(chan);
                Ok(())
            }
            Err((e, chan)) => {
                self.channel = Some(chan);
                Err(LedAdapterError::TransmissionError(e))
            }
        }
    }
}

// Support for asynchronous and non-blocking use of the RMT peripheral to drive smart LEDs.

/// Function to calculate the required RMT buffer size for a given number of RGB LEDs when using
/// the asynchronous API.
///
/// Use [buffer_size_async_rgbw] for RGBW leds.
///
/// This buffer size is calculated for the asynchronous API provided by the
/// [SmartLedsAdapterAsync]. [buffer_size] should be used for the synchronous API.
pub const fn buffer_size_async(num_leds: usize) -> usize {
    // 1 byte end delimiter for each transfer.
    num_leds * (RMT_RAM_ONE_LED + 1)
}

/// Function to calculate the required RMT buffer size for a given number of RGBW LEDs when using
/// the asynchronous API.
///
/// Use [buffer_size_async] for RGB leds.
///
/// This buffer size is calculated for the asynchronous API provided by the
/// [SmartLedsAdapterAsync]. [buffer_size] should be used for the synchronous API.
pub const fn buffer_size_async_rgbw(num_leds: usize) -> usize {
    // 1 byte end delimiter for each transfer.
    num_leds * (RMT_RAM_ONE_RBGW_LED + 1)
}

/// Adapter taking an RMT channel and a specific pin and providing RGB LED
/// interaction functionality.
pub struct SmartLedsAdapterAsync<Tx, const BUFFER_SIZE: usize, Color = Grb<u8>>
where
    Tx: RawChannelAccess + TxChannelInternal + 'static,
{
    channel: Channel<Async, Tx>,
    rmt_buffer: [u32; BUFFER_SIZE],
    pulses: (u32, u32),
    color: PhantomData<Color>,
}

impl<'d, Tx, const BUFFER_SIZE: usize> SmartLedsAdapterAsync<Tx, BUFFER_SIZE, Grb<u8>>
where
    Tx: RawChannelAccess + TxChannelInternal + 'static,
{
    /// Create a new adapter object that drives the pin using the RMT channel.
    pub fn new<C, O>(channel: C, pin: O, rmt_buffer: [u32; BUFFER_SIZE]) -> Self
    where
        O: PeripheralOutput<'d>,
        C: TxChannelCreator<'d, Async, Raw = Tx>,
    {
        Self::new_with_color(channel, pin, rmt_buffer)
    }
}

impl<'d, Tx, const BUFFER_SIZE: usize, Color> SmartLedsAdapterAsync<Tx, BUFFER_SIZE, Color>
where
    Tx: RawChannelAccess + TxChannelInternal + 'static,
    Color: rgb::ComponentSlice<u8>,
{
    /// Create a new adapter object that drives the pin using the RMT channel.
    pub fn new_with_color<C, O>(
        channel: C,
        pin: O,
        rmt_buffer: [u32; BUFFER_SIZE],
    ) -> SmartLedsAdapterAsync<Tx, BUFFER_SIZE, Color>
    where
        O: PeripheralOutput<'d>,
        C: TxChannelCreator<'d, Async, Raw = Tx>,
    {
        let channel = channel.configure_tx(pin, led_config()).unwrap();

        // Assume the RMT peripheral is set up to use the APB clock
        let src_clock = Clocks::get().apb_clock.as_mhz();

        Self {
            channel,
            rmt_buffer,
            pulses: led_pulses_for_clock(src_clock),
            color: PhantomData,
        }
    }

    fn prepare_rmt_buffer<I: Into<Color>>(
        &mut self,
        iterator: impl IntoIterator<Item = I>,
    ) -> Result<(), LedAdapterError> {
        // We always start from the beginning of the buffer
        let mut seq_iter = self.rmt_buffer.iter_mut();

        // Add all converted iterator items to the buffer.
        // This will result in an `BufferSizeExceeded` error in case
        // the iterator provides more elements than the buffer can take.
        for item in iterator {
            Self::convert_to_pulses(item.into().as_slice(), &mut seq_iter, self.pulses)?;
        }
        Ok(())
    }

    /// Async sends one pixel at a time so needs a delimiter after each pixel
    fn convert_to_pulses(
        value: &[u8],
        mut_iter: &mut IterMut<u32>,
        pulses: (u32, u32),
    ) -> Result<(), LedAdapterError> {
        for v in value {
            convert_rgb_channel_to_pulses(*v, mut_iter, pulses)?;
        }
        *mut_iter.next().ok_or(LedAdapterError::BufferSizeExceeded)? = 0;
        Ok(())
    }
}

impl<Tx, const BUFFER_SIZE: usize, Color> SmartLedsWriteAsync
    for SmartLedsAdapterAsync<Tx, BUFFER_SIZE, Color>
where
    Tx: RawChannelAccess + TxChannelInternal + 'static,
    Color: rgb::ComponentSlice<u8>,
{
    type Error = LedAdapterError;
    type Color = Color;

    /// Convert all items of the iterator to the RMT format and
    /// add them to internal buffer, then start perform all asynchronous operations based on
    /// that buffer.
    async fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
    where
        T: IntoIterator<Item = I>,
        I: Into<Self::Color>,
    {
        self.prepare_rmt_buffer(iterator)?;
        for chunk in self.rmt_buffer.chunks(RMT_RAM_ONE_LED + 1) {
            self.channel
                .transmit(chunk)
                .await
                .map_err(LedAdapterError::TransmissionError)?;
        }
        Ok(())
    }
}