From 9793bc62aff7bea0778e422baf8667e15e6e4484 Mon Sep 17 00:00:00 2001 From: Matt Spencer Date: Sat, 17 Oct 2026 18:22:09 +0100 Subject: [PATCH] feat(encoder): trigger on B and sample A Waiting on both phases via select drops the pending future each time the other fires, so B's edges were being lost and a later sample of B always read it back at rest. Triggering on B's falling edge and sampling A there is stable on this encoder. Also moves the encoder to D10/D9/D8 next to the power pads, drops the strip to a single LED for bring-up, and makes saturation an adjustable axis so the light defaults to white. --- Cargo.toml | 19 ++++++---- src/bin/pin_diag.rs | 89 +++++++++++++++++++++++++++++++++++++++++++++ src/config.rs | 5 ++- src/encoder.rs | 61 +++++++------------------------ src/light.rs | 32 +++++++++++----- src/main.rs | 83 ++++++++++++++++++++++++++---------------- 6 files changed, 192 insertions(+), 97 deletions(-) create mode 100644 src/bin/pin_diag.rs diff --git a/Cargo.toml b/Cargo.toml index 9f87174..cef0b24 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,17 +4,20 @@ version = "0.1.0" edition = "2024" [features] -default = ["esp32c6"] +default = ["esp32c6", "zigbee"] +## Join a Zigbee network. Disable to bring up the local hardware on its own: +## the stack reboots the device when it cannot find its coordinator. +zigbee = ["dep:esp-radio", "dep:zigbee", "dep:zigbee-cluster-library", "dep:zigbee-mac", "dep:zigbee-types"] esp32c6 = [ "esp-alloc/esp32c6", "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", "esp-println/esp32c6", - "esp-radio/esp32c6", + "esp-radio?/esp32c6", "esp-rtos/esp32c6", "esp-storage/esp32c6", - "zigbee-mac/esp32c6", + "zigbee-mac?/esp32c6", ] [dependencies] @@ -23,7 +26,7 @@ esp-backtrace = { version = "0.20", features = ["panic-handler", "println"] } esp-bootloader-esp-idf = "0.6" esp-hal = { version = "1.2", features = ["log-04", "unstable"] } esp-println = { version = "0.18", features = ["log-04"] } -esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"] } +esp-radio = { version = "1.0.0-beta.1", features = ["ieee802154", "unstable"], optional = true } esp-rtos = { version = "0.4", features = ["embassy", "log-04"] } esp-storage = { version = "0.10", features = ["embedded-storage"] } @@ -42,10 +45,10 @@ esp-hal-smartled = "0.18" # vendored upstream: the lighting cluster is not implemented there yet, so the # path dependency lets us add it in-tree and upstream it later -zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"] } -zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library" } -zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac" } -zigbee-types = { path = "vendor/zigbee-rs/zigbee-types" } +zigbee = { path = "vendor/zigbee-rs/zigbee", features = ["storage"], optional = true } +zigbee-cluster-library = { path = "vendor/zigbee-rs/zigbee-cluster-library", optional = true } +zigbee-mac = { path = "vendor/zigbee-rs/zigbee-mac", optional = true } +zigbee-types = { path = "vendor/zigbee-rs/zigbee-types", optional = true } [profile.release] debug = true diff --git a/src/bin/pin_diag.rs b/src/bin/pin_diag.rs new file mode 100644 index 0000000..cb2bf75 --- /dev/null +++ b/src/bin/pin_diag.rs @@ -0,0 +1,89 @@ +//! Pin-level diagnostic: polls every XIAO pad, alternating pull-up and +//! pull-down, and logs whichever pads change. +//! +//! Deliberately avoids interrupts, so a wiring fault (nothing ever changes) is +//! distinguishable from an interrupt fault (levels move but `encoder_task` +//! stays silent). +//! +//! Scanning every pad catches wires landing somewhere unexpected, and +//! alternating the pull settles whether the encoder's common pin is tied to +//! GND (active low, needs pull-up) or to + (active high, needs pull-down). +//! +//! Run with: +//! cargo run --release --no-default-features --features esp32c6 --bin pin_diag + +#![no_std] +#![no_main] + +use embassy_time::Duration; +use embassy_time::Timer; +use esp_alloc as _; +use esp_backtrace as _; +use esp_hal::gpio::Input; +use esp_hal::gpio::InputConfig; +use esp_hal::gpio::Pull; +use esp_hal::timer::timg::TimerGroup; + +esp_bootloader_esp_idf::esp_app_desc!(); + +/// How long to watch in each pull configuration. +const PHASE_SECS: u32 = 8; + +#[esp_rtos::main] +async fn main(_spawner: embassy_executor::Spawner) -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + + let up = InputConfig::default().with_pull(Pull::Up); + + // every pad broken out on the XIAO ESP32C6, in silkscreen order + let mut pads = [ + ("D0/GPIO0", Input::new(peripherals.GPIO0, up)), + ("D1/GPIO1", Input::new(peripherals.GPIO1, up)), + ("D2/GPIO2", Input::new(peripherals.GPIO2, up)), + ("D3/GPIO21", Input::new(peripherals.GPIO21, up)), + ("D4/GPIO22", Input::new(peripherals.GPIO22, up)), + ("D5/GPIO23", Input::new(peripherals.GPIO23, up)), + ("D6/GPIO16", Input::new(peripherals.GPIO16, up)), + ("D7/GPIO17", Input::new(peripherals.GPIO17, up)), + ("D8/GPIO19", Input::new(peripherals.GPIO19, up)), + ("D9/GPIO20", Input::new(peripherals.GPIO20, up)), + ("D10/GPIO18", Input::new(peripherals.GPIO18, up)), + ]; + + log::info!("pin_diag: scanning every pad, alternating pull-up and pull-down"); + log::info!("keep turning the knob and pressing it through both phases"); + + let mut previous = [false; 11]; + + loop { + for pull in [Pull::Up, Pull::Down] { + let config = InputConfig::default().with_pull(pull); + for (_, pin) in pads.iter_mut() { + pin.apply_config(&config); + } + // let the pull charge the pin before sampling the baseline + Timer::after(Duration::from_millis(10)).await; + + log::info!("--- pull {pull:?} for {PHASE_SECS}s ---"); + for (index, (name, pin)) in pads.iter().enumerate() { + previous[index] = pin.is_high(); + log::info!(" baseline {name} = {}", previous[index] as u8); + } + + for _ in 0..(PHASE_SECS * 500) { + Timer::after(Duration::from_millis(2)).await; + for (index, (name, pin)) in pads.iter().enumerate() { + let level = pin.is_high(); + if level != previous[index] { + log::info!(" {name} -> {}", level as u8); + previous[index] = level; + } + } + } + } + } +} diff --git a/src/config.rs b/src/config.rs index 630e48e..938384d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,7 +3,10 @@ //! Everything that changes when the hardware changes lives here. /// Number of WS2812B pixels on the strip. -pub const LED_COUNT: usize = 60; +/// +/// Held at 1 during bring-up to keep the current draw within what the board +/// can supply; a full strip needs its own 5V supply. +pub const LED_COUNT: usize = 1; /// Ceiling on the duty cycle applied to every channel, as a fraction of 255. /// diff --git a/src/encoder.rs b/src/encoder.rs index 813c483..47a44c2 100644 --- a/src/encoder.rs +++ b/src/encoder.rs @@ -1,12 +1,11 @@ //! Interrupt-driven rotary encoder with a push button. //! -//! Both tasks park on GPIO edge interrupts; nothing here polls. Quadrature is -//! decoded from the transition between the previous and current A/B pair, so a -//! bounce that returns to the previous state cancels itself out instead of -//! registering a step. +//! Both tasks park on GPIO edge interrupts; nothing here polls. +//! +//! Direction comes from sampling A on B's falling edge: one detent produces +//! exactly one such edge, and A's level there is opposite for the two +//! directions. -use embassy_futures::select::Either; -use embassy_futures::select::select; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use embassy_sync::channel::Channel; use embassy_time::Duration; @@ -29,47 +28,19 @@ pub enum EncoderEvent { /// drops the oldest step, which is preferable to blocking the interrupt task. pub static EVENTS: Channel = Channel::new(); -/// Valid quadrature transitions, indexed by `(previous << 2) | current` where -/// each pair is `(a << 1) | b`. Zero marks either no movement or an illegal -/// jump of two states, which means a transition was missed. -#[rustfmt::skip] -const TRANSITIONS: [i8; 16] = [ - 0, -1, 1, 0, - 1, 0, 0, -1, - -1, 0, 0, 1, - 0, 1, -1, 0, -]; - #[embassy_executor::task] -pub async fn encoder_task(mut a: Input<'static>, mut b: Input<'static>) { - let mut previous = state(&a, &b); - // a full detent is four quadrature transitions; only whole detents are - // reported so a resting-point jitter never moves the light - let mut substeps: i8 = 0; - +pub async fn encoder_task(a: Input<'static>, mut b: Input<'static>) { loop { - match select(a.wait_for_any_edge(), b.wait_for_any_edge()).await { - Either::First(()) | Either::Second(()) => {} - } + b.wait_for_falling_edge().await; - let current = state(&a, &b); - if current == previous { - continue; - } + // A must be read here, before the rest of the detent moves it + let delta = if a.is_high() { -1 } else { 1 }; + log::info!("edge on B -> A={} rotate {delta:+}", a.is_high() as u8); + let _ = EVENTS.try_send(EncoderEvent::Rotate(delta)); - let delta = TRANSITIONS[(previous << 2) | current]; - previous = current; - if delta == 0 { - continue; - } - - substeps += delta; - if substeps.abs() >= 4 { - let detents = substeps / 4; - substeps -= detents * 4; - // full is fine: a dropped step during a spin is invisible - let _ = EVENTS.try_send(EncoderEvent::Rotate(detents)); - } + // the rest of the detent returns B to rest; ignoring it stops one + // detent counting twice + b.wait_for_rising_edge().await; } } @@ -101,7 +72,3 @@ pub async fn button_task(mut button: Input<'static>) { Timer::after(Duration::from_millis(DEBOUNCE_MS)).await; } } - -fn state(a: &Input<'static>, b: &Input<'static>) -> usize { - usize::from(a.is_high()) << 1 | usize::from(b.is_high()) -} diff --git a/src/light.rs b/src/light.rs index 0a9980f..2fdc4a6 100644 --- a/src/light.rs +++ b/src/light.rs @@ -21,17 +21,20 @@ use crate::config::LED_COUNT; use crate::config::MAX_DUTY; use crate::strip::Strip; -/// What a turn of the encoder adjusts. +/// What a turn of the encoder adjusts. A long press moves to the next one. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Mode { Brightness, Hue, + Saturation, } static ON: AtomicBool = AtomicBool::new(false); static BRIGHTNESS: AtomicU8 = AtomicU8::new(128); static HUE: AtomicU8 = AtomicU8::new(0); -static HUE_MODE: AtomicBool = AtomicBool::new(false); +/// Zero is white, whatever the hue; a lamp should not power on coloured. +static SATURATION: AtomicU8 = AtomicU8::new(0); +static MODE: AtomicU8 = AtomicU8::new(0); static DIRTY: Signal = Signal::new(); pub fn is_on() -> bool { @@ -73,18 +76,29 @@ pub fn adjust_hue(delta: i16) { } pub fn mode() -> Mode { - if HUE_MODE.load(Ordering::Relaxed) { - Mode::Hue - } else { - Mode::Brightness + match MODE.load(Ordering::Relaxed) { + 1 => Mode::Hue, + 2 => Mode::Saturation, + _ => Mode::Brightness, } } -pub fn toggle_mode() -> Mode { - HUE_MODE.fetch_xor(true, Ordering::Relaxed); +pub fn next_mode() -> Mode { + MODE.store((MODE.load(Ordering::Relaxed) + 1) % 3, Ordering::Relaxed); mode() } +pub fn saturation() -> u8 { + SATURATION.load(Ordering::Relaxed) +} + +/// Clamps, so the ends of the travel are pure white and fully saturated. +pub fn adjust_saturation(delta: i16) { + let level = (i16::from(saturation()) + delta).clamp(0, 255) as u8; + SATURATION.store(level, Ordering::Relaxed); + DIRTY.signal(()); +} + #[embassy_executor::task] pub async fn render_task(mut strip: Strip<'static>) { let mut frame = [RGB8::default(); LED_COUNT]; @@ -92,7 +106,7 @@ pub async fn render_task(mut strip: Strip<'static>) { loop { frame.fill(hsv2rgb(Hsv { hue: hue(), - sat: 255, + sat: saturation(), val: 255, })); diff --git a/src/main.rs b/src/main.rs index 536c334..94373d2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,9 +6,9 @@ mod encoder; mod light; mod status; mod strip; +#[cfg(feature = "zigbee")] mod zigbee_stack; -use embassy_embedded_hal::adapter::BlockingAsync; use esp_alloc as _; use esp_backtrace as _; use esp_hal::gpio::Input; @@ -21,28 +21,24 @@ use esp_hal::rmt::Rmt; use esp_hal::time::Rate; use esp_hal::timer::timg::TimerGroup; use esp_hal_smartled::WS2812B_TIMING; -use esp_radio::ieee802154::Ieee802154; -use esp_storage::FlashStorage; -use static_cell::StaticCell; -use zigbee_mac::esp::EspMlme; use crate::config::STEPS_PER_BRIGHTNESS_UNIT; use crate::encoder::EVENTS; use crate::encoder::EncoderEvent; use crate::light::Mode; use crate::strip::Strip; -use crate::zigbee_stack::Stack; esp_bootloader_esp_idf::esp_app_desc!(); -static STACK: StaticCell = StaticCell::new(); - /// Brightness units per detent. const BRIGHTNESS_STEP: i16 = 8; /// Hue per detent, in 1/256ths of the colour circle (~5.6 degrees). const HUE_STEP: i16 = 4; +/// Saturation units per detent; 0 is white, 255 fully coloured. +const SATURATION_STEP: i16 = 16; + #[esp_rtos::main] async fn main(spawner: embassy_executor::Spawner) -> ! { esp_println::logger::init_logger_from_env(); @@ -65,38 +61,54 @@ async fn main(spawner: embassy_executor::Spawner) -> ! { .expect("configure WS2812B adapter"); // the encoder's common pin is grounded, so both phases and the switch idle - // high and are driven low; the pull-ups make an open contact well defined + // high and are driven low; the pull-ups make an open contact well defined. + // D10/D9/D8 sit directly under the 3V3 and GND pads, keeping the module's + // five wires on one side of the board. let pull_up = InputConfig::default().with_pull(Pull::Up); - let encoder_a = Input::new(peripherals.GPIO21, pull_up); - let encoder_b = Input::new(peripherals.GPIO22, pull_up); - let button = Input::new(peripherals.GPIO23, pull_up); + let encoder_a = Input::new(peripherals.GPIO18, pull_up); // D10, CLK + let encoder_b = Input::new(peripherals.GPIO20, pull_up); // D9, DT + let button = Input::new(peripherals.GPIO19, pull_up); // D8, SW // on-board user LED, starting dark let led = Output::new(peripherals.GPIO15, Level::High, OutputConfig::default()); - // the stack owns persistence: the information bases are restored here and - // written back whenever the stack changes them - let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH)); - let storage = zigbee::storage::init_with_flash(flash, zigbee_stack::FLASH_RANGE).await; - - let ieee802154 = Ieee802154::new(peripherals.IEEE802154); - let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default()); - log::info!("device IEEE address: {:#018x}", mac.ieee_address()); - - let stack: &'static Stack = STACK.init(Stack::new( - mac, - zigbee_stack::config(), - zigbee_stack::handler(), - storage, - )); - spawner.spawn(status::heartbeat_task(led).expect("spawn heartbeat_task")); spawner.spawn(light::render_task(strip).expect("spawn render_task")); spawner.spawn(encoder::encoder_task(encoder_a, encoder_b).expect("spawn encoder_task")); spawner.spawn(encoder::button_task(button).expect("spawn button_task")); - spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task")); - spawner.spawn(zigbee_stack::on_off_task().expect("spawn on_off_task")); - spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task")); + + #[cfg(feature = "zigbee")] + { + use embassy_embedded_hal::adapter::BlockingAsync; + use esp_radio::ieee802154::Ieee802154; + use esp_storage::FlashStorage; + use static_cell::StaticCell; + use zigbee_mac::esp::EspMlme; + + use crate::zigbee_stack::Stack; + + static STACK: StaticCell = StaticCell::new(); + + // the stack owns persistence: the information bases are restored here + // and written back whenever the stack changes them + let flash = BlockingAsync::new(FlashStorage::new(peripherals.FLASH)); + let storage = zigbee::storage::init_with_flash(flash, zigbee_stack::FLASH_RANGE).await; + + let ieee802154 = Ieee802154::new(peripherals.IEEE802154); + let mac = EspMlme::new(ieee802154, esp_radio::ieee802154::Config::default()); + log::info!("device IEEE address: {:#018x}", mac.ieee_address()); + + let stack: &'static Stack = STACK.init(Stack::new( + mac, + zigbee_stack::config(), + zigbee_stack::handler(), + storage, + )); + + spawner.spawn(zigbee_stack::stack_task(stack).expect("spawn stack_task")); + spawner.spawn(zigbee_stack::on_off_task().expect("spawn on_off_task")); + spawner.spawn(zigbee_stack::identify_task().expect("spawn identify_task")); + } loop { match EVENTS.receive().await { @@ -105,14 +117,21 @@ async fn main(spawner: embassy_executor::Spawner) -> ! { match light::mode() { Mode::Brightness => light::adjust_brightness(steps * BRIGHTNESS_STEP), Mode::Hue => light::adjust_hue(steps * HUE_STEP), + Mode::Saturation => light::adjust_saturation(steps * SATURATION_STEP), } + log::info!( + "rotate {detents:+} -> brightness {} hue {} saturation {}", + light::brightness(), + light::hue(), + light::saturation() + ); } EncoderEvent::Click => { let on = light::toggle(); log::info!("light {}", if on { "on" } else { "off" }); } EncoderEvent::LongPress => { - let mode = light::toggle_mode(); + let mode = light::next_mode(); log::info!("encoder now adjusts {mode:?}"); } }