refactor(led): drive the strip through the smart-leds traits
Replaces the hand-rolled Rgb type, HSV conversion and brightness scaling with RGB8, hsv2rgb, gamma and brightness from smart-leds, and exposes the driver as SmartLedsWriteAsync. The RMT symbol encoding stays in-tree: no upstream RMT driver currently targets esp-hal 1.1.
This commit is contained in:
1 parent
bb81182daa
commit
e021ab751a
6 files changed
+102
-90
No files matched your search
+1
-1
@@ -57,7 +57,7 @@ pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let delta = TRANSITIONS[usize::from((previous << 2) | current)];
|
||||
let delta = TRANSITIONS[(previous << 2) | current];
|
||||
previous = current;
|
||||
if delta == 0 {
|
||||
continue;
|
||||
|
||||
+27
-41
@@ -6,15 +6,19 @@
|
||||
|
||||
use core::sync::atomic::AtomicBool;
|
||||
use core::sync::atomic::AtomicU8;
|
||||
use core::sync::atomic::AtomicU16;
|
||||
use core::sync::atomic::Ordering;
|
||||
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::signal::Signal;
|
||||
use smart_leds::RGB8;
|
||||
use smart_leds::SmartLedsWriteAsync;
|
||||
use smart_leds::brightness as scale_brightness;
|
||||
use smart_leds::gamma;
|
||||
use smart_leds::hsv::Hsv;
|
||||
use smart_leds::hsv::hsv2rgb;
|
||||
|
||||
use crate::config::LED_COUNT;
|
||||
use crate::config::MAX_DUTY;
|
||||
use crate::ws2812::Rgb;
|
||||
use crate::ws2812::Ws2812;
|
||||
|
||||
/// What a turn of the encoder adjusts.
|
||||
@@ -26,7 +30,7 @@ pub enum Mode {
|
||||
|
||||
static ON: AtomicBool = AtomicBool::new(false);
|
||||
static BRIGHTNESS: AtomicU8 = AtomicU8::new(128);
|
||||
static HUE: AtomicU16 = AtomicU16::new(0);
|
||||
static HUE: AtomicU8 = AtomicU8::new(0);
|
||||
static HUE_MODE: AtomicBool = AtomicBool::new(false);
|
||||
static DIRTY: Signal<CriticalSectionRawMutex, ()> = Signal::new();
|
||||
|
||||
@@ -57,13 +61,13 @@ pub fn adjust_brightness(delta: i16) {
|
||||
DIRTY.signal(());
|
||||
}
|
||||
|
||||
pub fn hue() -> u16 {
|
||||
pub fn hue() -> u8 {
|
||||
HUE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Hue is a circle, so this one wraps.
|
||||
/// Hue is a circle, so this one wraps. `smart-leds` spans it over a full u8.
|
||||
pub fn adjust_hue(delta: i16) {
|
||||
let hue = (i32::from(hue()) + i32::from(delta)).rem_euclid(360) as u16;
|
||||
let hue = hue().wrapping_add_signed(delta as i8);
|
||||
HUE.store(hue, Ordering::Relaxed);
|
||||
DIRTY.signal(());
|
||||
}
|
||||
@@ -83,47 +87,29 @@ pub fn toggle_mode() -> Mode {
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn render_task(mut strip: Ws2812<'static>) {
|
||||
let mut frame = [Rgb::BLACK; LED_COUNT];
|
||||
let mut frame = [RGB8::default(); LED_COUNT];
|
||||
|
||||
loop {
|
||||
let colour = if is_on() {
|
||||
let level = (u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8;
|
||||
hsv_to_rgb(hue(), 255, 255).scaled(level)
|
||||
} else {
|
||||
Rgb::BLACK
|
||||
};
|
||||
frame.fill(colour);
|
||||
frame.fill(hsv2rgb(Hsv {
|
||||
hue: hue(),
|
||||
sat: 255,
|
||||
val: 255,
|
||||
}));
|
||||
|
||||
if let Err(e) = strip.write(&frame).await {
|
||||
// off is just zero brightness, so the colour survives a power cycle of
|
||||
// the strip output and comes back as it was
|
||||
let level = if is_on() {
|
||||
(u16::from(brightness()) * u16::from(MAX_DUTY) / 255) as u8
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
// gamma before brightness, as smart-leds requires
|
||||
let pixels = scale_brightness(gamma(frame.iter().copied()), level);
|
||||
if let Err(e) = strip.write(pixels).await {
|
||||
log::warn!("strip write failed: {e:?}");
|
||||
}
|
||||
|
||||
DIRTY.wait().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// `hue` in degrees, `saturation` and `value` as 0..=255.
|
||||
fn hsv_to_rgb(hue: u16, saturation: u8, value: u8) -> Rgb {
|
||||
if saturation == 0 {
|
||||
return Rgb::new(value, value, value);
|
||||
}
|
||||
|
||||
let sector = u32::from(hue % 360) / 60;
|
||||
let offset = u32::from(hue % 360) % 60;
|
||||
let v = u32::from(value);
|
||||
let s = u32::from(saturation);
|
||||
|
||||
let p = (v * (255 - s) / 255) as u8;
|
||||
let q = (v * (255 - s * offset / 60) / 255) as u8;
|
||||
let t = (v * (255 - s * (60 - offset) / 60) / 255) as u8;
|
||||
let v = value;
|
||||
|
||||
match sector {
|
||||
0 => Rgb::new(v, t, p),
|
||||
1 => Rgb::new(q, v, p),
|
||||
2 => Rgb::new(p, v, t),
|
||||
3 => Rgb::new(p, q, v),
|
||||
4 => Rgb::new(t, p, v),
|
||||
_ => Rgb::new(v, p, q),
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -38,8 +38,8 @@ static STACK: StaticCell<Stack> = StaticCell::new();
|
||||
/// Brightness units per detent.
|
||||
const BRIGHTNESS_STEP: i16 = 8;
|
||||
|
||||
/// Degrees of hue per detent.
|
||||
const HUE_STEP: i16 = 6;
|
||||
/// Hue per detent, in 1/256ths of the colour circle (~5.6 degrees).
|
||||
const HUE_STEP: i16 = 4;
|
||||
|
||||
#[esp_rtos::main]
|
||||
async fn main(spawner: embassy_executor::Spawner) -> ! {
|
||||
|
||||
+39
-46
@@ -2,12 +2,18 @@
|
||||
//!
|
||||
//! The RMT clock is divided to 12.5 ns per tick, so each of the 24 colour bits
|
||||
//! becomes one `PulseCode` whose high and low durations encode a 0 or a 1.
|
||||
//!
|
||||
//! Only the symbol encoding lives here; colour types, gamma and brightness
|
||||
//! come from `smart-leds`, and the strip is driven through its async write
|
||||
//! trait so an upstream driver can replace this one without touching callers.
|
||||
|
||||
use esp_hal::Async;
|
||||
use esp_hal::gpio::Level;
|
||||
use esp_hal::rmt::Channel;
|
||||
use esp_hal::rmt::PulseCode;
|
||||
use esp_hal::rmt::Tx;
|
||||
use smart_leds_trait::RGB8;
|
||||
use smart_leds_trait::SmartLedsWriteAsync;
|
||||
|
||||
use crate::config::LED_COUNT;
|
||||
|
||||
@@ -20,37 +26,6 @@ const T1L: u16 = 36; // 0.45 us
|
||||
/// Pulse codes for a whole frame, plus the terminating end marker.
|
||||
const PULSE_COUNT: usize = LED_COUNT * 24 + 1;
|
||||
|
||||
/// A colour in the order the application thinks about it; the wire order
|
||||
/// (green first) is applied when encoding.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
|
||||
pub struct Rgb {
|
||||
pub r: u8,
|
||||
pub g: u8,
|
||||
pub b: u8,
|
||||
}
|
||||
|
||||
impl Rgb {
|
||||
pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
|
||||
|
||||
pub const fn new(r: u8, g: u8, b: u8) -> Self {
|
||||
Self { r, g, b }
|
||||
}
|
||||
|
||||
/// Scales every channel by `level / 255`, rounding so that a non-zero
|
||||
/// channel at a non-zero level never collapses to off.
|
||||
#[must_use]
|
||||
pub const fn scaled(self, level: u8) -> Self {
|
||||
const fn scale(channel: u8, level: u8) -> u8 {
|
||||
((channel as u16 * level as u16 + 127) / 255) as u8
|
||||
}
|
||||
Self {
|
||||
r: scale(self.r, level),
|
||||
g: scale(self.g, level),
|
||||
b: scale(self.b, level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Ws2812<'d> {
|
||||
channel: Channel<'d, Async, Tx>,
|
||||
pulses: [PulseCode; PULSE_COUNT],
|
||||
@@ -62,24 +37,42 @@ impl<'d> Ws2812<'d> {
|
||||
pulses[PULSE_COUNT - 1] = PulseCode::end_marker();
|
||||
Self { channel, pulses }
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes `pixels` and clocks the frame out.
|
||||
///
|
||||
/// A frame shorter than the strip leaves the remaining pixels dark.
|
||||
pub async fn write(&mut self, pixels: &[Rgb]) -> Result<(), esp_hal::rmt::Error> {
|
||||
for (led, slot) in self.pulses[..LED_COUNT * 24].chunks_exact_mut(24).enumerate() {
|
||||
let colour = pixels.get(led).copied().unwrap_or(Rgb::BLACK);
|
||||
// WS2812B latches GRB, most significant bit first
|
||||
let word = u32::from(colour.g) << 16 | u32::from(colour.r) << 8 | u32::from(colour.b);
|
||||
for (bit, code) in slot.iter_mut().enumerate() {
|
||||
*code = if word & (1 << (23 - bit)) != 0 {
|
||||
PulseCode::new(Level::High, T1H, Level::Low, T1L)
|
||||
} else {
|
||||
PulseCode::new(Level::High, T0H, Level::Low, T0L)
|
||||
};
|
||||
}
|
||||
impl SmartLedsWriteAsync for Ws2812<'_> {
|
||||
type Error = esp_hal::rmt::Error;
|
||||
type Color = RGB8;
|
||||
|
||||
/// An iterator shorter than the strip leaves the remaining pixels dark; a
|
||||
/// longer one is truncated.
|
||||
async fn write<T, I>(&mut self, iterator: T) -> Result<(), Self::Error>
|
||||
where
|
||||
T: IntoIterator<Item = I>,
|
||||
I: Into<Self::Color>,
|
||||
{
|
||||
let (slots, _) = self.pulses[..LED_COUNT * 24].as_chunks_mut::<24>();
|
||||
let mut slots = slots.iter_mut();
|
||||
|
||||
for colour in iterator {
|
||||
let Some(slot) = slots.next() else { break };
|
||||
encode(colour.into(), slot);
|
||||
}
|
||||
for slot in slots {
|
||||
encode(RGB8::default(), slot);
|
||||
}
|
||||
|
||||
self.channel.transmit(&self.pulses).await
|
||||
}
|
||||
}
|
||||
|
||||
fn encode(colour: RGB8, slot: &mut [PulseCode; 24]) {
|
||||
// WS2812B latches GRB, most significant bit first
|
||||
let word = u32::from(colour.g) << 16 | u32::from(colour.r) << 8 | u32::from(colour.b);
|
||||
for (bit, code) in slot.iter_mut().enumerate() {
|
||||
*code = if word & (1 << (23 - bit)) != 0 {
|
||||
PulseCode::new(Level::High, T1H, Level::Low, T1L)
|
||||
} else {
|
||||
PulseCode::new(Level::High, T0H, Level::Low, T0L)
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user