From 0fc3046028b405695fdc509aa6bf2ebc893048a9 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 30 Sep 2023 15:13:04 +0800 Subject: [PATCH 01/16] Implement basic keyboard firmware Lights up capslock LED and when in USB suspend blinks it every 500ms. Signed-off-by: Daniel Schaefer --- .github/workflows/firmware.yml | 15 ++ .github/workflows/software.yml | 2 + .github/workflows/traditional-cargo.yml | 2 + Cargo.lock | 20 ++ Cargo.toml | 7 + fl16-inputmodules/Cargo.toml | 1 + fl16-inputmodules/src/keyboard_hal.rs | 97 ++++++++ fl16-inputmodules/src/lib.rs | 9 +- keyboard/Cargo.toml | 39 ++++ keyboard/Makefile.toml | 12 + keyboard/README.md | 4 + keyboard/src/main.rs | 281 ++++++++++++++++++++++++ 12 files changed, 488 insertions(+), 1 deletion(-) create mode 100644 fl16-inputmodules/src/keyboard_hal.rs create mode 100644 keyboard/Cargo.toml create mode 100644 keyboard/Makefile.toml create mode 100644 keyboard/README.md create mode 100644 keyboard/src/main.rs diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index cba0a1a5..20663fd8 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -38,12 +38,14 @@ jobs: - run: cargo make --cwd ledmatrix - run: cargo make --cwd qtpy # Release version + - run: cargo make --cwd keyboard - run: cargo make --cwd ledmatrix build-release - run: cargo make --cwd ledmatrix build-release-10k - run: cargo make --cwd ledmatrix build-release-evt - run: cargo make --cwd b1display build-release - run: cargo make --cwd c1minimal build-release - run: cargo make --cwd qtpy build-release + - run: cargo make --cwd keyboard build-release - name: Convert to UF2 format run: | @@ -52,6 +54,7 @@ jobs: cargo make --cwd b1display uf2 cargo make --cwd c1minimal uf2 cargo make --cwd qtpy uf2 + cargo make --cwd keyboard uf2 cargo make --cwd ledmatrix build-release-10k-uf2 cargo make --cwd ledmatrix build-release-evt-uf2 cargo make --cwd ledmatrix uf2 @@ -63,6 +66,7 @@ jobs: cargo make --cwd b1display bin cargo make --cwd qtpy bin cargo make --cwd c1minimal bin + cargo make --cwd keyboard bin cargo make --cwd ledmatrix bin - name: Upload ledmatrix files @@ -94,6 +98,14 @@ jobs: target/thumbv6m-none-eabi/release/c1minimal.bin target/thumbv6m-none-eabi/release/c1minimal.uf2 + - name: Upload keyboard files + uses: actions/upload-artifact@v3 + with: + name: c1minimal_fw_${{github.sha}} + path: | + target/thumbv6m-none-eabi/release/keyboard.bin + target/thumbv6m-none-eabi/release/keyboard.uf2 + linting: name: Linting runs-on: ubuntu-latest @@ -111,6 +123,7 @@ jobs: cargo make clippy --cwd b1display cargo make clippy --cwd qtpy cargo make clippy --cwd c1minimal + cargo make clippy --cwd keyboard cargo make clippy --cwd ledmatrix # fl16-inputmodules/src/serialnum.rs @@ -123,6 +136,7 @@ jobs: cargo pkgid -p b1display | cut -d "#" -f2 >> versions.tmp cargo pkgid -p qtpy | cut -d "#" -f2 >> versions.tmp cargo pkgid -p c1minimal | cut -d "#" -f2 >> versions.tmp + cargo pkgid -p keyboard | cut -d "#" -f2 >> versions.tmp cargo pkgid -p ledmatrix | cut -d "#" -f2 >> versions.tmp uniq -c versions.tmp | [ $(wc -l) -eq 1 ] @@ -138,6 +152,7 @@ jobs: - run: | cargo fmt -p b1display -- --check cargo fmt -p c1minimal -- --check + cargo fmt -p keyboard -- --check cargo fmt -p ledmatrix -- --check cargo fmt -p qtpy -- --check cargo fmt -p fl16-inputmodules -- --check diff --git a/.github/workflows/software.yml b/.github/workflows/software.yml index 105dde7b..238339a0 100644 --- a/.github/workflows/software.yml +++ b/.github/workflows/software.yml @@ -8,6 +8,7 @@ on: paths-ignore: - 'b1display/**' - 'c1minimal/**' + - 'keyboard/**' - 'fl16-inputmodules/**' - 'ledmatrix/**' pull_request: @@ -16,6 +17,7 @@ on: paths-ignore: - 'b1display/**' - 'c1minimal/**' + - 'keyboard/**' - 'fl16-inputmodules/**' - 'ledmatrix/**' diff --git a/.github/workflows/traditional-cargo.yml b/.github/workflows/traditional-cargo.yml index 231ead0d..ad5bab56 100644 --- a/.github/workflows/traditional-cargo.yml +++ b/.github/workflows/traditional-cargo.yml @@ -36,6 +36,7 @@ jobs: - run: cargo build -p ledmatrix --features evt - run: cargo build -p b1display - run: cargo build -p c1minimal + - run: cargo build -p keyboard linux-software: name: Build Linux @@ -92,6 +93,7 @@ jobs: run: | cargo clippy -p b1display -- --deny=warnings cargo clippy -p c1minimal -- --deny=warnings + cargo clippy -p keyboard -- --deny=warnings cargo clippy -p ledmatrix -- --deny=warnings cargo clippy -p fl16-inputmodules -- --deny=warnings diff --git a/Cargo.lock b/Cargo.lock index 9a7bd7b6..47bc6244 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1175,6 +1175,26 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keyboard" +version = "0.1.7" +dependencies = [ + "cortex-m", + "cortex-m-rt", + "defmt", + "defmt-rtt", + "embedded-hal", + "fl16-inputmodules", + "fugit", + "heapless", + "rp2040-boot2", + "rp2040-hal", + "rp2040-panic-usb-boot", + "usb-device", + "usbd-hid", + "usbd-serial", +] + [[package]] name = "lazy_static" version = "1.5.0" diff --git a/Cargo.toml b/Cargo.toml index 5182cad9..1bba756b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ resolver = "2" members = [ "b1display", "c1minimal", + "keyboard", "ledmatrix", "fl16-inputmodules", "inputmodule-control", @@ -57,6 +58,12 @@ incremental = true # To allow single-stepping through code use 0. Will cause timing issues, though opt-level = 3 +[profile.dev.package.keyboard] +codegen-units = 1 +incremental = true +# To allow single-stepping through code use 0. Will cause timing issues, though +opt-level = 3 + [profile.dev.package.b1display] codegen-units = 1 incremental = true diff --git a/fl16-inputmodules/Cargo.toml b/fl16-inputmodules/Cargo.toml index dbd87997..90a14069 100644 --- a/fl16-inputmodules/Cargo.toml +++ b/fl16-inputmodules/Cargo.toml @@ -47,3 +47,4 @@ ledmatrix = ["is31fl3741"] b1display = ["st7306", "embedded-graphics", "tinybmp"] c1minimal = ["smart-leds", "ws2812-pio"] qtpy = ["c1minimal"] +keyboard = [] diff --git a/fl16-inputmodules/src/keyboard_hal.rs b/fl16-inputmodules/src/keyboard_hal.rs new file mode 100644 index 00000000..beeb3ec1 --- /dev/null +++ b/fl16-inputmodules/src/keyboard_hal.rs @@ -0,0 +1,97 @@ +// Taken from rp_pico hal and adjusted + +pub extern crate rp2040_hal as hal; + +extern crate cortex_m_rt; +pub use hal::entry; + +/// The linker will place this boot block at the start of our program image. We +/// need this to help the ROM bootloader get our code up and running. +#[link_section = ".boot2"] +#[no_mangle] +#[used] +pub static BOOT2_FIRMWARE: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080; + +pub use hal::pac; + +hal::bsp_pins!( + /// GPIO 0 is connected to the SLEEP# pin of the EC + Gpio0 { name: sleep }, + /// Mux selector A + Gpio1 { name: mux_a }, + /// Mux selector B + Gpio2 { name: mux_b }, + /// Mux selector C + Gpio3 { name: mux_c }, + /// Mux enable + Gpio4 { name: mux_enable }, + /// Pull low when firmware has started to turn off bootloader logic + Gpio5 { name: boot_done }, + /// Connected to KSI5 but unused, should use high-Z + Gpio6 { + name: ksi5_reserved + }, + /// Connected to KSI5 but unused, should use high-Z + Gpio7 { + name: ksi6_reserved + }, + /// Keyboard column drive + Gpio8 { name: kso0 }, + /// Keyboard column drive + Gpio9 { name: kso1 }, + /// Keyboard column drive + Gpio10 { name: kso2 }, + /// Keyboard column drive + Gpio11 { name: kso3 }, + /// Keyboard column drive + Gpio12 { name: kso4 }, + /// Keyboard column drive + Gpio13 { name: kso5 }, + /// Keyboard column drive + Gpio14 { name: kso6 }, + /// Keyboard column drive + Gpio15 { name: kso7 }, + /// Keyboard column drive + Gpio16 { name: kso13 }, + /// Keyboard column drive + Gpio17 { name: kso12 }, + /// Keyboard column drive + Gpio18 { name: kso11 }, + /// Keyboard column drive + Gpio19 { name: kso10 }, + /// Keyboard column drive + Gpio20 { name: kso9 }, + /// Keyboard column drive + Gpio21 { name: kso8 }, + /// Keyboard column drive + Gpio22 { name: kso15 }, + /// Keyboard column drive + Gpio23 { name: kso14 }, + /// Capslock LED + Gpio24 { name: caps_led }, + /// Single zone backlight (unused on RGB keyboard) + Gpio25 { name: backlight }, + /// GPIO 26 is connected to I2C SDA of the LED controller + Gpio26 { + name: gpio26, + aliases: { + /// I2C Function alias for pin [crate::Pins::gpio26]. + FunctionI2C: Gp26I2C1Sda + } + }, + /// GPIO 27 is connected to I2C SCL of the LED controller + Gpio27 { + name: gpio27, + aliases: { + /// I2C Function alias for pin [crate::Pins::gpio27]. + FunctionI2C: Gp27I2C1Scl + } + }, + /// Analog IN from mux + Gpio28 { name: analog_in }, + /// GPIO 29 is connected to the SDB pin of the LED controller + Gpio29 { name: sdb }, +); + +// External crystal frequency, same as Raspberry Pi Pico +pub const XOSC_CRYSTAL_FREQ: u32 = 12_000_000; diff --git a/fl16-inputmodules/src/lib.rs b/fl16-inputmodules/src/lib.rs index df107681..631cca99 100644 --- a/fl16-inputmodules/src/lib.rs +++ b/fl16-inputmodules/src/lib.rs @@ -5,8 +5,13 @@ all(feature = "ledmatrix", feature = "b1display"), all(feature = "ledmatrix", feature = "c1minimal"), all(feature = "b1display", feature = "c1minimal"), + all(feature = "ledmatrix", feature = "keyboard"), + all(feature = "b1display", feature = "keyboard"), + all(feature = "c1minimal", feature = "keyboard"), ))] -compile_error!("Features \"ledmatrix\", \"b1display\", and \"c1minimal\" are mutually exclusive"); +compile_error!( + "Features \"ledmatrix\", \"b1display\", \"c1minimal\", and \"keyboard\" are mutually exclusive" +); #[cfg(feature = "ledmatrix")] pub mod fl16; @@ -34,6 +39,8 @@ pub mod minimal_hal; #[cfg(feature = "qtpy")] pub mod qtpy_hal; +#[cfg(feature = "keyboard")] +pub mod keyboard_hal; pub mod control; pub mod serialnum; diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml new file mode 100644 index 00000000..f16b1b94 --- /dev/null +++ b/keyboard/Cargo.toml @@ -0,0 +1,39 @@ +[package] +edition = "2021" +name = "keyboard" +version = "0.1.7" + +[features] +default = ["macropad"] +cli = [] +ansi = [] +iso = [] +jis = [] +numpad = [] +macropad = [] + +[dependencies] +cortex-m.workspace = true +cortex-m-rt.workspace = true +embedded-hal.workspace = true + +defmt.workspace = true +defmt-rtt.workspace = true + +#panic-probe.workspace = true +rp2040-panic-usb-boot.workspace = true + +# Not using an external BSP, we've got the Framework Laptop 16 BSPs locally in this crate +rp2040-hal.workspace = true +rp2040-boot2.workspace = true + +# USB Serial +usb-device.workspace = true +heapless.workspace = true +usbd-serial.workspace = true +usbd-hid.workspace = true +fugit.workspace = true + +[dependencies.fl16-inputmodules] +path = "../fl16-inputmodules" +features = ["keyboard"] diff --git a/keyboard/Makefile.toml b/keyboard/Makefile.toml new file mode 100644 index 00000000..ea7d5ecc --- /dev/null +++ b/keyboard/Makefile.toml @@ -0,0 +1,12 @@ +extend = "../Makefile.toml" + +[tasks.uf2] +command = "elf2uf2-rs" +args = ["../target/thumbv6m-none-eabi/release/b1display", "../target/thumbv6m-none-eabi/release/b1display.uf2"] +dependencies = ["build-release"] +install_crate = "elf2uf2-rs" + +[tasks.bin] +command = "llvm-objcopy" +args = ["-Obinary", "../target/thumbv6m-none-eabi/release/b1display", "../target/thumbv6m-none-eabi/release/b1display.bin"] +dependencies = ["build-release"] diff --git a/keyboard/README.md b/keyboard/README.md new file mode 100644 index 00000000..9beb06c0 --- /dev/null +++ b/keyboard/README.md @@ -0,0 +1,4 @@ +# Keyboard + +NOT THE OFFICIAL Keyboard firmware +Just experimental reference code for building keyboard firmare in Rust \ No newline at end of file diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs new file mode 100644 index 00000000..8d2e3546 --- /dev/null +++ b/keyboard/src/main.rs @@ -0,0 +1,281 @@ +//! NOT THE OFFICIAL Keyboard firmware +//! Just experimental reference code for building keyboard firmare in Rust +#![no_std] +#![no_main] +#![allow(clippy::needless_range_loop)] + +//use cortex_m::delay::Delay; +//use defmt::*; +use defmt_rtt as _; +use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin}; + +use rp2040_hal::Timer; +//#[cfg(debug_assertions)] +//use panic_probe as _; +use rp2040_panic_usb_boot as _; + +/// List maximum current as 500mA in the USB descriptor +const MAX_CURRENT: usize = 500; + +// Provide an alias for our BSP so we can switch targets quickly. +// Uncomment the BSP you included in Cargo.toml, the rest of the code does not need to change. +use bsp::entry; +use fl16_inputmodules::keyboard_hal as bsp; +//use rp_pico as bsp; +// use sparkfun_pro_micro_rp2040 as bsp; + +use bsp::hal::{ + clocks::{init_clocks_and_plls, Clock}, + pac, + sio::Sio, + usb, + watchdog::Watchdog, +}; + +// USB Device support +use usb_device::{class_prelude::*, prelude::*}; + +// USB Communications Class Device support +use usbd_serial::{SerialPort, USB_CLASS_CDC}; + +// Used to demonstrate writing formatted strings +use core::fmt::Write; +use heapless::String; + +use fl16_inputmodules::serialnum::device_release; + +#[entry] +fn main() -> ! { + let mut pac = pac::Peripherals::take().unwrap(); + let core = pac::CorePeripherals::take().unwrap(); + let mut watchdog = Watchdog::new(pac.WATCHDOG); + let sio = Sio::new(pac.SIO); + + let clocks = init_clocks_and_plls( + bsp::XOSC_CRYSTAL_FREQ, + pac.XOSC, + pac.CLOCKS, + pac.PLL_SYS, + pac.PLL_USB, + &mut pac.RESETS, + &mut watchdog, + ) + .ok() + .unwrap(); + + let rosc = rp2040_hal::rosc::RingOscillator::new(pac.ROSC); + let _rosc = rosc.initialize(); + + let mut _delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); + + let pins = bsp::Pins::new( + pac.IO_BANK0, + pac.PADS_BANK0, + sio.gpio_bank0, + &mut pac.RESETS, + ); + + // Set up the USB driver + let usb_bus = UsbBusAllocator::new(usb::UsbBus::new( + pac.USBCTRL_REGS, + pac.USBCTRL_DPRAM, + clocks.usb_clock, + true, + &mut pac.RESETS, + )); + + // Set up the USB Communications Class Device driver + let mut serial = SerialPort::new(&usb_bus); + + #[cfg(feature = "macropad")] + let pid = 0x013; + #[cfg(feature = "ansi")] + let pid = 0x012; + #[cfg(feature = "numpad")] + let pid = 0x014; + #[cfg(feature = "iso")] + let pid = 0x018; + #[cfg(feature = "jis")] + let pid = 0x019; + + #[cfg(feature = "macropad")] + let product = "Rust Macropad"; + #[cfg(feature = "ansi")] + let product = "Rust ANSI Keyboard"; + #[cfg(feature = "numpad")] + let product = "Rust Numpad"; + #[cfg(feature = "iso")] + let product = "Rust ISO Keyboard"; + #[cfg(feature = "jis")] + let product = "Rust JIS Keyboard"; + + let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x32ac, pid)) + .manufacturer("Framework Computer Inc") + .product(product) + //.supports_remote_wakeup(true) + .device_class(USB_CLASS_CDC) + .max_power(MAX_CURRENT) + .serial_number("testing") + .device_release(device_release()) + .build(); + + // Disable bootloader circuitry + let mut boot_done = pins.boot_done.into_push_pull_output(); + boot_done.set_high().unwrap(); + + // pins.gp26 // SDA + // pins.gp27 // SCL + // pins.analog_in + + let mut caps_led = pins.caps_led.into_push_pull_output(); + let mut _backlight = pins.backlight.into_push_pull_output(); + + // Pull low to enable mux + let mut mux_enable = pins.mux_enable.into_push_pull_output(); + mux_enable.set_low().unwrap(); + let mut _mux_a = pins.mux_a.into_push_pull_output(); + let mut _mux_b = pins.mux_b.into_push_pull_output(); + let mut _mux_c = pins.mux_c.into_push_pull_output(); + + // KS0 - KSO7 for Keyboard and Numpad + let mut _kso0 = pins.kso0.into_push_pull_output(); + let mut _kso1 = pins.kso1.into_push_pull_output(); + let mut _kso2 = pins.kso2.into_push_pull_output(); + let mut _kso3 = pins.kso3.into_push_pull_output(); + let mut _kso4 = pins.kso4.into_push_pull_output(); + let mut _kso5 = pins.kso5.into_push_pull_output(); + let mut _kso6 = pins.kso6.into_push_pull_output(); + let mut _kso7 = pins.kso7.into_push_pull_output(); + // KS08 - KS015 for Keyboard only + let mut _kso8 = pins.kso8.into_push_pull_output(); + let mut _kso9 = pins.kso9.into_push_pull_output(); + let mut _kso10 = pins.kso10.into_push_pull_output(); + let mut _kso11 = pins.kso11.into_push_pull_output(); + let mut _kso12 = pins.kso12.into_push_pull_output(); + let mut _kso13 = pins.kso13.into_push_pull_output(); + let mut _kso14 = pins.kso14.into_push_pull_output(); + let mut _kso15 = pins.kso15.into_push_pull_output(); + // Set unused pins to input to avoid interfering. They're hooked up to rows 5 and 6 + let _ = pins.ksi5_reserved.into_floating_input(); + let _ = pins.ksi6_reserved.into_floating_input(); + + let sleep = pins.sleep.into_floating_input(); + + // Enable LED controller + // SDB + let mut led_enable = pins.sdb.into_push_pull_output(); + led_enable.set_low().unwrap(); + // led_enable.set_high().unwrap(); + // + // let i2c = bsp::hal::I2C::i2c1( + // pac.I2C1, + // pins.gpio26.into_mode::(), + // pins.gpio27.into_mode::(), + // 1000.kHz(), + // &mut pac.RESETS, + // &clocks.peripheral_clock, + // ); + // + // let mut matrix = LedMatrix::new(i2c, DVT2_CALC_PIXEL); + // matrix + // .setup(&mut delay) + // .expect("failed to setup RGB controller"); + // + // matrix + // .set_scaling(MAX_BRIGHTNESS) + // .expect("failed to set scaling"); + // + // fill_grid_pixels(&state, &mut matrix); + + let timer = Timer::new(pac.TIMER, &mut pac.RESETS); + let mut animation_timer = timer.get_counter().ticks(); + caps_led.set_high().unwrap(); + + let mut usb_initialized; + let mut usb_suspended = false; + loop { + let _ = sleep.is_high(); + + // Turn back on when not suspended anymore + if !usb_suspended { + if caps_led.is_set_low().unwrap() { + caps_led.set_high().unwrap(); + } + } + + // Blink when in USB Suspend + // 500_000us = 500ms = 0.5s + if usb_suspended && timer.get_counter().ticks() > animation_timer + 500_000 { + if caps_led.is_set_high().unwrap() { + caps_led.set_low().unwrap(); + } else { + caps_led.set_high().unwrap(); + } + animation_timer = timer.get_counter().ticks(); + } + + // Check for new data + if usb_dev.poll(&mut [&mut serial]) { + match usb_dev.state() { + // Default: Device has just been created or reset + // Addressed: Device has received an address for the host + UsbDeviceState::Default | UsbDeviceState::Addressed => { + usb_initialized = false; + usb_suspended = false; + // Must not display anything or windows cannot enumerate properly + } + // Configured and is fully operational + UsbDeviceState::Configured => { + usb_initialized = true; + usb_suspended = false; + } + // Never occurs here. Only if poll() returns false + UsbDeviceState::Suspend => { + panic!("Never occurs here. Only if poll() returns false") + } + } + + // Ignore unused + let _ = usb_initialized; + let _ = usb_suspended; + + let mut buf = [0u8; 64]; + match serial.read(&mut buf) { + Err(_e) => { + // Do nothing + } + Ok(0) => { + // Do nothing + } + Ok(count) => { + let mut text: String<64> = String::new(); + write!( + &mut text, + "Hello World: Usb Suspended: {}. C: {}\r\n", + usb_suspended, count + ) + .unwrap(); + let _ = serial.write(text.as_bytes()); + } + } + } else { + match usb_dev.state() { + // No new data + UsbDeviceState::Default | UsbDeviceState::Addressed => { + usb_initialized = false; + usb_suspended = false; + } + UsbDeviceState::Configured => { + usb_initialized = true; + usb_suspended = false; + } + UsbDeviceState::Suspend => { + usb_suspended = true; + } + } + // Ignore unused + let _ = usb_initialized; + let _ = usb_suspended; + } + } +} From 6aaf73ee5410cbbd9a385355eb1035a5aa54e67f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 30 Sep 2023 19:11:05 +0800 Subject: [PATCH 02/16] keyboard: Implement reading of arrow keys Prints to USB serial Signed-off-by: Daniel Schaefer --- Cargo.lock | 4 +- keyboard/src/main.rs | 263 ++++++++++++++++++++++++++++++++++++++----- 2 files changed, 233 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 47bc6244..b9e3ec47 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2031,10 +2031,8 @@ dependencies = [ [[package]] name = "rp2040-hal-macros" version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86479063e497efe1ae81995ef9071f54fd1c7427e04d6c5b84cde545ff672a5e" +source = "git+https://github.com/FrameworkComputer/rp-hal?branch=adc-pull-down-up#ef80ceba220f0dc0f50cabeee4ed8fc3c597cf43" dependencies = [ - "cortex-m-rt", "proc-macro2", "quote", "syn 1.0.109", diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 8d2e3546..306a8178 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -7,9 +7,24 @@ //use cortex_m::delay::Delay; //use defmt::*; use defmt_rtt as _; +use embedded_hal::adc::OneShot; use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin}; - -use rp2040_hal::Timer; +use rp2040_hal::gpio::bank0::Gpio28; +use rp2040_hal::gpio::{Input, PullUp}; + +use core::fmt::Display; +use core::fmt::{self, Formatter}; + +use rp2040_hal::{ + gpio::{ + bank0::{ + Gpio1, Gpio10, Gpio11, Gpio12, Gpio13, Gpio14, Gpio15, Gpio16, Gpio17, Gpio18, Gpio19, + Gpio2, Gpio20, Gpio21, Gpio22, Gpio23, Gpio3, Gpio8, Gpio9, + }, + Output, Pin, PinState, PushPull, + }, + Adc, Timer, +}; //#[cfg(debug_assertions)] //use panic_probe as _; use rp2040_panic_usb_boot as _; @@ -44,6 +59,151 @@ use heapless::String; use fl16_inputmodules::serialnum::device_release; +const MATRIX_COLS: usize = 16; +const MATRIX_ROWS: usize = 8; +const ADC_THRESHOLD: usize = 2900; + +struct Mux { + a: Pin>, + b: Pin>, + c: Pin>, + // TODO + // x: Pin>, +} +impl Mux { + pub fn select_row(&mut self, row: usize) { + let index = match row { + 0 => 2, + 1 => 0, + 2 => 1, + _ => row, + }; + self.a.set_state(PinState::from(index & 0x01 != 0)).unwrap(); + self.b.set_state(PinState::from(index & 0x02 != 0)).unwrap(); + self.c.set_state(PinState::from(index & 0x04 != 0)).unwrap(); + } +} + +#[derive(Debug, PartialEq, Eq, Clone, Default)] +pub struct Col(u8); +#[derive(Debug, PartialEq, Eq, Clone, Default)] +struct Matrix([Col; MATRIX_COLS]); + +impl Matrix { + pub fn set(&mut self, row: usize, col: usize, val: bool) { + let mask = 1 << row; + + self.0[col].0 = if val { + self.0[col].0 | mask + } else { + self.0[col].0 & !mask + }; + } +} + +impl Display for Col { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + for row in 0..MATRIX_ROWS { + let val = (self.0 & (1 << row)) >> row; + write!(f, "{:b}", val)? + } + Ok(()) + } +} + +type Kso = ( + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, + Pin>, +); + +struct Scanner { + kso: Kso, + mux: Mux, + adc: (Adc, Pin>), +} +impl Scanner { + fn drive_col(&mut self, col: usize, state: PinState) { + match col { + 0 => self.kso.0.set_state(state).unwrap(), + 1 => self.kso.1.set_state(state).unwrap(), + 2 => self.kso.2.set_state(state).unwrap(), + 3 => self.kso.3.set_state(state).unwrap(), + 4 => self.kso.4.set_state(state).unwrap(), + 5 => self.kso.5.set_state(state).unwrap(), + 6 => self.kso.6.set_state(state).unwrap(), + 7 => self.kso.7.set_state(state).unwrap(), + 8 => self.kso.8.set_state(state).unwrap(), + 9 => self.kso.9.set_state(state).unwrap(), + 10 => self.kso.10.set_state(state).unwrap(), + 11 => self.kso.11.set_state(state).unwrap(), + 12 => self.kso.12.set_state(state).unwrap(), + 13 => self.kso.13.set_state(state).unwrap(), + 14 => self.kso.14.set_state(state).unwrap(), + 15 => self.kso.15.set_state(state).unwrap(), + _ => unreachable!(), + } + } + fn read_voltage(&mut self) -> usize { + let _adc_read: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); + 33000 + } + pub fn measure_key(&mut self, row: usize, col: usize) -> (usize, usize) { + for col in 0..MATRIX_COLS { + self.drive_col(col, PinState::High); + } + self.drive_col(col, PinState::Low); + + self.mux.select_row(row); + cortex_m::asm::delay(2000); + let adc_read: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); + + self.drive_col(col, PinState::High); + + let voltage_10k = ((adc_read as usize) * 3300) / 4096; + (voltage_10k / 1_000, voltage_10k % 1_000) + } + pub fn scan(&mut self) -> Matrix { + let mut matrix = Matrix::default(); + + // Initialize all cols as high + for col in 0..MATRIX_COLS { + self.drive_col(col, PinState::High); + } + + for col in 0..MATRIX_COLS { + self.drive_col(col, PinState::Low); + + for row in 0..MATRIX_ROWS { + self.mux.select_row(row); + + if self.read_voltage() < ADC_THRESHOLD { + matrix.set(row, col, true); + } + } + + self.drive_col(col, PinState::High); + } + + matrix.set(3, 4, true); + matrix.set(0, 4, true); + matrix + } +} + #[entry] fn main() -> ! { let mut pac = pac::Peripherals::take().unwrap(); @@ -121,7 +281,7 @@ fn main() -> ! { // Disable bootloader circuitry let mut boot_done = pins.boot_done.into_push_pull_output(); - boot_done.set_high().unwrap(); + boot_done.set_low().unwrap(); // pins.gp26 // SDA // pins.gp27 // SCL @@ -133,28 +293,28 @@ fn main() -> ! { // Pull low to enable mux let mut mux_enable = pins.mux_enable.into_push_pull_output(); mux_enable.set_low().unwrap(); - let mut _mux_a = pins.mux_a.into_push_pull_output(); - let mut _mux_b = pins.mux_b.into_push_pull_output(); - let mut _mux_c = pins.mux_c.into_push_pull_output(); + let mux_a = pins.mux_a.into_push_pull_output(); + let mux_b = pins.mux_b.into_push_pull_output(); + let mux_c = pins.mux_c.into_push_pull_output(); // KS0 - KSO7 for Keyboard and Numpad - let mut _kso0 = pins.kso0.into_push_pull_output(); - let mut _kso1 = pins.kso1.into_push_pull_output(); - let mut _kso2 = pins.kso2.into_push_pull_output(); - let mut _kso3 = pins.kso3.into_push_pull_output(); - let mut _kso4 = pins.kso4.into_push_pull_output(); - let mut _kso5 = pins.kso5.into_push_pull_output(); - let mut _kso6 = pins.kso6.into_push_pull_output(); - let mut _kso7 = pins.kso7.into_push_pull_output(); + let kso0 = pins.kso0.into_push_pull_output(); + let kso1 = pins.kso1.into_push_pull_output(); + let kso2 = pins.kso2.into_push_pull_output(); + let kso3 = pins.kso3.into_push_pull_output(); + let kso4 = pins.kso4.into_push_pull_output(); + let kso5 = pins.kso5.into_push_pull_output(); + let kso6 = pins.kso6.into_push_pull_output(); + let kso7 = pins.kso7.into_push_pull_output(); // KS08 - KS015 for Keyboard only - let mut _kso8 = pins.kso8.into_push_pull_output(); - let mut _kso9 = pins.kso9.into_push_pull_output(); - let mut _kso10 = pins.kso10.into_push_pull_output(); - let mut _kso11 = pins.kso11.into_push_pull_output(); - let mut _kso12 = pins.kso12.into_push_pull_output(); - let mut _kso13 = pins.kso13.into_push_pull_output(); - let mut _kso14 = pins.kso14.into_push_pull_output(); - let mut _kso15 = pins.kso15.into_push_pull_output(); + let kso8 = pins.kso8.into_push_pull_output(); + let kso9 = pins.kso9.into_push_pull_output(); + let kso10 = pins.kso10.into_push_pull_output(); + let kso11 = pins.kso11.into_push_pull_output(); + let kso12 = pins.kso12.into_push_pull_output(); + let kso13 = pins.kso13.into_push_pull_output(); + let kso14 = pins.kso14.into_push_pull_output(); + let kso15 = pins.kso15.into_push_pull_output(); // Set unused pins to input to avoid interfering. They're hooked up to rows 5 and 6 let _ = pins.ksi5_reserved.into_floating_input(); let _ = pins.ksi6_reserved.into_floating_input(); @@ -191,6 +351,22 @@ fn main() -> ! { let mut animation_timer = timer.get_counter().ticks(); caps_led.set_high().unwrap(); + let adc = Adc::new(pac.ADC, &mut pac.RESETS); + let adc_x = pins.analog_in.into_pull_up_input(); + + let mut scanner = Scanner { + kso: ( + kso0, kso1, kso2, kso3, kso4, kso5, kso6, kso7, kso8, kso9, kso10, kso11, kso12, kso13, + kso14, kso15, + ), + mux: Mux { + a: mux_a, + b: mux_b, + c: mux_c, + }, + adc: (adc, adc_x), + }; + let mut usb_initialized; let mut usb_suspended = false; loop { @@ -214,6 +390,23 @@ fn main() -> ! { animation_timer = timer.get_counter().ticks(); } + if timer.get_counter().ticks() > animation_timer + 500_000 { + let left = scanner.measure_key(6, 11); + let up = scanner.measure_key(1, 13); + let down = scanner.measure_key(1, 8); + let right = scanner.measure_key(2, 15); + let mut text: String<64> = String::new(); + write!( + &mut text, + "L:{}.{:0>4}V, R:{}.{:0>4}V, U:{}.{:0>4}V, D:{}.{:0>4}V\r\n", + left.0, left.1, right.0, right.1, up.0, up.1, down.0, down.1 + ) + .unwrap(); + let _ = serial.write(text.as_bytes()); + + animation_timer = timer.get_counter().ticks(); + } + // Check for new data if usb_dev.poll(&mut [&mut serial]) { match usb_dev.state() { @@ -239,6 +432,9 @@ fn main() -> ! { let _ = usb_initialized; let _ = usb_suspended; + let kb = Matrix::default(); + let kb = scanner.scan(); + let mut buf = [0u8; 64]; match serial.read(&mut buf) { Err(_e) => { @@ -247,15 +443,20 @@ fn main() -> ! { Ok(0) => { // Do nothing } - Ok(count) => { - let mut text: String<64> = String::new(); - write!( - &mut text, - "Hello World: Usb Suspended: {}. C: {}\r\n", - usb_suspended, count - ) - .unwrap(); - let _ = serial.write(text.as_bytes()); + Ok(_count) => { + match buf[0] { + b'r' => rp2040_hal::rom_data::reset_to_usb_boot(0, 0), + _ => (), + } + //let mut text: String<64> = String::new(); + //write!(&mut text, " 01234567\r\n").unwrap(); + //let _ = serial.write(text.as_bytes()); + + //for col in 0..MATRIX_COLS { + // let mut text: String<64> = String::new(); + // write!(&mut text, "{:2}: {}\r\n", col, kb.0[col]).unwrap(); + // let _ = serial.write(text.as_bytes()); + //} } } } else { From c408a6a34c9a662d79568291e91d0d725b58bfb5 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 30 Sep 2023 19:11:39 +0800 Subject: [PATCH 03/16] fixup! Implement basic keyboard firmware --- keyboard/Makefile.toml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/keyboard/Makefile.toml b/keyboard/Makefile.toml index ea7d5ecc..38bc921b 100644 --- a/keyboard/Makefile.toml +++ b/keyboard/Makefile.toml @@ -2,11 +2,18 @@ extend = "../Makefile.toml" [tasks.uf2] command = "elf2uf2-rs" -args = ["../target/thumbv6m-none-eabi/release/b1display", "../target/thumbv6m-none-eabi/release/b1display.uf2"] +args = [ + "../target/thumbv6m-none-eabi/release/keyboard", + "../target/thumbv6m-none-eabi/release/keyboard.uf2", +] dependencies = ["build-release"] install_crate = "elf2uf2-rs" [tasks.bin] command = "llvm-objcopy" -args = ["-Obinary", "../target/thumbv6m-none-eabi/release/b1display", "../target/thumbv6m-none-eabi/release/b1display.bin"] +args = [ + "-Obinary", + "../target/thumbv6m-none-eabi/release/keyboard", + "../target/thumbv6m-none-eabi/release/keyboard.bin", +] dependencies = ["build-release"] From f54cc954b00287a82a948b5f03461ae38f5206a8 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 30 Sep 2023 19:19:14 +0800 Subject: [PATCH 04/16] fixup! keyboard: Implement reading of arrow keys --- keyboard/src/main.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 306a8178..5c66ea0f 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -395,15 +395,30 @@ fn main() -> ! { let up = scanner.measure_key(1, 13); let down = scanner.measure_key(1, 8); let right = scanner.measure_key(2, 15); + let mut text: String<64> = String::new(); write!( &mut text, - "L:{}.{:0>4}V, R:{}.{:0>4}V, U:{}.{:0>4}V, D:{}.{:0>4}V\r\n", + "L:{}.{:0>3}V, R:{}.{:0>3}V, U:{}.{:0>3}V, D:{}.{:0>3}V\r\n", left.0, left.1, right.0, right.1, up.0, up.1, down.0, down.1 ) .unwrap(); let _ = serial.write(text.as_bytes()); + let left_p = left.0 < 2 || (left.0 == 2 && left.1 < 290); + let right_p = right.0 < 2 || (right.0 == 2 && right.1 < 290); + let up_p = up.0 < 2 || (up.0 == 2 && up.1 < 290); + let down_p = down.0 < 2 || (up.0 == 2 && down.1 < 290); + + let mut text: String<64> = String::new(); + write!( + &mut text, + "L:{:5}, R:{:5}, U:{:5}, D:{:5}\r\n", + left_p, right_p, up_p, down_p + ) + .unwrap(); + let _ = serial.write(text.as_bytes()); + animation_timer = timer.get_counter().ticks(); } From 6a421208eb75fef4aace4a988e51cace06b4833f Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sat, 30 Sep 2023 23:32:08 +0800 Subject: [PATCH 05/16] keyboard: Implement HID keyboard TODO: - [x] Basic keyscan - [x] Send UP/LEFT/RIGHT/CAPS HID reports, DOWN to go into bootloader - [x] Can go into D2 (tested on Linux) - [x] Can wake host (remote wakeup) - [ ] Both serial and HID keyboard as composite device - [ ] Key Debouncing - [ ] 1-Zone PWM backlight - [ ] RGB backlight (needs new/modified Rust driver) - [ ] Separate builds for different keyboard variants - [ ] Measure and optimize scan frequency - [ ] Implement full key matrix with all keys - [ ] Implement second layer for FN (including FN lock) - [ ] Persist brightness setting and FN lock through reset - [ ] Media keys Signed-off-by: Daniel Schaefer --- keyboard/Cargo.toml | 2 + keyboard/src/main.rs | 180 +++++++++++++++++++++++++++++-------------- 2 files changed, 126 insertions(+), 56 deletions(-) diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml index f16b1b94..7ee13d62 100644 --- a/keyboard/Cargo.toml +++ b/keyboard/Cargo.toml @@ -34,6 +34,8 @@ usbd-serial.workspace = true usbd-hid.workspace = true fugit.workspace = true +usbd-human-interface-device = "0.3.1" + [dependencies.fl16-inputmodules] path = "../fl16-inputmodules" features = ["keyboard"] diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 5c66ea0f..81547fe2 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -4,6 +4,22 @@ #![no_main] #![allow(clippy::needless_range_loop)] +// TODO: +// - [x] Basic keyscan +// - [x] Send UP/LEFT/RIGHT/CAPS HID reports, DOWN to go into bootloader +// - [x] Can go into D2 (tested on Linux) +// - [x] Can wake host (remote wakeup) +// - [ ] Both serial and HID keyboard as composite device +// - [ ] Key Debouncing +// - [ ] 1-Zone PWM backlight +// - [ ] RGB backlight (needs new/modified Rust driver) +// - [ ] Separate builds for different keyboard variants +// - [ ] Measure and optimize scan frequency +// - [ ] Implement full key matrix with all keys +// - [ ] Implement second layer for FN (including FN lock) +// - [ ] Persist brightness setting and FN lock through reset +// - [ ] Media keys + //use cortex_m::delay::Delay; //use defmt::*; use defmt_rtt as _; @@ -11,6 +27,10 @@ use embedded_hal::adc::OneShot; use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin}; use rp2040_hal::gpio::bank0::Gpio28; use rp2040_hal::gpio::{Input, PullUp}; +use usbd_human_interface_device::device::keyboard::BootKeyboardInterface; +use usbd_human_interface_device::page::Keyboard; +use usbd_human_interface_device::prelude::UsbHidClassBuilder; +use usbd_human_interface_device::UsbHidError; use core::fmt::Display; use core::fmt::{self, Formatter}; @@ -168,6 +188,7 @@ impl Scanner { self.drive_col(col, PinState::Low); self.mux.select_row(row); + // Let column and mux settle a bit cortex_m::asm::delay(2000); let adc_read: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); @@ -245,7 +266,10 @@ fn main() -> ! { )); // Set up the USB Communications Class Device driver - let mut serial = SerialPort::new(&usb_bus); + //let mut serial = SerialPort::new(&usb_bus); + let mut keyboard_hid = UsbHidClassBuilder::new() + .add_interface(BootKeyboardInterface::default_config()) + .build(&usb_bus); #[cfg(feature = "macropad")] let pid = 0x013; @@ -272,8 +296,10 @@ fn main() -> ! { let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x32ac, pid)) .manufacturer("Framework Computer Inc") .product(product) - //.supports_remote_wakeup(true) - .device_class(USB_CLASS_CDC) + .supports_remote_wakeup(true) + .device_class(0) + .device_sub_class(0) + .device_protocol(0) .max_power(MAX_CURRENT) .serial_number("testing") .device_release(device_release()) @@ -285,7 +311,6 @@ fn main() -> ! { // pins.gp26 // SDA // pins.gp27 // SCL - // pins.analog_in let mut caps_led = pins.caps_led.into_push_pull_output(); let mut _backlight = pins.backlight.into_push_pull_output(); @@ -348,7 +373,8 @@ fn main() -> ! { // fill_grid_pixels(&state, &mut matrix); let timer = Timer::new(pac.TIMER, &mut pac.RESETS); - let mut animation_timer = timer.get_counter().ticks(); + let mut scan_timer = timer.get_counter().ticks(); + let mut capslock_timer = timer.get_counter().ticks(); caps_led.set_high().unwrap(); let adc = Adc::new(pac.ADC, &mut pac.RESETS); @@ -381,49 +407,89 @@ fn main() -> ! { // Blink when in USB Suspend // 500_000us = 500ms = 0.5s - if usb_suspended && timer.get_counter().ticks() > animation_timer + 500_000 { + if usb_suspended && timer.get_counter().ticks() > capslock_timer + 500_000 { if caps_led.is_set_high().unwrap() { caps_led.set_low().unwrap(); } else { caps_led.set_high().unwrap(); } - animation_timer = timer.get_counter().ticks(); + capslock_timer = timer.get_counter().ticks(); } - if timer.get_counter().ticks() > animation_timer + 500_000 { + let mut keycode: Option = None; + if timer.get_counter().ticks() > scan_timer + 250_000 { let left = scanner.measure_key(6, 11); let up = scanner.measure_key(1, 13); let down = scanner.measure_key(1, 8); let right = scanner.measure_key(2, 15); + let caps = scanner.measure_key(4, 4); - let mut text: String<64> = String::new(); - write!( - &mut text, - "L:{}.{:0>3}V, R:{}.{:0>3}V, U:{}.{:0>3}V, D:{}.{:0>3}V\r\n", - left.0, left.1, right.0, right.1, up.0, up.1, down.0, down.1 - ) - .unwrap(); - let _ = serial.write(text.as_bytes()); + // let mut text: String<64> = String::new(); + // write!( + // &mut text, + // "L:{}.{:0>3}V, R:{}.{:0>3}V, U:{}.{:0>3}V, D:{}.{:0>3}V\r\n", + // left.0, left.1, right.0, right.1, up.0, up.1, down.0, down.1 + // ) + // .unwrap(); + // let _ = serial.write(text.as_bytes()); let left_p = left.0 < 2 || (left.0 == 2 && left.1 < 290); let right_p = right.0 < 2 || (right.0 == 2 && right.1 < 290); let up_p = up.0 < 2 || (up.0 == 2 && up.1 < 290); - let down_p = down.0 < 2 || (up.0 == 2 && down.1 < 290); - - let mut text: String<64> = String::new(); - write!( - &mut text, - "L:{:5}, R:{:5}, U:{:5}, D:{:5}\r\n", - left_p, right_p, up_p, down_p - ) - .unwrap(); - let _ = serial.write(text.as_bytes()); - - animation_timer = timer.get_counter().ticks(); + let down_p = down.0 < 2 || (down.0 == 2 && down.1 < 290); + let caps_p = caps.0 < 2 || (caps.0 == 2 && caps.1 < 290); + + // let mut text: String<64> = String::new(); + // write!( + // &mut text, + // "L:{:5}, R:{:5}, U:{:5}, D:{:5}\r\n", + // left_p, right_p, up_p, down_p + // ) + // .unwrap(); + // let _ = serial.write(text.as_bytes()); + + if left_p { + keycode = Some(Keyboard::LeftArrow); + } else if right_p { + keycode = Some(Keyboard::RightArrow); + } else if up_p { + keycode = Some(Keyboard::UpArrow); + } else if down_p { + keycode = None; + rp2040_hal::rom_data::reset_to_usb_boot(0, 0); + } else if caps_p { + keycode = Some(Keyboard::CapsLock); + } else { + keycode = None; + } + + scan_timer = timer.get_counter().ticks(); + } + + let _ = keyboard_hid.interface().read_report(); + + // Setup the report for the control channel + let keycodes = if let Some(keycode) = keycode { + [keycode] + } else { + [Keyboard::NoEventIndicated] + }; + match keyboard_hid.interface().write_report(keycodes) { + Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} + Err(e) => panic!("Failed to write keyboard report: {:?}", e), + } + match keyboard_hid.interface().tick() { + Err(UsbHidError::WouldBlock) | Ok(_) => {} + Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } + + // Wake the host. + if keycode.is_some() && usb_suspended && usb_dev.remote_wakeup_enabled() { + usb_dev.bus().remote_wakeup(); } // Check for new data - if usb_dev.poll(&mut [&mut serial]) { + if usb_dev.poll(&mut [&mut keyboard_hid]) { match usb_dev.state() { // Default: Device has just been created or reset // Addressed: Device has received an address for the host @@ -447,33 +513,35 @@ fn main() -> ! { let _ = usb_initialized; let _ = usb_suspended; - let kb = Matrix::default(); - let kb = scanner.scan(); - - let mut buf = [0u8; 64]; - match serial.read(&mut buf) { - Err(_e) => { - // Do nothing - } - Ok(0) => { - // Do nothing - } - Ok(_count) => { - match buf[0] { - b'r' => rp2040_hal::rom_data::reset_to_usb_boot(0, 0), - _ => (), - } - //let mut text: String<64> = String::new(); - //write!(&mut text, " 01234567\r\n").unwrap(); - //let _ = serial.write(text.as_bytes()); - - //for col in 0..MATRIX_COLS { - // let mut text: String<64> = String::new(); - // write!(&mut text, "{:2}: {}\r\n", col, kb.0[col]).unwrap(); - // let _ = serial.write(text.as_bytes()); - //} - } - } + //let kb = Matrix::default(); + //let kb = scanner.scan(); + + keyboard_hid.poll(); + + // let mut buf = [0u8; 64]; + // match serial.read(&mut buf) { + // Err(_e) => { + // // Do nothing + // } + // Ok(0) => { + // // Do nothing + // } + // Ok(_count) => { + // match buf[0] { + // b'r' => rp2040_hal::rom_data::reset_to_usb_boot(0, 0), + // _ => (), + // } + // //let mut text: String<64> = String::new(); + // //write!(&mut text, " 01234567\r\n").unwrap(); + // //let _ = serial.write(text.as_bytes()); + + // //for col in 0..MATRIX_COLS { + // // let mut text: String<64> = String::new(); + // // write!(&mut text, "{:2}: {}\r\n", col, kb.0[col]).unwrap(); + // // let _ = serial.write(text.as_bytes()); + // //} + // } + // } } else { match usb_dev.state() { // No new data From 8af1d0b2326a1f675fd3353541d01d0631859b13 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 1 Oct 2023 00:22:40 +0800 Subject: [PATCH 06/16] keyboard: Light up RGB backlight Just all white Signed-off-by: Daniel Schaefer --- keyboard/Cargo.toml | 1 + keyboard/src/main.rs | 61 +++++++++++++++++++++++++------------------- 2 files changed, 36 insertions(+), 26 deletions(-) diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml index 7ee13d62..51fc93e5 100644 --- a/keyboard/Cargo.toml +++ b/keyboard/Cargo.toml @@ -35,6 +35,7 @@ usbd-hid.workspace = true fugit.workspace = true usbd-human-interface-device = "0.3.1" +is31fl3741.workspace = true [dependencies.fl16-inputmodules] path = "../fl16-inputmodules" diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 81547fe2..edb9bf8b 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -12,7 +12,9 @@ // - [ ] Both serial and HID keyboard as composite device // - [ ] Key Debouncing // - [ ] 1-Zone PWM backlight -// - [ ] RGB backlight (needs new/modified Rust driver) +// - [x] RGB backlight (needs new/modified Rust driver) +// - [x] Working (all white) +// - [ ] Map all LEDs // - [ ] Separate builds for different keyboard variants // - [ ] Measure and optimize scan frequency // - [ ] Implement full key matrix with all keys @@ -22,16 +24,19 @@ //use cortex_m::delay::Delay; //use defmt::*; +use crate::rgb_matrix::{LedMatrix, DVT2_CALC_PIXEL}; use defmt_rtt as _; use embedded_hal::adc::OneShot; use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin}; use rp2040_hal::gpio::bank0::Gpio28; -use rp2040_hal::gpio::{Input, PullUp}; +use rp2040_hal::gpio::{self, Input, PullUp}; use usbd_human_interface_device::device::keyboard::BootKeyboardInterface; use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::prelude::UsbHidClassBuilder; use usbd_human_interface_device::UsbHidError; +mod rgb_matrix; + use core::fmt::Display; use core::fmt::{self, Formatter}; @@ -66,6 +71,7 @@ use bsp::hal::{ usb, watchdog::Watchdog, }; +use fugit::RateExtU32; // USB Device support use usb_device::{class_prelude::*, prelude::*}; @@ -247,7 +253,7 @@ fn main() -> ! { let rosc = rp2040_hal::rosc::RingOscillator::new(pac.ROSC); let _rosc = rosc.initialize(); - let mut _delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); + let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); let pins = bsp::Pins::new( pac.IO_BANK0, @@ -347,30 +353,33 @@ fn main() -> ! { let sleep = pins.sleep.into_floating_input(); // Enable LED controller - // SDB let mut led_enable = pins.sdb.into_push_pull_output(); - led_enable.set_low().unwrap(); - // led_enable.set_high().unwrap(); - // - // let i2c = bsp::hal::I2C::i2c1( - // pac.I2C1, - // pins.gpio26.into_mode::(), - // pins.gpio27.into_mode::(), - // 1000.kHz(), - // &mut pac.RESETS, - // &clocks.peripheral_clock, - // ); - // - // let mut matrix = LedMatrix::new(i2c, DVT2_CALC_PIXEL); - // matrix - // .setup(&mut delay) - // .expect("failed to setup RGB controller"); - // - // matrix - // .set_scaling(MAX_BRIGHTNESS) - // .expect("failed to set scaling"); - // - // fill_grid_pixels(&state, &mut matrix); + led_enable.set_high().unwrap(); + + let i2c = bsp::hal::I2C::i2c1( + pac.I2C1, + pins.gpio26.into_mode::(), + pins.gpio27.into_mode::(), + 1000.kHz(), + &mut pac.RESETS, + &clocks.peripheral_clock, + ); + + let mut matrix = LedMatrix::new(i2c, DVT2_CALC_PIXEL); + + matrix.set_address(0b0100000); + matrix + .setup(&mut delay) + .expect("failed to setup RGB controller"); + matrix.set_scaling(0xFF).expect("failed to set scaling"); + matrix.device.fill(0xFF); + + matrix.set_address(0b0100011); + matrix + .setup(&mut delay) + .expect("failed to setup RGB controller"); + matrix.set_scaling(0xFF).expect("failed to set scaling"); + matrix.device.fill(0xFF); let timer = Timer::new(pac.TIMER, &mut pac.RESETS); let mut scan_timer = timer.get_counter().ticks(); From e5db69b3cda1707a90645fa4b99ad75ce671c7c2 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 1 Oct 2023 13:13:31 +0800 Subject: [PATCH 07/16] keyboard: Avoid HID activity in USB suspend Signed-off-by: Daniel Schaefer --- keyboard/src/main.rs | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index edb9bf8b..53826cfb 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -475,21 +475,23 @@ fn main() -> ! { scan_timer = timer.get_counter().ticks(); } - let _ = keyboard_hid.interface().read_report(); + if !usb_suspended { + let _ = keyboard_hid.interface().read_report(); - // Setup the report for the control channel - let keycodes = if let Some(keycode) = keycode { - [keycode] - } else { - [Keyboard::NoEventIndicated] - }; - match keyboard_hid.interface().write_report(keycodes) { - Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} - Err(e) => panic!("Failed to write keyboard report: {:?}", e), - } - match keyboard_hid.interface().tick() { - Err(UsbHidError::WouldBlock) | Ok(_) => {} - Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + // Setup the report for the control channel + let keycodes = if let Some(keycode) = keycode { + [keycode] + } else { + [Keyboard::NoEventIndicated] + }; + match keyboard_hid.interface().write_report(keycodes) { + Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} + Err(e) => panic!("Failed to write keyboard report: {:?}", e), + } + match keyboard_hid.interface().tick() { + Err(UsbHidError::WouldBlock) | Ok(_) => {} + Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } } // Wake the host. From d47d7185b05cd913953a2e6a108c9e9d7b362fcd Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 1 Oct 2023 18:13:24 +0800 Subject: [PATCH 08/16] keyboard: Move HID code into USB poll Automatically handles not doing anything if in USB suspend. Signed-off-by: Daniel Schaefer --- keyboard/src/main.rs | 36 ++++++++++++++++-------------------- 1 file changed, 16 insertions(+), 20 deletions(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 53826cfb..c91709b7 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -475,25 +475,6 @@ fn main() -> ! { scan_timer = timer.get_counter().ticks(); } - if !usb_suspended { - let _ = keyboard_hid.interface().read_report(); - - // Setup the report for the control channel - let keycodes = if let Some(keycode) = keycode { - [keycode] - } else { - [Keyboard::NoEventIndicated] - }; - match keyboard_hid.interface().write_report(keycodes) { - Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} - Err(e) => panic!("Failed to write keyboard report: {:?}", e), - } - match keyboard_hid.interface().tick() { - Err(UsbHidError::WouldBlock) | Ok(_) => {} - Err(e) => panic!("Failed to process keyboard tick: {:?}", e), - } - } - // Wake the host. if keycode.is_some() && usb_suspended && usb_dev.remote_wakeup_enabled() { usb_dev.bus().remote_wakeup(); @@ -527,7 +508,22 @@ fn main() -> ! { //let kb = Matrix::default(); //let kb = scanner.scan(); - keyboard_hid.poll(); + let _ = keyboard_hid.interface().read_report(); + + // Setup the report for the control channel + let keycodes = if let Some(keycode) = keycode { + [keycode] + } else { + [Keyboard::NoEventIndicated] + }; + match keyboard_hid.interface().write_report(keycodes) { + Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} + Err(e) => panic!("Failed to write keyboard report: {:?}", e), + } + match keyboard_hid.interface().tick() { + Err(UsbHidError::WouldBlock) | Ok(_) => {} + Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } // let mut buf = [0u8; 64]; // match serial.read(&mut buf) { From f5a9de4192c41ecb43868557304bc32064e8e1c3 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 3 Oct 2023 11:46:51 +0800 Subject: [PATCH 09/16] Revert "keyboard: Move HID code into USB poll" This reverts commit 246b8553db61e881d039b472d9b60eb6fa746f54. --- keyboard/src/main.rs | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index c91709b7..53826cfb 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -475,6 +475,25 @@ fn main() -> ! { scan_timer = timer.get_counter().ticks(); } + if !usb_suspended { + let _ = keyboard_hid.interface().read_report(); + + // Setup the report for the control channel + let keycodes = if let Some(keycode) = keycode { + [keycode] + } else { + [Keyboard::NoEventIndicated] + }; + match keyboard_hid.interface().write_report(keycodes) { + Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} + Err(e) => panic!("Failed to write keyboard report: {:?}", e), + } + match keyboard_hid.interface().tick() { + Err(UsbHidError::WouldBlock) | Ok(_) => {} + Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } + } + // Wake the host. if keycode.is_some() && usb_suspended && usb_dev.remote_wakeup_enabled() { usb_dev.bus().remote_wakeup(); @@ -508,22 +527,7 @@ fn main() -> ! { //let kb = Matrix::default(); //let kb = scanner.scan(); - let _ = keyboard_hid.interface().read_report(); - - // Setup the report for the control channel - let keycodes = if let Some(keycode) = keycode { - [keycode] - } else { - [Keyboard::NoEventIndicated] - }; - match keyboard_hid.interface().write_report(keycodes) { - Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} - Err(e) => panic!("Failed to write keyboard report: {:?}", e), - } - match keyboard_hid.interface().tick() { - Err(UsbHidError::WouldBlock) | Ok(_) => {} - Err(e) => panic!("Failed to process keyboard tick: {:?}", e), - } + keyboard_hid.poll(); // let mut buf = [0u8; 64]; // match serial.read(&mut buf) { From 1298eef36bf864770f37e79818545409eb5f6404 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 24 Oct 2023 01:09:47 +0800 Subject: [PATCH 10/16] keyboard: Separate build per variant ``` > cargo run -p keyboard --features ansi > cargo run -p keyboard --features numpad > cargo run -p keyboard --features macropad ``` Signed-off-by: Daniel Schaefer --- Cargo.lock | 1 + keyboard/Cargo.toml | 2 + keyboard/src/main.rs | 132 +++++++++++++++++++++++++------------------ 3 files changed, 79 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b9e3ec47..7923264a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1179,6 +1179,7 @@ dependencies = [ name = "keyboard" version = "0.1.7" dependencies = [ + "cfg-if", "cortex-m", "cortex-m-rt", "defmt", diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml index 51fc93e5..9ed709b2 100644 --- a/keyboard/Cargo.toml +++ b/keyboard/Cargo.toml @@ -37,6 +37,8 @@ fugit.workspace = true usbd-human-interface-device = "0.3.1" is31fl3741.workspace = true +cfg-if = "1.0.0" + [dependencies.fl16-inputmodules] path = "../fl16-inputmodules" features = ["keyboard"] diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 53826cfb..e4b67611 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -367,19 +367,27 @@ fn main() -> ! { let mut matrix = LedMatrix::new(i2c, DVT2_CALC_PIXEL); - matrix.set_address(0b0100000); - matrix - .setup(&mut delay) - .expect("failed to setup RGB controller"); - matrix.set_scaling(0xFF).expect("failed to set scaling"); - matrix.device.fill(0xFF); - - matrix.set_address(0b0100011); - matrix - .setup(&mut delay) - .expect("failed to setup RGB controller"); - matrix.set_scaling(0xFF).expect("failed to set scaling"); - matrix.device.fill(0xFF); + cfg_if::cfg_if! { + if #[cfg(any(feature = "ansi", feature = "macropad"))] { + matrix.set_address(0b0100000); + matrix + .setup(&mut delay) + .expect("failed to setup RGB controller"); + matrix.set_scaling(0xFF).expect("failed to set scaling"); + matrix.device.fill(0xFF); + } + } + + cfg_if::cfg_if! { + if #[cfg(feature = "ansi")] { + matrix.set_address(0b0100011); + matrix + .setup(&mut delay) + .expect("failed to setup RGB controller"); + matrix.set_scaling(0xFF).expect("failed to set scaling"); + matrix.device.fill(0xFF); + } + } let timer = Timer::new(pac.TIMER, &mut pac.RESETS); let mut scan_timer = timer.get_counter().ticks(); @@ -427,49 +435,61 @@ fn main() -> ! { let mut keycode: Option = None; if timer.get_counter().ticks() > scan_timer + 250_000 { - let left = scanner.measure_key(6, 11); - let up = scanner.measure_key(1, 13); - let down = scanner.measure_key(1, 8); - let right = scanner.measure_key(2, 15); - let caps = scanner.measure_key(4, 4); - - // let mut text: String<64> = String::new(); - // write!( - // &mut text, - // "L:{}.{:0>3}V, R:{}.{:0>3}V, U:{}.{:0>3}V, D:{}.{:0>3}V\r\n", - // left.0, left.1, right.0, right.1, up.0, up.1, down.0, down.1 - // ) - // .unwrap(); - // let _ = serial.write(text.as_bytes()); - - let left_p = left.0 < 2 || (left.0 == 2 && left.1 < 290); - let right_p = right.0 < 2 || (right.0 == 2 && right.1 < 290); - let up_p = up.0 < 2 || (up.0 == 2 && up.1 < 290); - let down_p = down.0 < 2 || (down.0 == 2 && down.1 < 290); - let caps_p = caps.0 < 2 || (caps.0 == 2 && caps.1 < 290); - - // let mut text: String<64> = String::new(); - // write!( - // &mut text, - // "L:{:5}, R:{:5}, U:{:5}, D:{:5}\r\n", - // left_p, right_p, up_p, down_p - // ) - // .unwrap(); - // let _ = serial.write(text.as_bytes()); - - if left_p { - keycode = Some(Keyboard::LeftArrow); - } else if right_p { - keycode = Some(Keyboard::RightArrow); - } else if up_p { - keycode = Some(Keyboard::UpArrow); - } else if down_p { - keycode = None; - rp2040_hal::rom_data::reset_to_usb_boot(0, 0); - } else if caps_p { - keycode = Some(Keyboard::CapsLock); - } else { - keycode = None; + cfg_if::cfg_if! { + if #[cfg(any(feature = "ansi", feature = "iso", feature = "jis"))] { + let left = scanner.measure_key(6, 11); + let up = scanner.measure_key(1, 13); + let down = scanner.measure_key(1, 8); + let right = scanner.measure_key(2, 15); + let caps = scanner.measure_key(4, 4); + + let left_p = left.0 < 2 || (left.0 == 2 && left.1 < 290); + let right_p = right.0 < 2 || (right.0 == 2 && right.1 < 290); + let up_p = up.0 < 2 || (up.0 == 2 && up.1 < 290); + let down_p = down.0 < 2 || (down.0 == 2 && down.1 < 290); + let caps_p = caps.0 < 2 || (caps.0 == 2 && caps.1 < 290); + + if left_p { + keycode = Some(Keyboard::LeftArrow); + } else if right_p { + keycode = Some(Keyboard::RightArrow); + } else if up_p { + keycode = Some(Keyboard::UpArrow); + } else if down_p { + keycode = None; + rp2040_hal::rom_data::reset_to_usb_boot(0, 0); + } else if caps_p { + keycode = Some(Keyboard::CapsLock); + } else { + keycode = None; + } + } + } + + cfg_if::cfg_if! { + if #[cfg(any(feature = "numapd", feature = "macropad"))] { + let one = scanner.measure_key(0, 3); + let two = scanner.measure_key(0, 7); + let three = scanner.measure_key(1, 4); + let four = scanner.measure_key(2, 6); + + let one_p = one.0 < 2 || (one.0 == 2 && one.1 < 290); + let two_p = two.0 < 2 || (two.0 == 2 && two.1 < 290); + let three_p = three.0 < 2 || (three.0 == 2 && three.1 < 290); + let four_p = four.0 < 2 || (four.0 == 2 && four.1 < 290); + + if one_p { + keycode = Some(Keyboard::Keyboard1); + } else if two_p { + keycode = Some(Keyboard::Keyboard2); + } else if three_p { + keycode = Some(Keyboard::Keyboard3); + } else if four_p { + keycode = Some(Keyboard::Keyboard4); + } else { + keycode = None; + } + } } scan_timer = timer.get_counter().ticks(); From 5b1af0314ba1b8ec9ea4cdc04b4af5a0bbdbffaa Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 24 Oct 2023 01:11:14 +0800 Subject: [PATCH 11/16] fixup! keyboard: Light up RGB backlight --- keyboard/src/rgb_matrix.rs | 377 +++++++++++++++++++++++++++++++++++++ 1 file changed, 377 insertions(+) create mode 100644 keyboard/src/rgb_matrix.rs diff --git a/keyboard/src/rgb_matrix.rs b/keyboard/src/rgb_matrix.rs new file mode 100644 index 00000000..3b077022 --- /dev/null +++ b/keyboard/src/rgb_matrix.rs @@ -0,0 +1,377 @@ +// #[cfg_attr(docsrs, doc(cfg(feature = "adafruit_rgb_13x9")))] +#[allow(unused_imports)] +use core::convert::TryFrom; +#[allow(unused_imports)] +use embedded_hal::blocking::delay::DelayMs; +use embedded_hal::blocking::i2c::Read; +use embedded_hal::blocking::i2c::Write; +#[allow(unused_imports)] +use is31fl3741::{Error, IS31FL3743}; + +pub const DVT2_CALC_PIXEL: fn(x: u8, y: u8) -> (u8, u8) = |x: u8, y: u8| -> (u8, u8) { + // Generated by led-matrix.py + let lookup: [(u8, u8); 34 * 9] = [ + (0x00, 0), // x: 1, y: 1, sw: 1, cs: 1, id: 1 + (0x1e, 0), // x: 2, y: 1, sw: 2, cs: 1, id: 2 + (0x3c, 0), // x: 3, y: 1, sw: 3, cs: 1, id: 3 + (0x5a, 0), // x: 4, y: 1, sw: 4, cs: 1, id: 4 + (0x78, 0), // x: 5, y: 1, sw: 5, cs: 1, id: 5 + (0x96, 0), // x: 6, y: 1, sw: 6, cs: 1, id: 6 + (0x00, 1), // x: 7, y: 1, sw: 7, cs: 1, id: 7 + (0x1e, 1), // x: 8, y: 1, sw: 8, cs: 1, id: 8 + (0x5f, 1), // x: 9, y: 1, sw: 1, cs:36, id: 9 + (0x01, 0), // x: 1, y: 2, sw: 1, cs: 2, id: 10 + (0x1f, 0), // x: 2, y: 2, sw: 2, cs: 2, id: 11 + (0x3d, 0), // x: 3, y: 2, sw: 3, cs: 2, id: 12 + (0x5b, 0), // x: 4, y: 2, sw: 4, cs: 2, id: 13 + (0x79, 0), // x: 5, y: 2, sw: 5, cs: 2, id: 14 + (0x97, 0), // x: 6, y: 2, sw: 6, cs: 2, id: 15 + (0x01, 1), // x: 7, y: 2, sw: 7, cs: 2, id: 16 + (0x1f, 1), // x: 8, y: 2, sw: 8, cs: 2, id: 17 + (0x60, 1), // x: 9, y: 2, sw: 1, cs:37, id: 18 + (0x02, 0), // x: 1, y: 3, sw: 1, cs: 3, id: 19 + (0x20, 0), // x: 2, y: 3, sw: 2, cs: 3, id: 20 + (0x3e, 0), // x: 3, y: 3, sw: 3, cs: 3, id: 21 + (0x5c, 0), // x: 4, y: 3, sw: 4, cs: 3, id: 22 + (0x7a, 0), // x: 5, y: 3, sw: 5, cs: 3, id: 23 + (0x98, 0), // x: 6, y: 3, sw: 6, cs: 3, id: 24 + (0x02, 1), // x: 7, y: 3, sw: 7, cs: 3, id: 25 + (0x20, 1), // x: 8, y: 3, sw: 8, cs: 3, id: 26 + (0x61, 1), // x: 9, y: 3, sw: 1, cs:38, id: 27 + (0x03, 0), // x: 1, y: 4, sw: 1, cs: 4, id: 28 + (0x21, 0), // x: 2, y: 4, sw: 2, cs: 4, id: 29 + (0x3f, 0), // x: 3, y: 4, sw: 3, cs: 4, id: 30 + (0x5d, 0), // x: 4, y: 4, sw: 4, cs: 4, id: 31 + (0x7b, 0), // x: 5, y: 4, sw: 5, cs: 4, id: 32 + (0x99, 0), // x: 6, y: 4, sw: 6, cs: 4, id: 33 + (0x03, 1), // x: 7, y: 4, sw: 7, cs: 4, id: 34 + (0x21, 1), // x: 8, y: 4, sw: 8, cs: 4, id: 35 + (0x62, 1), // x: 9, y: 4, sw: 1, cs:39, id: 36 + (0x04, 0), // x: 1, y: 5, sw: 1, cs: 5, id: 37 + (0x22, 0), // x: 2, y: 5, sw: 2, cs: 5, id: 41 + (0x40, 0), // x: 3, y: 5, sw: 3, cs: 5, id: 45 + (0x5e, 0), // x: 4, y: 5, sw: 4, cs: 5, id: 49 + (0x7c, 0), // x: 5, y: 5, sw: 5, cs: 5, id: 53 + (0x9a, 0), // x: 6, y: 5, sw: 6, cs: 5, id: 57 + (0x04, 1), // x: 7, y: 5, sw: 7, cs: 5, id: 61 + (0x22, 1), // x: 8, y: 5, sw: 8, cs: 5, id: 65 + (0x5e, 1), // x: 9, y: 5, sw: 1, cs:35, id: 69 + (0x05, 0), // x: 1, y: 6, sw: 1, cs: 6, id: 38 + (0x23, 0), // x: 2, y: 6, sw: 2, cs: 6, id: 42 + (0x41, 0), // x: 3, y: 6, sw: 3, cs: 6, id: 46 + (0x5f, 0), // x: 4, y: 6, sw: 4, cs: 6, id: 50 + (0x7d, 0), // x: 5, y: 6, sw: 5, cs: 6, id: 54 + (0x9b, 0), // x: 6, y: 6, sw: 6, cs: 6, id: 58 + (0x05, 1), // x: 7, y: 6, sw: 7, cs: 6, id: 62 + (0x23, 1), // x: 8, y: 6, sw: 8, cs: 6, id: 66 + (0x68, 1), // x: 9, y: 6, sw: 2, cs:36, id: 70 + (0x06, 0), // x: 1, y: 7, sw: 1, cs: 7, id: 39 + (0x24, 0), // x: 2, y: 7, sw: 2, cs: 7, id: 43 + (0x42, 0), // x: 3, y: 7, sw: 3, cs: 7, id: 47 + (0x60, 0), // x: 4, y: 7, sw: 4, cs: 7, id: 51 + (0x7e, 0), // x: 5, y: 7, sw: 5, cs: 7, id: 55 + (0x9c, 0), // x: 6, y: 7, sw: 6, cs: 7, id: 59 + (0x06, 1), // x: 7, y: 7, sw: 7, cs: 7, id: 63 + (0x24, 1), // x: 8, y: 7, sw: 8, cs: 7, id: 67 + (0x69, 1), // x: 9, y: 7, sw: 2, cs:37, id: 71 + (0x07, 0), // x: 1, y: 8, sw: 1, cs: 8, id: 40 + (0x25, 0), // x: 2, y: 8, sw: 2, cs: 8, id: 44 + (0x43, 0), // x: 3, y: 8, sw: 3, cs: 8, id: 48 + (0x61, 0), // x: 4, y: 8, sw: 4, cs: 8, id: 52 + (0x7f, 0), // x: 5, y: 8, sw: 5, cs: 8, id: 56 + (0x9d, 0), // x: 6, y: 8, sw: 6, cs: 8, id: 60 + (0x07, 1), // x: 7, y: 8, sw: 7, cs: 8, id: 64 + (0x25, 1), // x: 8, y: 8, sw: 8, cs: 8, id: 68 + (0x6a, 1), // x: 9, y: 8, sw: 2, cs:38, id: 72 + (0x08, 0), // x: 1, y: 9, sw: 1, cs: 9, id: 73 + (0x26, 0), // x: 2, y: 9, sw: 2, cs: 9, id: 81 + (0x44, 0), // x: 3, y: 9, sw: 3, cs: 9, id: 89 + (0x62, 0), // x: 4, y: 9, sw: 4, cs: 9, id: 97 + (0x80, 0), // x: 5, y: 9, sw: 5, cs: 9, id:105 + (0x9e, 0), // x: 6, y: 9, sw: 6, cs: 9, id:113 + (0x08, 1), // x: 7, y: 9, sw: 7, cs: 9, id:121 + (0x26, 1), // x: 8, y: 9, sw: 8, cs: 9, id:129 + (0x6b, 1), // x: 9, y: 9, sw: 2, cs:39, id:137 + (0x09, 0), // x: 1, y:10, sw: 1, cs:10, id: 74 + (0x27, 0), // x: 2, y:10, sw: 2, cs:10, id: 82 + (0x45, 0), // x: 3, y:10, sw: 3, cs:10, id: 90 + (0x63, 0), // x: 4, y:10, sw: 4, cs:10, id: 98 + (0x81, 0), // x: 5, y:10, sw: 5, cs:10, id:106 + (0x9f, 0), // x: 6, y:10, sw: 6, cs:10, id:114 + (0x09, 1), // x: 7, y:10, sw: 7, cs:10, id:122 + (0x27, 1), // x: 8, y:10, sw: 8, cs:10, id:130 + (0x67, 1), // x: 9, y:10, sw: 2, cs:35, id:138 + (0x0a, 0), // x: 1, y:11, sw: 1, cs:11, id: 75 + (0x28, 0), // x: 2, y:11, sw: 2, cs:11, id: 83 + (0x46, 0), // x: 3, y:11, sw: 3, cs:11, id: 91 + (0x64, 0), // x: 4, y:11, sw: 4, cs:11, id: 99 + (0x82, 0), // x: 5, y:11, sw: 5, cs:11, id:107 + (0xa0, 0), // x: 6, y:11, sw: 6, cs:11, id:115 + (0x0a, 1), // x: 7, y:11, sw: 7, cs:11, id:123 + (0x28, 1), // x: 8, y:11, sw: 8, cs:11, id:131 + (0x71, 1), // x: 9, y:11, sw: 3, cs:36, id:139 + (0x0b, 0), // x: 1, y:12, sw: 1, cs:12, id: 76 + (0x29, 0), // x: 2, y:12, sw: 2, cs:12, id: 84 + (0x47, 0), // x: 3, y:12, sw: 3, cs:12, id: 92 + (0x65, 0), // x: 4, y:12, sw: 4, cs:12, id:100 + (0x83, 0), // x: 5, y:12, sw: 5, cs:12, id:108 + (0xa1, 0), // x: 6, y:12, sw: 6, cs:12, id:116 + (0x0b, 1), // x: 7, y:12, sw: 7, cs:12, id:124 + (0x29, 1), // x: 8, y:12, sw: 8, cs:12, id:132 + (0x72, 1), // x: 9, y:12, sw: 3, cs:37, id:140 + (0x0c, 0), // x: 1, y:13, sw: 1, cs:13, id: 77 + (0x2a, 0), // x: 2, y:13, sw: 2, cs:13, id: 85 + (0x48, 0), // x: 3, y:13, sw: 3, cs:13, id: 93 + (0x66, 0), // x: 4, y:13, sw: 4, cs:13, id:101 + (0x84, 0), // x: 5, y:13, sw: 5, cs:13, id:109 + (0xa2, 0), // x: 6, y:13, sw: 6, cs:13, id:117 + (0x0c, 1), // x: 7, y:13, sw: 7, cs:13, id:125 + (0x2a, 1), // x: 8, y:13, sw: 8, cs:13, id:133 + (0x73, 1), // x: 9, y:13, sw: 3, cs:38, id:141 + (0x0d, 0), // x: 1, y:14, sw: 1, cs:14, id: 78 + (0x2b, 0), // x: 2, y:14, sw: 2, cs:14, id: 86 + (0x49, 0), // x: 3, y:14, sw: 3, cs:14, id: 94 + (0x67, 0), // x: 4, y:14, sw: 4, cs:14, id:102 + (0x85, 0), // x: 5, y:14, sw: 5, cs:14, id:110 + (0xa3, 0), // x: 6, y:14, sw: 6, cs:14, id:118 + (0x0d, 1), // x: 7, y:14, sw: 7, cs:14, id:126 + (0x2b, 1), // x: 8, y:14, sw: 8, cs:14, id:134 + (0x70, 1), // x: 9, y:14, sw: 3, cs:35, id:142 + (0x0e, 0), // x: 1, y:15, sw: 1, cs:15, id: 79 + (0x2c, 0), // x: 2, y:15, sw: 2, cs:15, id: 87 + (0x4a, 0), // x: 3, y:15, sw: 3, cs:15, id: 95 + (0x68, 0), // x: 4, y:15, sw: 4, cs:15, id:103 + (0x86, 0), // x: 5, y:15, sw: 5, cs:15, id:111 + (0xa4, 0), // x: 6, y:15, sw: 6, cs:15, id:119 + (0x0e, 1), // x: 7, y:15, sw: 7, cs:15, id:127 + (0x2c, 1), // x: 8, y:15, sw: 8, cs:15, id:135 + (0x7a, 1), // x: 9, y:15, sw: 4, cs:36, id:143 + (0x0f, 0), // x: 1, y:16, sw: 1, cs:16, id: 80 + (0x2d, 0), // x: 2, y:16, sw: 2, cs:16, id: 88 + (0x4b, 0), // x: 3, y:16, sw: 3, cs:16, id: 96 + (0x69, 0), // x: 4, y:16, sw: 4, cs:16, id:104 + (0x87, 0), // x: 5, y:16, sw: 5, cs:16, id:112 + (0xa5, 0), // x: 6, y:16, sw: 6, cs:16, id:120 + (0x0f, 1), // x: 7, y:16, sw: 7, cs:16, id:128 + (0x2d, 1), // x: 8, y:16, sw: 8, cs:16, id:136 + (0x7b, 1), // x: 9, y:16, sw: 4, cs:37, id:144 + (0x10, 0), // x: 1, y:17, sw: 1, cs:17, id:145 + (0x2e, 0), // x: 2, y:17, sw: 2, cs:17, id:161 + (0x4c, 0), // x: 3, y:17, sw: 3, cs:17, id:177 + (0x6a, 0), // x: 4, y:17, sw: 4, cs:17, id:193 + (0x88, 0), // x: 5, y:17, sw: 5, cs:17, id:209 + (0xa6, 0), // x: 6, y:17, sw: 6, cs:17, id:225 + (0x10, 1), // x: 7, y:17, sw: 7, cs:17, id:241 + (0x2e, 1), // x: 8, y:17, sw: 8, cs:17, id:257 + (0x7c, 1), // x: 9, y:17, sw: 4, cs:38, id:273 + (0x11, 0), // x: 1, y:18, sw: 1, cs:18, id:146 + (0x2f, 0), // x: 2, y:18, sw: 2, cs:18, id:162 + (0x4d, 0), // x: 3, y:18, sw: 3, cs:18, id:178 + (0x6b, 0), // x: 4, y:18, sw: 4, cs:18, id:194 + (0x89, 0), // x: 5, y:18, sw: 5, cs:18, id:210 + (0xa7, 0), // x: 6, y:18, sw: 6, cs:18, id:226 + (0x11, 1), // x: 7, y:18, sw: 7, cs:18, id:242 + (0x2f, 1), // x: 8, y:18, sw: 8, cs:18, id:258 + (0x79, 1), // x: 9, y:18, sw: 4, cs:35, id:274 + (0x12, 0), // x: 1, y:19, sw: 1, cs:19, id:147 + (0x30, 0), // x: 2, y:19, sw: 2, cs:19, id:163 + (0x4e, 0), // x: 3, y:19, sw: 3, cs:19, id:179 + (0x6c, 0), // x: 4, y:19, sw: 4, cs:19, id:195 + (0x8a, 0), // x: 5, y:19, sw: 5, cs:19, id:211 + (0xa8, 0), // x: 6, y:19, sw: 6, cs:19, id:227 + (0x12, 1), // x: 7, y:19, sw: 7, cs:19, id:243 + (0x30, 1), // x: 8, y:19, sw: 8, cs:19, id:259 + (0x83, 1), // x: 9, y:19, sw: 5, cs:36, id:275 + (0x13, 0), // x: 1, y:20, sw: 1, cs:20, id:148 + (0x31, 0), // x: 2, y:20, sw: 2, cs:20, id:164 + (0x4f, 0), // x: 3, y:20, sw: 3, cs:20, id:180 + (0x6d, 0), // x: 4, y:20, sw: 4, cs:20, id:196 + (0x8b, 0), // x: 5, y:20, sw: 5, cs:20, id:212 + (0xa9, 0), // x: 6, y:20, sw: 6, cs:20, id:228 + (0x13, 1), // x: 7, y:20, sw: 7, cs:20, id:244 + (0x31, 1), // x: 8, y:20, sw: 8, cs:20, id:260 + (0x84, 1), // x: 9, y:20, sw: 5, cs:37, id:276 + (0x14, 0), // x: 1, y:21, sw: 1, cs:21, id:149 + (0x32, 0), // x: 2, y:21, sw: 2, cs:21, id:165 + (0x50, 0), // x: 3, y:21, sw: 3, cs:21, id:181 + (0x6e, 0), // x: 4, y:21, sw: 4, cs:21, id:197 + (0x8c, 0), // x: 5, y:21, sw: 5, cs:21, id:213 + (0xaa, 0), // x: 6, y:21, sw: 6, cs:21, id:229 + (0x14, 1), // x: 7, y:21, sw: 7, cs:21, id:245 + (0x32, 1), // x: 8, y:21, sw: 8, cs:21, id:261 + (0x85, 1), // x: 9, y:21, sw: 5, cs:38, id:277 + (0x15, 0), // x: 1, y:22, sw: 1, cs:22, id:150 + (0x33, 0), // x: 2, y:22, sw: 2, cs:22, id:166 + (0x51, 0), // x: 3, y:22, sw: 3, cs:22, id:182 + (0x6f, 0), // x: 4, y:22, sw: 4, cs:22, id:198 + (0x8d, 0), // x: 5, y:22, sw: 5, cs:22, id:214 + (0xab, 0), // x: 6, y:22, sw: 6, cs:22, id:230 + (0x15, 1), // x: 7, y:22, sw: 7, cs:22, id:246 + (0x33, 1), // x: 8, y:22, sw: 8, cs:22, id:262 + (0x82, 1), // x: 9, y:22, sw: 5, cs:35, id:278 + (0x16, 0), // x: 1, y:23, sw: 1, cs:23, id:151 + (0x34, 0), // x: 2, y:23, sw: 2, cs:23, id:167 + (0x52, 0), // x: 3, y:23, sw: 3, cs:23, id:183 + (0x70, 0), // x: 4, y:23, sw: 4, cs:23, id:199 + (0x8e, 0), // x: 5, y:23, sw: 5, cs:23, id:215 + (0xac, 0), // x: 6, y:23, sw: 6, cs:23, id:231 + (0x16, 1), // x: 7, y:23, sw: 7, cs:23, id:247 + (0x34, 1), // x: 8, y:23, sw: 8, cs:23, id:263 + (0x8c, 1), // x: 9, y:23, sw: 6, cs:36, id:279 + (0x17, 0), // x: 1, y:24, sw: 1, cs:24, id:152 + (0x35, 0), // x: 2, y:24, sw: 2, cs:24, id:168 + (0x53, 0), // x: 3, y:24, sw: 3, cs:24, id:184 + (0x71, 0), // x: 4, y:24, sw: 4, cs:24, id:200 + (0x8f, 0), // x: 5, y:24, sw: 5, cs:24, id:216 + (0xad, 0), // x: 6, y:24, sw: 6, cs:24, id:232 + (0x17, 1), // x: 7, y:24, sw: 7, cs:24, id:248 + (0x35, 1), // x: 8, y:24, sw: 8, cs:24, id:264 + (0x8d, 1), // x: 9, y:24, sw: 6, cs:37, id:280 + (0x18, 0), // x: 1, y:25, sw: 1, cs:25, id:153 + (0x36, 0), // x: 2, y:25, sw: 2, cs:25, id:169 + (0x54, 0), // x: 3, y:25, sw: 3, cs:25, id:185 + (0x72, 0), // x: 4, y:25, sw: 4, cs:25, id:201 + (0x90, 0), // x: 5, y:25, sw: 5, cs:25, id:217 + (0xae, 0), // x: 6, y:25, sw: 6, cs:25, id:233 + (0x18, 1), // x: 7, y:25, sw: 7, cs:25, id:249 + (0x36, 1), // x: 8, y:25, sw: 8, cs:25, id:265 + (0x8e, 1), // x: 9, y:25, sw: 6, cs:38, id:281 + (0x19, 0), // x: 1, y:26, sw: 1, cs:26, id:154 + (0x37, 0), // x: 2, y:26, sw: 2, cs:26, id:170 + (0x55, 0), // x: 3, y:26, sw: 3, cs:26, id:186 + (0x73, 0), // x: 4, y:26, sw: 4, cs:26, id:202 + (0x91, 0), // x: 5, y:26, sw: 5, cs:26, id:218 + (0xaf, 0), // x: 6, y:26, sw: 6, cs:26, id:234 + (0x19, 1), // x: 7, y:26, sw: 7, cs:26, id:250 + (0x37, 1), // x: 8, y:26, sw: 8, cs:26, id:266 + (0x8b, 1), // x: 9, y:26, sw: 6, cs:35, id:282 + (0x1a, 0), // x: 1, y:27, sw: 1, cs:27, id:155 + (0x38, 0), // x: 2, y:27, sw: 2, cs:27, id:171 + (0x56, 0), // x: 3, y:27, sw: 3, cs:27, id:187 + (0x74, 0), // x: 4, y:27, sw: 4, cs:27, id:203 + (0x92, 0), // x: 5, y:27, sw: 5, cs:27, id:219 + (0xb0, 0), // x: 6, y:27, sw: 6, cs:27, id:235 + (0x1a, 1), // x: 7, y:27, sw: 7, cs:27, id:251 + (0x38, 1), // x: 8, y:27, sw: 8, cs:27, id:267 + (0x95, 1), // x: 9, y:27, sw: 7, cs:36, id:283 + (0x1b, 0), // x: 1, y:28, sw: 1, cs:28, id:156 + (0x39, 0), // x: 2, y:28, sw: 2, cs:28, id:172 + (0x57, 0), // x: 3, y:28, sw: 3, cs:28, id:188 + (0x75, 0), // x: 4, y:28, sw: 4, cs:28, id:204 + (0x93, 0), // x: 5, y:28, sw: 5, cs:28, id:220 + (0xb1, 0), // x: 6, y:28, sw: 6, cs:28, id:236 + (0x1b, 1), // x: 7, y:28, sw: 7, cs:28, id:252 + (0x39, 1), // x: 8, y:28, sw: 8, cs:28, id:268 + (0x96, 1), // x: 9, y:28, sw: 7, cs:37, id:284 + (0x1c, 0), // x: 1, y:29, sw: 1, cs:29, id:157 + (0x3a, 0), // x: 2, y:29, sw: 2, cs:29, id:173 + (0x58, 0), // x: 3, y:29, sw: 3, cs:29, id:189 + (0x76, 0), // x: 4, y:29, sw: 4, cs:29, id:205 + (0x94, 0), // x: 5, y:29, sw: 5, cs:29, id:221 + (0xb2, 0), // x: 6, y:29, sw: 6, cs:29, id:237 + (0x1c, 1), // x: 7, y:29, sw: 7, cs:29, id:253 + (0x3a, 1), // x: 8, y:29, sw: 8, cs:29, id:269 + (0x97, 1), // x: 9, y:29, sw: 7, cs:38, id:285 + (0x1d, 0), // x: 1, y:30, sw: 1, cs:30, id:158 + (0x3b, 0), // x: 2, y:30, sw: 2, cs:30, id:174 + (0x59, 0), // x: 3, y:30, sw: 3, cs:30, id:190 + (0x77, 0), // x: 4, y:30, sw: 4, cs:30, id:206 + (0x95, 0), // x: 5, y:30, sw: 5, cs:30, id:222 + (0xb3, 0), // x: 6, y:30, sw: 6, cs:30, id:238 + (0x1d, 1), // x: 7, y:30, sw: 7, cs:30, id:254 + (0x3b, 1), // x: 8, y:30, sw: 8, cs:30, id:270 + (0x94, 1), // x: 9, y:30, sw: 7, cs:35, id:286 + (0x5a, 1), // x: 1, y:31, sw: 1, cs:31, id:159 + (0x63, 1), // x: 2, y:31, sw: 2, cs:31, id:175 + (0x6c, 1), // x: 3, y:31, sw: 3, cs:31, id:191 + (0x75, 1), // x: 4, y:31, sw: 4, cs:31, id:207 + (0x7e, 1), // x: 5, y:31, sw: 5, cs:31, id:223 + (0x87, 1), // x: 6, y:31, sw: 6, cs:31, id:239 + (0x90, 1), // x: 7, y:31, sw: 7, cs:31, id:255 + (0x99, 1), // x: 8, y:31, sw: 8, cs:31, id:271 + (0x9e, 1), // x: 9, y:31, sw: 8, cs:36, id:287 + (0x5b, 1), // x: 1, y:32, sw: 1, cs:32, id:160 + (0x64, 1), // x: 2, y:32, sw: 2, cs:32, id:176 + (0x6d, 1), // x: 3, y:32, sw: 3, cs:32, id:192 + (0x76, 1), // x: 4, y:32, sw: 4, cs:32, id:208 + (0x7f, 1), // x: 5, y:32, sw: 5, cs:32, id:224 + (0x88, 1), // x: 6, y:32, sw: 6, cs:32, id:240 + (0x91, 1), // x: 7, y:32, sw: 7, cs:32, id:256 + (0x9a, 1), // x: 8, y:32, sw: 8, cs:32, id:272 + (0x9f, 1), // x: 9, y:32, sw: 8, cs:37, id:288 + (0x5c, 1), // x: 1, y:33, sw: 1, cs:33, id:289 + (0x65, 1), // x: 2, y:33, sw: 2, cs:33, id:290 + (0x6e, 1), // x: 3, y:33, sw: 3, cs:33, id:291 + (0x77, 1), // x: 4, y:33, sw: 4, cs:33, id:292 + (0x80, 1), // x: 5, y:33, sw: 5, cs:33, id:293 + (0x89, 1), // x: 6, y:33, sw: 6, cs:33, id:294 + (0x92, 1), // x: 7, y:33, sw: 7, cs:33, id:295 + (0x9b, 1), // x: 8, y:33, sw: 8, cs:33, id:296 + (0xa0, 1), // x: 9, y:33, sw: 8, cs:38, id:297 + (0x5d, 1), // x: 1, y:34, sw: 1, cs:34, id:298 + (0x66, 1), // x: 2, y:34, sw: 2, cs:34, id:299 + (0x6f, 1), // x: 3, y:34, sw: 3, cs:34, id:300 + (0x78, 1), // x: 4, y:34, sw: 4, cs:34, id:301 + (0x81, 1), // x: 5, y:34, sw: 5, cs:34, id:302 + (0x8a, 1), // x: 6, y:34, sw: 6, cs:34, id:303 + (0x93, 1), // x: 7, y:34, sw: 7, cs:34, id:304 + (0x9c, 1), // x: 8, y:34, sw: 8, cs:34, id:305 + (0x9d, 1), // x: 9, y:34, sw: 8, cs:35, id:306 + ]; + let index: usize = (x as usize) + (y as usize) * 9; + if index < lookup.len() { + lookup[index] + } else { + (0x00, 0) + } +}; + +pub struct LedMatrix { + pub device: IS31FL3743, +} + +impl LedMatrix +where + I2C: Write, + I2C: Read, + I2cError: core::fmt::Debug, +{ + pub fn unwrap(self) -> I2C { + self.device.i2c + } + + // TODO: Maybe make this private and set it once in the constructor + pub fn set_scaling(&mut self, scale: u8) -> Result<(), I2cError> { + self.device.set_scaling(scale) + } + + pub fn set_address(&mut self, address: u8) { + self.device.address = address; + } + + pub fn new(i2c: I2C, calc_pixel: fn(x: u8, y: u8) -> (u8, u8)) -> LedMatrix { + LedMatrix { + device: IS31FL3743 { + i2c, + address: 0b0100000, + width: 9, + height: 34, + calc_pixel, + }, + } + } + + pub fn setup>(&mut self, delay: &mut DEL) -> Result<(), Error> { + self.device.setup(delay)?; + Ok(()) + } + + pub fn fill_brightness(&mut self, brightness: u8) -> Result<(), Error> { + for x in 0..self.device.width { + for y in 0..self.device.height { + self.device.pixel(x, y, brightness)?; + } + } + Ok(()) + } +} From a71713b76596824cf1f805fabd1715f3c4d54d89 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Thu, 26 Oct 2023 16:15:15 +0800 Subject: [PATCH 12/16] keyboard: Use newly published is31fl3743a crate Signed-off-by: Daniel Schaefer --- Cargo.toml | 1 + keyboard/Cargo.toml | 2 +- keyboard/src/main.rs | 2 +- keyboard/src/rgb_matrix.rs | 4 ++-- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 1bba756b..d3999201 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,6 +38,7 @@ heapless = "0.8" usbd-serial = "0.2.2" fugit = "0.3.7" is31fl3741 = { version = "0.4.0", features = ["framework_ledmatrix"] } +is31fl3743a = "0.1.0" # B1 Display st7306 = { git = "https://github.com/FrameworkComputer/st7306-rs", tag = "v0.10.0" } embedded-graphics = "0.8" diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml index 9ed709b2..e15a57f4 100644 --- a/keyboard/Cargo.toml +++ b/keyboard/Cargo.toml @@ -35,7 +35,7 @@ usbd-hid.workspace = true fugit.workspace = true usbd-human-interface-device = "0.3.1" -is31fl3741.workspace = true +is31fl3743a.workspace = true cfg-if = "1.0.0" diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index e4b67611..eff78e86 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -365,7 +365,7 @@ fn main() -> ! { &clocks.peripheral_clock, ); - let mut matrix = LedMatrix::new(i2c, DVT2_CALC_PIXEL); + let mut matrix = LedMatrix::new(i2c, |_, _| 0x00); cfg_if::cfg_if! { if #[cfg(any(feature = "ansi", feature = "macropad"))] { diff --git a/keyboard/src/rgb_matrix.rs b/keyboard/src/rgb_matrix.rs index 3b077022..c750283a 100644 --- a/keyboard/src/rgb_matrix.rs +++ b/keyboard/src/rgb_matrix.rs @@ -6,7 +6,7 @@ use embedded_hal::blocking::delay::DelayMs; use embedded_hal::blocking::i2c::Read; use embedded_hal::blocking::i2c::Write; #[allow(unused_imports)] -use is31fl3741::{Error, IS31FL3743}; +use is31fl3743a::{Error, IS31FL3743}; pub const DVT2_CALC_PIXEL: fn(x: u8, y: u8) -> (u8, u8) = |x: u8, y: u8| -> (u8, u8) { // Generated by led-matrix.py @@ -349,7 +349,7 @@ where self.device.address = address; } - pub fn new(i2c: I2C, calc_pixel: fn(x: u8, y: u8) -> (u8, u8)) -> LedMatrix { + pub fn new(i2c: I2C, calc_pixel: fn(x: u8, y: u8) -> u8) -> LedMatrix { LedMatrix { device: IS31FL3743 { i2c, From a9d0405bb92147bfc08ee6e97737dda08a786ce7 Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Tue, 21 Nov 2023 13:30:35 +0800 Subject: [PATCH 13/16] keyboard: Also blink RGB backlight in suspend Signed-off-by: Daniel Schaefer --- keyboard/src/main.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index eff78e86..2ca6cdbd 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -22,7 +22,7 @@ // - [ ] Persist brightness setting and FN lock through reset // - [ ] Media keys -//use cortex_m::delay::Delay; +use cortex_m::delay::Delay; //use defmt::*; use crate::rgb_matrix::{LedMatrix, DVT2_CALC_PIXEL}; use defmt_rtt as _; @@ -419,6 +419,8 @@ fn main() -> ! { if !usb_suspended { if caps_led.is_set_low().unwrap() { caps_led.set_high().unwrap(); + #[cfg(any(feature = "ansi", feature = "macropad"))] + matrix.device.fill(0xFF); } } @@ -426,9 +428,13 @@ fn main() -> ! { // 500_000us = 500ms = 0.5s if usb_suspended && timer.get_counter().ticks() > capslock_timer + 500_000 { if caps_led.is_set_high().unwrap() { + #[cfg(any(feature = "ansi", feature = "macropad"))] + matrix.device.fill(0x00); caps_led.set_low().unwrap(); } else { caps_led.set_high().unwrap(); + #[cfg(any(feature = "ansi", feature = "macropad"))] + matrix.device.fill(0xFF); } capslock_timer = timer.get_counter().ticks(); } @@ -467,7 +473,7 @@ fn main() -> ! { } cfg_if::cfg_if! { - if #[cfg(any(feature = "numapd", feature = "macropad"))] { + if #[cfg(any(feature = "numpad", feature = "macropad"))] { let one = scanner.measure_key(0, 3); let two = scanner.measure_key(0, 7); let three = scanner.measure_key(1, 4); From 2f557845b4dec3084e1415962c84ff82ea2977ca Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Sun, 4 Feb 2024 18:30:23 +0800 Subject: [PATCH 14/16] keyboard: Update hid to 0.4.5 Signed-off-by: Daniel Schaefer --- .github/workflows/firmware.yml | 6 +- Cargo.lock | 144 ++++++++++++++++++++++++-- fl16-inputmodules/src/keyboard_hal.rs | 4 +- fl16-inputmodules/src/lib.rs | 4 +- keyboard/Cargo.toml | 6 +- keyboard/src/main.rs | 91 ++++++++-------- keyboard/src/rgb_matrix.rs | 11 +- 7 files changed, 198 insertions(+), 68 deletions(-) diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index 20663fd8..e34d6c16 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -37,8 +37,8 @@ jobs: - run: cargo make --cwd c1minimal - run: cargo make --cwd ledmatrix - run: cargo make --cwd qtpy - # Release version - run: cargo make --cwd keyboard + # Release version - run: cargo make --cwd ledmatrix build-release - run: cargo make --cwd ledmatrix build-release-10k - run: cargo make --cwd ledmatrix build-release-evt @@ -99,9 +99,9 @@ jobs: target/thumbv6m-none-eabi/release/c1minimal.uf2 - name: Upload keyboard files - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: - name: c1minimal_fw_${{github.sha}} + name: keyboard_fw_${{github.sha}} path: | target/thumbv6m-none-eabi/release/keyboard.bin target/thumbv6m-none-eabi/release/keyboard.uf2 diff --git a/Cargo.lock b/Cargo.lock index 7923264a..feea6897 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -255,6 +255,18 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "bitvec" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837" +dependencies = [ + "funty", + "radium", + "tap", + "wyz", +] + [[package]] name = "bumpalo" version = "3.19.1" @@ -835,8 +847,18 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28aef0f9aa070bce60767c12ba9cb41efeaf1a2bc6427f87b7d83f11239a16d7" dependencies = [ - "frunk_core", - "frunk_derives", + "frunk_core 0.4.4", + "frunk_derives 0.4.4", +] + +[[package]] +name = "frunk" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6eb8c34bdcab8c1ebc7fee7af3d99913932a9f29acf9017250fb02604cda9507" +dependencies = [ + "frunk_core 0.5.0", + "frunk_derives 0.5.0", ] [[package]] @@ -845,6 +867,12 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "476eeaa382e3462b84da5d6ba3da97b5786823c2d0d3a0d04ef088d073da225c" +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "frunk_derives" version = "0.4.4" @@ -856,13 +884,24 @@ dependencies = [ "syn 2.0.114", ] +[[package]] +name = "frunk_derives" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91a723c961c87aa962bc3a8b6d1534064974c0e05e42306e219d5b0a7409bed" +dependencies = [ + "frunk_proc_macro_helpers", + "quote", + "syn 2.0.114", +] + [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1952b802269f2db12ab7c0bd328d0ae8feaabf19f352a7b0af7bb0c5693abfce" +checksum = "b70229a1347a20d4af9c06116cc452acef34f798668c6b69e97dd5c8a88052bd" dependencies = [ - "frunk_core", + "frunk_core 0.5.0", "proc-macro2", "quote", "syn 2.0.114", @@ -883,6 +922,12 @@ dependencies = [ "gcd", ] +[[package]] +name = "funty" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" + [[package]] name = "futures-core" version = "0.3.31" @@ -1109,6 +1154,16 @@ dependencies = [ "embedded-hal 0.2.7", ] +[[package]] +name = "is31fl3743a" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f57b8f71c0082095db2add777426021e4103bc872b6603b42a46bbb244ca68df" +dependencies = [ + "embedded-graphics-core", + "embedded-hal 1.0.0", +] + [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -1177,22 +1232,24 @@ dependencies = [ [[package]] name = "keyboard" -version = "0.1.7" +version = "0.2.0" dependencies = [ "cfg-if", "cortex-m", "cortex-m-rt", - "defmt", + "defmt 0.3.100", "defmt-rtt", - "embedded-hal", + "embedded-hal 0.2.7", + "embedded-hal 1.0.0", "fl16-inputmodules", "fugit", "heapless", + "is31fl3743a", "rp2040-boot2", "rp2040-hal", "rp2040-panic-usb-boot", "usb-device", - "usbd-hid", + "usbd-human-interface-device", "usbd-serial", ] @@ -1566,6 +1623,33 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "option-block" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11c9704e085eb8d286265140cdb163c4a43d64ed0c479153a0b20411ca22c7e7" + +[[package]] +name = "packed_struct" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36b29691432cc9eff8b282278473b63df73bea49bc3ec5e67f31a3ae9c3ec190" +dependencies = [ + "bitvec", + "packed_struct_codegen", +] + +[[package]] +name = "packed_struct_codegen" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cd6706dfe50d53e0f6aa09e12c034c44faacd23e966ae5a209e8bdb8f179f98" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "parking_lot" version = "0.7.1" @@ -1760,6 +1844,12 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "radium" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" + [[package]] name = "rand" version = "0.6.5" @@ -2013,7 +2103,7 @@ dependencies = [ "embedded-hal-async", "embedded-hal-nb", "embedded-io", - "frunk", + "frunk 0.4.4", "fugit", "itertools 0.10.5", "nb 1.1.0", @@ -2032,8 +2122,10 @@ dependencies = [ [[package]] name = "rp2040-hal-macros" version = "0.1.0" -source = "git+https://github.com/FrameworkComputer/rp-hal?branch=adc-pull-down-up#ef80ceba220f0dc0f50cabeee4ed8fc3c597cf43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86479063e497efe1ae81995ef9071f54fd1c7427e04d6c5b84cde545ff672a5e" dependencies = [ + "cortex-m-rt", "proc-macro2", "quote", "syn 1.0.109", @@ -2302,6 +2394,12 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tap" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" + [[package]] name = "termcolor" version = "1.4.1" @@ -2471,6 +2569,21 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "usbd-human-interface-device" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87193dfb19354bc7930d5d58e4f47792f41eeb472e71e73672609c345188996e" +dependencies = [ + "frunk 0.5.0", + "fugit", + "heapless", + "num_enum 0.7.5", + "option-block", + "packed_struct", + "usb-device", +] + [[package]] name = "usbd-serial" version = "0.2.2" @@ -2930,6 +3043,15 @@ dependencies = [ "smart-leds-trait 0.3.2", ] +[[package]] +name = "wyz" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" +dependencies = [ + "tap", +] + [[package]] name = "zerocopy" version = "0.8.33" diff --git a/fl16-inputmodules/src/keyboard_hal.rs b/fl16-inputmodules/src/keyboard_hal.rs index beeb3ec1..7064bb47 100644 --- a/fl16-inputmodules/src/keyboard_hal.rs +++ b/fl16-inputmodules/src/keyboard_hal.rs @@ -76,7 +76,7 @@ hal::bsp_pins!( name: gpio26, aliases: { /// I2C Function alias for pin [crate::Pins::gpio26]. - FunctionI2C: Gp26I2C1Sda + FunctionI2C, PullUp: Gp26I2C1Sda } }, /// GPIO 27 is connected to I2C SCL of the LED controller @@ -84,7 +84,7 @@ hal::bsp_pins!( name: gpio27, aliases: { /// I2C Function alias for pin [crate::Pins::gpio27]. - FunctionI2C: Gp27I2C1Scl + FunctionI2C, PullUp: Gp27I2C1Scl } }, /// Analog IN from mux diff --git a/fl16-inputmodules/src/lib.rs b/fl16-inputmodules/src/lib.rs index 631cca99..cf03e8c4 100644 --- a/fl16-inputmodules/src/lib.rs +++ b/fl16-inputmodules/src/lib.rs @@ -37,10 +37,10 @@ pub mod lcd_hal; #[cfg(all(feature = "c1minimal", not(feature = "qtpy")))] pub mod minimal_hal; -#[cfg(feature = "qtpy")] -pub mod qtpy_hal; #[cfg(feature = "keyboard")] pub mod keyboard_hal; +#[cfg(feature = "qtpy")] +pub mod qtpy_hal; pub mod control; pub mod serialnum; diff --git a/keyboard/Cargo.toml b/keyboard/Cargo.toml index e15a57f4..eebe594a 100644 --- a/keyboard/Cargo.toml +++ b/keyboard/Cargo.toml @@ -1,7 +1,7 @@ [package] edition = "2021" name = "keyboard" -version = "0.1.7" +version = "0.2.0" [features] default = ["macropad"] @@ -16,6 +16,7 @@ macropad = [] cortex-m.workspace = true cortex-m-rt.workspace = true embedded-hal.workspace = true +embedded-hal-02 = { package = "embedded-hal", version = "0.2.7", features = ["unproven"] } defmt.workspace = true defmt-rtt.workspace = true @@ -31,10 +32,9 @@ rp2040-boot2.workspace = true usb-device.workspace = true heapless.workspace = true usbd-serial.workspace = true -usbd-hid.workspace = true fugit.workspace = true -usbd-human-interface-device = "0.3.1" +usbd-human-interface-device = "0.6.0" is31fl3743a.workspace = true cfg-if = "1.0.0" diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 2ca6cdbd..1552b879 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -26,13 +26,13 @@ use cortex_m::delay::Delay; //use defmt::*; use crate::rgb_matrix::{LedMatrix, DVT2_CALC_PIXEL}; use defmt_rtt as _; -use embedded_hal::adc::OneShot; -use embedded_hal::digital::v2::{InputPin, OutputPin, StatefulOutputPin}; +use embedded_hal::digital::{InputPin, OutputPin, StatefulOutputPin}; +use embedded_hal_02::adc::OneShot; use rp2040_hal::gpio::bank0::Gpio28; -use rp2040_hal::gpio::{self, Input, PullUp}; -use usbd_human_interface_device::device::keyboard::BootKeyboardInterface; +use rp2040_hal::gpio::{self, FunctionSioInput, PullUp}; use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::prelude::UsbHidClassBuilder; +use usbd_human_interface_device::prelude::*; use usbd_human_interface_device::UsbHidError; mod rgb_matrix; @@ -46,7 +46,7 @@ use rp2040_hal::{ Gpio1, Gpio10, Gpio11, Gpio12, Gpio13, Gpio14, Gpio15, Gpio16, Gpio17, Gpio18, Gpio19, Gpio2, Gpio20, Gpio21, Gpio22, Gpio23, Gpio3, Gpio8, Gpio9, }, - Output, Pin, PinState, PushPull, + FunctionSioOutput, Pin, PinState, PullDown, }, Adc, Timer, }; @@ -90,11 +90,11 @@ const MATRIX_ROWS: usize = 8; const ADC_THRESHOLD: usize = 2900; struct Mux { - a: Pin>, - b: Pin>, - c: Pin>, + a: Pin, + b: Pin, + c: Pin, // TODO - // x: Pin>, + // x: Pin, } impl Mux { pub fn select_row(&mut self, row: usize) { @@ -138,28 +138,31 @@ impl Display for Col { } type Kso = ( - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, - Pin>, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, + Pin, ); struct Scanner { kso: Kso, mux: Mux, - adc: (Adc, Pin>), + adc: ( + Adc, + rp2040_hal::adc::AdcPin>, + ), } impl Scanner { fn drive_col(&mut self, col: usize, state: PinState) { @@ -253,7 +256,7 @@ fn main() -> ! { let rosc = rp2040_hal::rosc::RingOscillator::new(pac.ROSC); let _rosc = rosc.initialize(); - let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); + let mut timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks); let pins = bsp::Pins::new( pac.IO_BANK0, @@ -274,7 +277,7 @@ fn main() -> ! { // Set up the USB Communications Class Device driver //let mut serial = SerialPort::new(&usb_bus); let mut keyboard_hid = UsbHidClassBuilder::new() - .add_interface(BootKeyboardInterface::default_config()) + .add_device(usbd_human_interface_device::device::keyboard::BootKeyboardConfig::default()) .build(&usb_bus); #[cfg(feature = "macropad")] @@ -300,14 +303,17 @@ fn main() -> ! { let product = "Rust JIS Keyboard"; let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x32ac, pid)) - .manufacturer("Framework Computer Inc") - .product(product) + .strings(&[usb_device::device::StringDescriptors::new(LangID::EN_US) + .manufacturer("Framework Computer Inc") + .product(product) + .serial_number("testing")]) + .unwrap() .supports_remote_wakeup(true) .device_class(0) .device_sub_class(0) .device_protocol(0) .max_power(MAX_CURRENT) - .serial_number("testing") + .unwrap() .device_release(device_release()) .build(); @@ -350,7 +356,7 @@ fn main() -> ! { let _ = pins.ksi5_reserved.into_floating_input(); let _ = pins.ksi6_reserved.into_floating_input(); - let sleep = pins.sleep.into_floating_input(); + let mut sleep = pins.sleep.into_floating_input(); // Enable LED controller let mut led_enable = pins.sdb.into_push_pull_output(); @@ -358,8 +364,12 @@ fn main() -> ! { let i2c = bsp::hal::I2C::i2c1( pac.I2C1, - pins.gpio26.into_mode::(), - pins.gpio27.into_mode::(), + pins.gpio26 + .into_function::() + .into_pull_type::(), + pins.gpio27 + .into_function::() + .into_pull_type::(), 1000.kHz(), &mut pac.RESETS, &clocks.peripheral_clock, @@ -371,7 +381,7 @@ fn main() -> ! { if #[cfg(any(feature = "ansi", feature = "macropad"))] { matrix.set_address(0b0100000); matrix - .setup(&mut delay) + .setup(&mut timer) .expect("failed to setup RGB controller"); matrix.set_scaling(0xFF).expect("failed to set scaling"); matrix.device.fill(0xFF); @@ -382,20 +392,19 @@ fn main() -> ! { if #[cfg(feature = "ansi")] { matrix.set_address(0b0100011); matrix - .setup(&mut delay) + .setup(&mut timer) .expect("failed to setup RGB controller"); matrix.set_scaling(0xFF).expect("failed to set scaling"); matrix.device.fill(0xFF); } } - let timer = Timer::new(pac.TIMER, &mut pac.RESETS); let mut scan_timer = timer.get_counter().ticks(); let mut capslock_timer = timer.get_counter().ticks(); caps_led.set_high().unwrap(); let adc = Adc::new(pac.ADC, &mut pac.RESETS); - let adc_x = pins.analog_in.into_pull_up_input(); + let adc_x = rp2040_hal::adc::AdcPin::new(pins.analog_in.into_pull_up_input()).unwrap(); let mut scanner = Scanner { kso: ( @@ -502,7 +511,7 @@ fn main() -> ! { } if !usb_suspended { - let _ = keyboard_hid.interface().read_report(); + let _ = keyboard_hid.device().read_report(); // Setup the report for the control channel let keycodes = if let Some(keycode) = keycode { @@ -510,11 +519,11 @@ fn main() -> ! { } else { [Keyboard::NoEventIndicated] }; - match keyboard_hid.interface().write_report(keycodes) { + match keyboard_hid.device().write_report(keycodes) { Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} Err(e) => panic!("Failed to write keyboard report: {:?}", e), } - match keyboard_hid.interface().tick() { + match keyboard_hid.tick() { Err(UsbHidError::WouldBlock) | Ok(_) => {} Err(e) => panic!("Failed to process keyboard tick: {:?}", e), } diff --git a/keyboard/src/rgb_matrix.rs b/keyboard/src/rgb_matrix.rs index c750283a..c65aa0eb 100644 --- a/keyboard/src/rgb_matrix.rs +++ b/keyboard/src/rgb_matrix.rs @@ -2,9 +2,9 @@ #[allow(unused_imports)] use core::convert::TryFrom; #[allow(unused_imports)] -use embedded_hal::blocking::delay::DelayMs; -use embedded_hal::blocking::i2c::Read; -use embedded_hal::blocking::i2c::Write; +use embedded_hal::delay::DelayNs; +use embedded_hal::i2c::I2c; + #[allow(unused_imports)] use is31fl3743a::{Error, IS31FL3743}; @@ -332,8 +332,7 @@ pub struct LedMatrix { impl LedMatrix where - I2C: Write, - I2C: Read, + I2C: I2c, I2cError: core::fmt::Debug, { pub fn unwrap(self) -> I2C { @@ -361,7 +360,7 @@ where } } - pub fn setup>(&mut self, delay: &mut DEL) -> Result<(), Error> { + pub fn setup(&mut self, delay: &mut DEL) -> Result<(), Error> { self.device.setup(delay)?; Ok(()) } From de225eb0006a17084e806472ccc1dc95dc5270bb Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 13 Nov 2026 17:19:01 +0800 Subject: [PATCH 15/16] keyboard: Implement basic keymaps and Fn layers --- keyboard/README.md | 41 ++++- keyboard/generate_keymaps.py | 47 +++++ keyboard/src/keymap.rs | 320 +++++++++++++++++++++++++++++++++++ keyboard/src/layouts.rs | 104 ++++++++++++ keyboard/src/main.rs | 281 +++++++++--------------------- 5 files changed, 592 insertions(+), 201 deletions(-) create mode 100644 keyboard/generate_keymaps.py create mode 100644 keyboard/src/keymap.rs create mode 100644 keyboard/src/layouts.rs diff --git a/keyboard/README.md b/keyboard/README.md index 9beb06c0..0ffb72bb 100644 --- a/keyboard/README.md +++ b/keyboard/README.md @@ -1,4 +1,43 @@ # Keyboard NOT THE OFFICIAL Keyboard firmware -Just experimental reference code for building keyboard firmare in Rust \ No newline at end of file +Just experimental reference code for building keyboard firmare in Rust + +Basic typing is implemented for ANSI, ISO, JIS, numpad and macropad using the +matrix positions and default keymaps in QMK's `keyboards/framework`. +Modifiers and simultaneous held keys use USB boot-keyboard reports (six ordinary +keys plus modifiers). Keys are debounced for 5 ms; the host handles key repeat. +The numpad and macropad send keypad usages, with Num Lock handled by the host. + +On ANSI/ISO, hold Fn for F1–F12. JIS sends F1–F12 without Fn, matching QMK. +Fn+arrows sends Home/Page Up/Page Down/End, Fn+Delete sends Insert, +Fn+P/B sends Pause/Break, and Fn+K sends Scroll Lock. +Fn+Esc toggles Fn lock for the top row until reset. Keys keep the meaning they +had when pressed until released, even if Fn is released first. +Down is now a normal arrow key rather than a bootloader shortcut. + +Media, brightness, airplane mode, calculator, and lighting shortcuts are not +implemented. Print Screen is supported. Existing basic RGB lighting remains. + +Build one variant at a time (`macropad` is the default): + +```sh +cargo build -p keyboard --release --no-default-features --features ansi +``` + +The pure input state machine can be tested without RP2040 hardware: + +```sh +rustc --edition=2021 --test keyboard/src/keymap.rs -o target/keyboard-keymap-tests +./target/keyboard-keymap-tests +``` + +To regenerate the layout tables from a QMK checkout: + +```sh +python keyboard/generate_keymaps.py ../qmk_firmware +cargo fmt -p keyboard +``` + +Hardware validation is still needed for scan timing, resistor thresholds, +simultaneous keys, and suspend/resume on each variant. diff --git a/keyboard/generate_keymaps.py b/keyboard/generate_keymaps.py new file mode 100644 index 00000000..548604e1 --- /dev/null +++ b/keyboard/generate_keymaps.py @@ -0,0 +1,47 @@ +"""Regenerate basic USB keymaps: python keyboard/generate_keymaps.py ../qmk_firmware.""" +import pathlib +import re +import sys + +qmk = pathlib.Path(sys.argv[1]) +codes = (qmk / "quantum/keycodes.h").read_text(encoding="utf-8") +values = {k: int(v, 16) for k, v in re.findall(r"(KC_\w+)\s*=\s*(0x[0-9A-Fa-f]+)", codes)} +aliases = dict(re.findall(r"^\s*(KC_\w+)\s*=\s*(KC_\w+)", codes, re.M)) +aliases.update(dict(re.findall(r"^#define\s+(JP_\w+)\s+(KC_\w+)", (qmk / "quantum/keymap_extras/keymap_japanese.h").read_text(encoding="utf-8"), re.M))) + + +def usage(code): + if code == "MO(_FN)": + return "FN" + while code in aliases: + code = aliases[code] + # Consumer/system controls and vendor actions are intentionally omitted. + value = values.get(code, 0) + return f"0x{value:02x}" if value <= 0x73 or 0x87 <= value <= 0x8B or 0xE0 <= value <= 0xE7 else "0x00" + + +output = ["// Matrix positions and default layouts from QMK keyboards/framework.", + "// Copyright 2022-2023 Framework Computer", "// SPDX-License-Identifier: GPL-2.0-or-later", + "// Generated by keyboard/generate_keymaps.py; values are USB keyboard usages.", + "use super::Keymap;", '#[cfg(any(feature = "ansi", feature = "iso", feature = "jis", test))]', "use super::FN;", ""] +for variant in ("ansi", "iso", "jis", "numpad", "macropad"): + directory = qmk / "keyboards/framework" / variant + header = (directory / f"{variant}.h").read_text(encoding="utf-8").replace("\\\n", "") + params, body = re.search(r"#define LAYOUT\((.*?)\)\s*\{(.*)", header, re.S).groups() + params = [p.strip() for p in params.split(",")] + source = (directory / "keymaps/default/keymap.c").read_text(encoding="utf-8") + layer = "_BASE" if variant in ("ansi", "iso", "jis") else "_NUMLOCK" + keys = re.search(r"\[" + layer + r"\]\s*=\s*LAYOUT\((.*?)\n\s*\)", source, re.S).group(1) + keys = [k.strip() for k in keys.split(",")] + assert len(params) == len(keys), (variant, len(params), len(keys)) + mapping = dict(zip(params, keys)) + output += [f'#[cfg(any(feature = "{variant}", test))]', "#[rustfmt::skip]", f"pub const {variant.upper()}: Keymap = ["] + rows = re.findall(r"\{([^{}]+)\}", body.split("\nenum")[0]) + assert len(rows) == (8 if variant in ("ansi", "iso", "jis") else 4) + for row in rows: + positions = [p.strip() for p in row.split(",") if p.strip()] + mapped = [mapping.get(p, "KC_NO") for p in positions] + output += [" // " + ", ".join(mapped), " [" + ", ".join(usage(k) for k in mapped) + (", 0x00" * (16 - len(mapped))) + "],"] + output += [" [0; 16],"] * (8 - len(rows)) + output += ["];", ""] +pathlib.Path(__file__).with_name("src").joinpath("layouts.rs").write_text("\n".join(output)) diff --git a/keyboard/src/keymap.rs b/keyboard/src/keymap.rs new file mode 100644 index 00000000..867015b2 --- /dev/null +++ b/keyboard/src/keymap.rs @@ -0,0 +1,320 @@ +// Matrix thresholds and Fn layout based on QMK keyboards/framework. +// Copyright 2022-2023 Framework Computer +// SPDX-License-Identifier: GPL-2.0-or-later +//! Basic keyboard usages and momentary Fn. No hardware dependencies so the +//! input state machine can also be tested on the host with rustc --test. +pub const ROWS: usize = 8; +pub const COLS: usize = 16; +pub type Matrix = [[bool; COLS]; ROWS]; +pub type Keymap = [[u8; COLS]; ROWS]; +const FN: u8 = 0xff; +const DEBOUNCE_US: u64 = 5_000; + +#[path = "layouts.rs"] +pub mod layouts; + +pub struct Keys { + raw: Matrix, + stable: Matrix, + changed_at: [[u64; COLS]; ROWS], + // Bind on press: releasing Fn must not change a key that is still held. + bindings: Keymap, + fn_lock: bool, +} + +impl Keys { + pub const fn new() -> Self { + Self { + raw: [[false; COLS]; ROWS], + stable: [[false; COLS]; ROWS], + changed_at: [[0; COLS]; ROWS], + bindings: [[0; COLS]; ROWS], + fn_lock: false, + } + } + + pub fn update(&mut self, matrix: Matrix, now: u64, layout: &Keymap) { + let previous = self.stable; + for row in 0..ROWS { + for col in 0..COLS { + if matrix[row][col] != self.raw[row][col] { + self.raw[row][col] = matrix[row][col]; + self.changed_at[row][col] = now; + } + if now.saturating_sub(self.changed_at[row][col]) >= DEBOUNCE_US { + self.stable[row][col] = self.raw[row][col]; + } + } + } + let fn_down = (0..ROWS).any(|r| (0..COLS).any(|c| self.stable[r][c] && layout[r][c] == FN)); + if fn_down + && (0..ROWS).any(|r| { + (0..COLS).any(|c| self.stable[r][c] && !previous[r][c] && layout[r][c] == 0x29) + }) + { + self.fn_lock = !self.fn_lock; + } + for row in 0..ROWS { + for col in 0..COLS { + if !self.stable[row][col] { + self.bindings[row][col] = 0; + } else if !previous[row][col] { + let base = layout[row][col]; + self.bindings[row][col] = if base == FN || (fn_down && base == 0x29) { + 0 + } else if let Some(index) = function_index(row, col) { + // ANSI/ISO have an omitted media row at rest; JIS has F1-F12. + let jis = layout[3][5] == 0x3a; + if fn_down ^ self.fn_lock ^ jis { + 0x3a + index + } else if jis { + // Only Print Screen uses the keyboard usage page; + // the other media/system actions are unsupported. + if index == 10 { + 0x46 + } else { + 0 + } + } else { + base + } + } else if fn_down { + match base { + 0x4c => 0x49, // Delete -> Insert + 0x50 => 0x4a, // Left -> Home + 0x4f => 0x4d, // Right -> End + 0x52 => 0x4b, // Up -> Page Up + 0x51 => 0x4e, // Down -> Page Down + 0x13 => 0x48, // P -> Pause + 0x0e => 0x47, // K -> Scroll Lock + 0x05 => 0x48, // B -> Break (same HID usage as Pause) + _ => base, + } + } else { + base + }; + } + } + } + } + + pub fn pressed(&self) -> impl Iterator + '_ { + let mut seen = [false; 256]; + self.bindings.iter().flatten().copied().filter(move |&key| { + let duplicate = seen[key as usize]; + seen[key as usize] = true; + key != 0 && !duplicate + }) + } + + pub fn any_pressed(&self) -> bool { + self.stable.iter().flatten().any(|&pressed| pressed) + } +} + +fn function_index(row: usize, col: usize) -> Option { + // Physical function row positions shared by ANSI, ISO and JIS. + const POSITIONS: [(usize, usize); 12] = [ + (3, 5), + (2, 5), + (6, 4), + (3, 4), + (4, 10), + (3, 10), + (2, 10), + (1, 15), + (3, 11), + (4, 8), + (6, 8), + (3, 13), + ]; + POSITIONS + .iter() + .position(|&p| p == (row, col)) + .map(|i| i as u8) +} + +/// QMK's row-dependent thresholds account for the resistor matrix when +/// several keys share a row. Input and thresholds are in millivolts. +pub fn interpret(voltages: &[[u16; COLS]; ROWS]) -> Matrix { + let mut result = [[false; COLS]; ROWS]; + for row in 0..ROWS { + let count = voltages[row].iter().filter(|&&v| v < 2900).count(); + let threshold = match count { + 0 | 1 => 1000, + 2 => 2000, + 3 => 2500, + _ => 2900, + }; + for col in 0..COLS { + result[row][col] = voltages[row][col] < threshold; + } + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + fn settle(keys: &mut Keys, matrix: Matrix, now: u64, layout: &Keymap) { + keys.update(matrix, now, layout); + keys.update(matrix, now + DEBOUNCE_US, layout); + } + + fn output(keys: &Keys) -> Vec { + keys.pressed().collect() + } + + #[test] + fn modifiers_chords_holds_and_release() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[1][12] = true; // Left Ctrl + matrix[1][9] = true; // Left Shift + matrix[7][2] = true; // A + settle(&mut keys, matrix, 0, &layouts::ANSI); + assert_eq!(output(&keys), [0xe1, 0xe0, 0x04]); + keys.update(matrix, 20_000, &layouts::ANSI); + assert_eq!(output(&keys), [0xe1, 0xe0, 0x04]); + settle(&mut keys, [[false; COLS]; ROWS], 30_000, &layouts::ANSI); + assert!(output(&keys).is_empty()); + } + + #[test] + fn bounce_does_not_press_or_release_a_key() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[7][2] = true; + keys.update(matrix, 0, &layouts::ANSI); + assert!(output(&keys).is_empty()); + keys.update([[false; COLS]; ROWS], 2_000, &layouts::ANSI); + settle(&mut keys, matrix, 3_000, &layouts::ANSI); + assert_eq!(output(&keys), [4]); + keys.update([[false; COLS]; ROWS], 9_000, &layouts::ANSI); + keys.update(matrix, 10_000, &layouts::ANSI); + assert_eq!(output(&keys), [4]); + } + + #[test] + fn fn_navigation_and_binding_survive_fn_release() { + for (position, usage) in [ + ((6, 11), 0x4a), + ((1, 13), 0x4b), + ((1, 8), 0x4e), + ((2, 15), 0x4d), + ((0, 1), 0x49), + ((5, 13), 0x48), + ((7, 10), 0x47), + ] { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[2][2] = true; + matrix[position.0][position.1] = true; + settle(&mut keys, matrix, 0, &layouts::ANSI); + assert_eq!(output(&keys), [usage]); + matrix[2][2] = false; + settle(&mut keys, matrix, 10_000, &layouts::ANSI); + assert_eq!(output(&keys), [usage]); + } + } + + #[test] + fn fn_lock_toggles_once_and_only_changes_function_row() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[2][2] = true; + matrix[7][5] = true; // Fn+Esc + settle(&mut keys, matrix, 0, &layouts::ANSI); + keys.update(matrix, 10_000, &layouts::ANSI); + assert!(keys.fn_lock); + assert!(output(&keys).is_empty()); + settle(&mut keys, [[false; COLS]; ROWS], 20_000, &layouts::ANSI); + matrix = [[false; COLS]; ROWS]; + matrix[3][5] = true; // F1 + matrix[1][8] = true; // Down stays Down when locked + settle(&mut keys, matrix, 30_000, &layouts::ANSI); + assert_eq!(output(&keys), [0x51, 0x3a]); + settle(&mut keys, [[false; COLS]; ROWS], 40_000, &layouts::ANSI); + matrix = [[false; COLS]; ROWS]; + matrix[2][2] = true; + matrix[7][5] = true; + settle(&mut keys, matrix, 50_000, &layouts::ANSI); + assert!(!keys.fn_lock); + } + + #[test] + fn pressing_fn_does_not_remap_an_already_held_key() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[1][8] = true; // Down + settle(&mut keys, matrix, 0, &layouts::ANSI); + matrix[2][2] = true; + settle(&mut keys, matrix, 10_000, &layouts::ANSI); + assert_eq!(output(&keys), [0x51]); + } + + #[test] + fn jis_fn_omits_media_but_preserves_print_screen() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[2][2] = true; + matrix[3][5] = true; // Fn+F1 = unsupported Mute + settle(&mut keys, matrix, 0, &layouts::JIS); + assert!(output(&keys).is_empty()); + matrix[6][8] = true; // Fn+F11 = Print Screen + settle(&mut keys, matrix, 10_000, &layouts::JIS); + assert_eq!(output(&keys), [0x46]); + } + + #[test] + fn variant_specific_keys_and_all_function_keys() { + assert_eq!(layouts::ISO[5][11], 0x64); // Non-US backslash + assert_eq!(layouts::ISO[2][8], 0x32); // Non-US hash + assert_eq!(layouts::ANSI[2][8], 0x31); // ANSI backslash + assert_eq!(layouts::JIS[0][15], 0x89); // Yen + assert_eq!(layouts::JIS[4][11], 0x87); // Ro + assert_eq!(layouts::JIS[6][2], 0x8b); // Muhenkan + for layout in [&layouts::ANSI, &layouts::ISO, &layouts::JIS] { + for row in 0..ROWS { + for col in 0..COLS { + if let Some(index) = function_index(row, col) { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[row][col] = true; + matrix[2][2] = layout != &layouts::JIS; + settle(&mut keys, matrix, 0, layout); + assert_eq!(output(&keys), [0x3a + index]); + } + } + } + } + } + + #[test] + fn duplicate_macropad_keys_produce_one_usage() { + let mut keys = Keys::new(); + let mut matrix = [[false; COLS]; ROWS]; + matrix[1][0] = true; + matrix[2][7] = true; + settle(&mut keys, matrix, 0, &layouts::MACROPAD); + assert_eq!(output(&keys), [0x62]); // keypad 0 + assert_eq!(layouts::NUMPAD[1][0], 0x62); + assert_eq!(layouts::NUMPAD[2][0], 0x58); // keypad Enter + } + + #[test] + fn row_thresholds_match_qmk_for_multiple_keys() { + let mut voltages = [[3300; COLS]; ROWS]; + voltages[0][0] = 900; + voltages[1][0] = 1900; + voltages[1][1] = 1900; + voltages[2][0..3].fill(2400); + voltages[3][0..4].fill(2800); + voltages[4][0] = 1100; // rejected under single-key threshold + let matrix = interpret(&voltages); + for (row, expected) in [1, 2, 3, 4, 0].into_iter().enumerate() { + assert_eq!(matrix[row].iter().filter(|&&v| v).count(), expected); + } + } +} diff --git a/keyboard/src/layouts.rs b/keyboard/src/layouts.rs new file mode 100644 index 00000000..c9a3c3ce --- /dev/null +++ b/keyboard/src/layouts.rs @@ -0,0 +1,104 @@ +// Matrix positions and default layouts from QMK keyboards/framework. +// Copyright 2022-2023 Framework Computer +// SPDX-License-Identifier: GPL-2.0-or-later +// Generated by keyboard/generate_keymaps.py; values are USB keyboard usages. +use super::Keymap; +#[cfg(any(feature = "ansi", feature = "iso", feature = "jis", test))] +use super::FN; + +#[cfg(any(feature = "ansi", test))] +#[rustfmt::skip] +pub const ANSI: Keymap = [ + // KC_C, KC_DEL, KC_Q, KC_RALT, KC_NO, KC_X, KC_V, KC_M, KC_DOT, KC_RSFT, KC_COMM, KC_NO, KC_RCTL, KC_SLSH, KC_QUOT, KC_NO + [0x06, 0x4c, 0x14, 0xe6, 0x00, 0x1b, 0x19, 0x10, 0x37, 0xe5, 0x36, 0x00, 0xe4, 0x38, 0x34, 0x00], + // KC_NO, KC_NO, KC_NO, KC_LALT, KC_SPC, KC_Z, KC_B, KC_N, KC_DOWN, KC_LSFT, KC_NO, KC_NO, KC_LCTL, KC_UP, KC_ENT, KC_BRIU + [0x00, 0x00, 0x00, 0xe2, 0x2c, 0x1d, 0x05, 0x11, 0x51, 0xe1, 0x00, 0x00, 0xe0, 0x52, 0x28, 0x00], + // KC_NO, KC_NO, MO(_FN), KC_NO, KC_E, KC_VOLD, KC_G, KC_H, KC_BSLS, KC_NO, KC_BRID, KC_NO, KC_NO, KC_MINS, KC_NO, KC_RGHT + [0x00, 0x00, FN, 0x00, 0x08, 0x00, 0x0a, 0x0b, 0x31, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x00, 0x4f], + // KC_NO, KC_LGUI, KC_TAB, KC_NO, KC_MPRV, KC_MUTE, KC_T, KC_Y, KC_O, KC_NO, KC_MNXT, KC_SCRN, KC_NO, KC_MSEL, KC_NO, KC_NO + [0x00, 0xe3, 0x2b, 0x00, 0x00, 0x00, 0x17, 0x1c, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_NO, KC_NO, KC_GRV, KC_NO, KC_CAPS, KC_S, KC_5, KC_6, KC_AIRP, KC_NO, KC_MPLY, KC_NO, KC_NO, KC_0, KC_EQL, KC_NO + [0x00, 0x00, 0x35, 0x00, 0x39, 0x16, 0x22, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x2e, 0x00], + // KC_NO, KC_NO, KC_1, KC_NO, KC_3, KC_2, KC_4, KC_7, KC_9, KC_NO, KC_8, KC_NO, KC_NO, KC_P, KC_BSPC, KC_NO + [0x00, 0x00, 0x1e, 0x00, 0x20, 0x1f, 0x21, 0x24, 0x26, 0x00, 0x25, 0x00, 0x00, 0x13, 0x2a, 0x00], + // KC_NO, KC_NO, KC_NO, KC_NO, KC_VOLU, KC_W, KC_R, KC_U, KC_PSCR, KC_NO, KC_I, KC_LEFT, KC_NO, KC_LBRC, KC_RBRC, KC_NO + [0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x15, 0x18, 0x46, 0x00, 0x0c, 0x50, 0x00, 0x2f, 0x30, 0x00], + // KC_NO, KC_NO, KC_A, KC_NO, KC_NO, KC_ESC, KC_F, KC_J, KC_L, KC_NO, KC_K, KC_NO, KC_NO, KC_SCLN, KC_D, KC_NO + [0x00, 0x00, 0x04, 0x00, 0x00, 0x29, 0x09, 0x0d, 0x0f, 0x00, 0x0e, 0x00, 0x00, 0x33, 0x07, 0x00], +]; + +#[cfg(any(feature = "iso", test))] +#[rustfmt::skip] +pub const ISO: Keymap = [ + // KC_C, KC_DEL, KC_Q, KC_RALT, KC_NO, KC_X, KC_V, KC_M, KC_DOT, KC_RSFT, KC_COMM, KC_NO, KC_RCTL, KC_SLSH, KC_QUOT, KC_NO + [0x06, 0x4c, 0x14, 0xe6, 0x00, 0x1b, 0x19, 0x10, 0x37, 0xe5, 0x36, 0x00, 0xe4, 0x38, 0x34, 0x00], + // KC_NO, KC_NO, KC_NO, KC_LALT, KC_SPC, KC_Z, KC_B, KC_N, KC_DOWN, KC_LSFT, KC_NO, KC_NO, KC_LCTL, KC_UP, KC_ENT, KC_BRIU + [0x00, 0x00, 0x00, 0xe2, 0x2c, 0x1d, 0x05, 0x11, 0x51, 0xe1, 0x00, 0x00, 0xe0, 0x52, 0x28, 0x00], + // KC_NO, KC_NO, MO(_FN), KC_NO, KC_E, KC_VOLD, KC_G, KC_H, KC_NUHS, KC_NO, KC_BRID, KC_NO, KC_NO, KC_MINS, KC_NO, KC_RGHT + [0x00, 0x00, FN, 0x00, 0x08, 0x00, 0x0a, 0x0b, 0x32, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x00, 0x4f], + // KC_NO, KC_LGUI, KC_TAB, KC_NO, KC_MPRV, KC_MUTE, KC_T, KC_Y, KC_O, KC_NO, KC_MNXT, KC_SCRN, KC_NO, KC_MSEL, KC_NO, KC_NO + [0x00, 0xe3, 0x2b, 0x00, 0x00, 0x00, 0x17, 0x1c, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_NO, KC_NO, KC_GRV, KC_NO, KC_CAPS, KC_S, KC_5, KC_6, KC_AIRP, KC_NO, KC_MPLY, KC_NO, KC_NO, KC_0, KC_EQL, KC_NO + [0x00, 0x00, 0x35, 0x00, 0x39, 0x16, 0x22, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x27, 0x2e, 0x00], + // KC_NO, KC_NO, KC_1, KC_NO, KC_3, KC_2, KC_4, KC_7, KC_9, KC_NO, KC_8, KC_NUBS, KC_NO, KC_P, KC_BSPC, KC_NO + [0x00, 0x00, 0x1e, 0x00, 0x20, 0x1f, 0x21, 0x24, 0x26, 0x00, 0x25, 0x64, 0x00, 0x13, 0x2a, 0x00], + // KC_NO, KC_NO, KC_NO, KC_NO, KC_VOLU, KC_W, KC_R, KC_U, KC_PSCR, KC_NO, KC_I, KC_LEFT, KC_NO, KC_LBRC, KC_RBRC, KC_NO + [0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x15, 0x18, 0x46, 0x00, 0x0c, 0x50, 0x00, 0x2f, 0x30, 0x00], + // KC_NO, KC_NO, KC_A, KC_NO, KC_NO, KC_ESC, KC_F, KC_J, KC_L, KC_NO, KC_K, KC_NO, KC_NO, KC_SCLN, KC_D, KC_NO + [0x00, 0x00, 0x04, 0x00, 0x00, 0x29, 0x09, 0x0d, 0x0f, 0x00, 0x0e, 0x00, 0x00, 0x33, 0x07, 0x00], +]; + +#[cfg(any(feature = "jis", test))] +#[rustfmt::skip] +pub const JIS: Keymap = [ + // KC_C, KC_DEL, KC_Q, KC_RALT, KC_NO, KC_X, KC_V, KC_M, KC_DOT, KC_RSFT, KC_COMM, JP_KANA, KC_RCTL, KC_SLSH, KC_QUOT, JP_YEN + [0x06, 0x4c, 0x14, 0xe6, 0x00, 0x1b, 0x19, 0x10, 0x37, 0xe5, 0x36, 0x88, 0xe4, 0x38, 0x34, 0x89], + // KC_NO, KC_NO, KC_NO, KC_LALT, KC_SPC, KC_Z, KC_B, KC_N, KC_DOWN, KC_LSFT, KC_NO, JP_HENK, KC_LCTL, KC_UP, KC_ENT, KC_F8 + [0x00, 0x00, 0x00, 0xe2, 0x2c, 0x1d, 0x05, 0x11, 0x51, 0xe1, 0x00, 0x8a, 0xe0, 0x52, 0x28, 0x41], + // KC_NO, KC_NO, MO(_FN), KC_NO, KC_E, KC_F2, KC_G, KC_H, KC_RBRC, KC_NO, KC_F7, KC_NO, KC_NO, KC_MINS, KC_NO, KC_RGHT + [0x00, 0x00, FN, 0x00, 0x08, 0x3b, 0x0a, 0x0b, 0x30, 0x00, 0x40, 0x00, 0x00, 0x2d, 0x00, 0x4f], + // KC_NO, KC_LGUI, KC_TAB, KC_NO, KC_F4, KC_F1, KC_T, KC_Y, KC_O, KC_NO, KC_F6, KC_F9, KC_NO, KC_F12, KC_NO, KC_NO + [0x00, 0xe3, 0x2b, 0x00, 0x3d, 0x3a, 0x17, 0x1c, 0x12, 0x00, 0x3f, 0x42, 0x00, 0x45, 0x00, 0x00], + // KC_NO, KC_NO, JP_ZKHK, KC_NO, JP_EISU, KC_S, KC_5, KC_6, KC_F10, KC_NO, KC_F5, JP_BSLS, KC_NO, KC_0, JP_CIRC, KC_NO + [0x00, 0x00, 0x35, 0x00, 0x39, 0x16, 0x22, 0x23, 0x43, 0x00, 0x3e, 0x87, 0x00, 0x27, 0x2e, 0x00], + // KC_NO, KC_NO, KC_1, KC_NO, KC_3, KC_2, KC_4, KC_7, KC_9, KC_NO, KC_8, KC_NO, KC_NO, KC_P, KC_BSPC, KC_NO + [0x00, 0x00, 0x1e, 0x00, 0x20, 0x1f, 0x21, 0x24, 0x26, 0x00, 0x25, 0x00, 0x00, 0x13, 0x2a, 0x00], + // KC_NO, KC_NO, JP_MHEN, KC_NO, KC_F3, KC_W, KC_R, KC_U, KC_F11, KC_NO, KC_I, KC_LEFT, KC_NO, JP_AT, KC_LBRC, KC_NO + [0x00, 0x00, 0x8b, 0x00, 0x3c, 0x1a, 0x15, 0x18, 0x44, 0x00, 0x0c, 0x50, 0x00, 0x2f, 0x2f, 0x00], + // KC_NO, KC_NO, KC_A, KC_NO, KC_NO, KC_ESC, KC_F, KC_J, KC_L, KC_NO, KC_K, KC_NO, KC_NO, KC_SCLN, KC_D, KC_NO + [0x00, 0x00, 0x04, 0x00, 0x00, 0x29, 0x09, 0x0d, 0x0f, 0x00, 0x0e, 0x00, 0x00, 0x33, 0x07, 0x00], +]; + +#[cfg(any(feature = "numpad", test))] +#[rustfmt::skip] +pub const NUMPAD: Keymap = [ + // KC_NUM, KC_P7, KC_P4, KC_P1, KC_PSLS, KC_P8, KC_P5, KC_P2 + [0x53, 0x5f, 0x5c, 0x59, 0x54, 0x60, 0x5d, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_P0, KC_PAST, KC_P9, KC_P6, KC_P3, KC_PDOT, KC_PMNS, KC_PPLS + [0x62, 0x55, 0x61, 0x5e, 0x5b, 0x63, 0x56, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_PENT, KC_ESC, KC_CALC, KC_NO, KC_BSPC, KC_NO, KC_NO, KC_NO + [0x58, 0x29, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_NO, KC_NO, KC_NO, KC_NO, KC_EQL, KC_NO, KC_NO, KC_NO + [0x00, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + [0; 16], + [0; 16], + [0; 16], + [0; 16], +]; + +#[cfg(any(feature = "macropad", test))] +#[rustfmt::skip] +pub const MACROPAD: Keymap = [ + // KC_NUM, KC_P7, KC_P4, KC_P1, KC_PSLS, KC_P8, KC_P5, KC_P2 + [0x53, 0x5f, 0x5c, 0x59, 0x54, 0x60, 0x5d, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_P0, KC_PAST, KC_P9, KC_P6, KC_P3, KC_PDOT, KC_PMNS, KC_PPLS + [0x62, 0x55, 0x61, 0x5e, 0x5b, 0x63, 0x56, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_PENT, KC_ESC, KC_CALC, KC_NO, KC_BSPC, KC_PPLS, KC_PENT, KC_P0 + [0x58, 0x29, 0x00, 0x00, 0x2a, 0x57, 0x58, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + // KC_NO, KC_NO, KC_NO, KC_NO, KC_EQL, KC_NO, KC_NO, KC_NO + [0x00, 0x00, 0x00, 0x00, 0x2e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + [0; 16], + [0; 16], + [0; 16], + [0; 16], +]; diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 1552b879..545cde6b 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -6,25 +6,24 @@ // TODO: // - [x] Basic keyscan -// - [x] Send UP/LEFT/RIGHT/CAPS HID reports, DOWN to go into bootloader +// - [x] Basic HID keymaps for all five variants // - [x] Can go into D2 (tested on Linux) // - [x] Can wake host (remote wakeup) // - [ ] Both serial and HID keyboard as composite device -// - [ ] Key Debouncing +// - [x] Key Debouncing // - [ ] 1-Zone PWM backlight // - [x] RGB backlight (needs new/modified Rust driver) // - [x] Working (all white) // - [ ] Map all LEDs -// - [ ] Separate builds for different keyboard variants +// - [x] Separate builds for different keyboard variants // - [ ] Measure and optimize scan frequency -// - [ ] Implement full key matrix with all keys -// - [ ] Implement second layer for FN (including FN lock) +// - [x] Implement full basic key matrix +// - [x] Implement second layer for FN (including volatile FN lock) // - [ ] Persist brightness setting and FN lock through reset // - [ ] Media keys -use cortex_m::delay::Delay; //use defmt::*; -use crate::rgb_matrix::{LedMatrix, DVT2_CALC_PIXEL}; +use crate::rgb_matrix::LedMatrix; use defmt_rtt as _; use embedded_hal::digital::{InputPin, OutputPin, StatefulOutputPin}; use embedded_hal_02::adc::OneShot; @@ -32,13 +31,33 @@ use rp2040_hal::gpio::bank0::Gpio28; use rp2040_hal::gpio::{self, FunctionSioInput, PullUp}; use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::prelude::UsbHidClassBuilder; -use usbd_human_interface_device::prelude::*; use usbd_human_interface_device::UsbHidError; +mod keymap; mod rgb_matrix; +use keymap::{COLS as MATRIX_COLS, ROWS as MATRIX_ROWS}; -use core::fmt::Display; -use core::fmt::{self, Formatter}; +const SCAN_COLS: usize = if cfg!(any(feature = "numpad", feature = "macropad")) { + 8 +} else { + 16 +}; +const SCAN_ROWS: usize = if cfg!(any(feature = "numpad", feature = "macropad")) { + 4 +} else { + 8 +}; + +#[cfg(feature = "ansi")] +use keymap::layouts::ANSI as LAYOUT; +#[cfg(feature = "iso")] +use keymap::layouts::ISO as LAYOUT; +#[cfg(feature = "jis")] +use keymap::layouts::JIS as LAYOUT; +#[cfg(feature = "macropad")] +use keymap::layouts::MACROPAD as LAYOUT; +#[cfg(feature = "numpad")] +use keymap::layouts::NUMPAD as LAYOUT; use rp2040_hal::{ gpio::{ @@ -64,31 +83,14 @@ use fl16_inputmodules::keyboard_hal as bsp; //use rp_pico as bsp; // use sparkfun_pro_micro_rp2040 as bsp; -use bsp::hal::{ - clocks::{init_clocks_and_plls, Clock}, - pac, - sio::Sio, - usb, - watchdog::Watchdog, -}; +use bsp::hal::{clocks::init_clocks_and_plls, pac, sio::Sio, usb, watchdog::Watchdog}; use fugit::RateExtU32; // USB Device support use usb_device::{class_prelude::*, prelude::*}; -// USB Communications Class Device support -use usbd_serial::{SerialPort, USB_CLASS_CDC}; - -// Used to demonstrate writing formatted strings -use core::fmt::Write; -use heapless::String; - use fl16_inputmodules::serialnum::device_release; -const MATRIX_COLS: usize = 16; -const MATRIX_ROWS: usize = 8; -const ADC_THRESHOLD: usize = 2900; - struct Mux { a: Pin, b: Pin, @@ -110,33 +112,6 @@ impl Mux { } } -#[derive(Debug, PartialEq, Eq, Clone, Default)] -pub struct Col(u8); -#[derive(Debug, PartialEq, Eq, Clone, Default)] -struct Matrix([Col; MATRIX_COLS]); - -impl Matrix { - pub fn set(&mut self, row: usize, col: usize, val: bool) { - let mask = 1 << row; - - self.0[col].0 = if val { - self.0[col].0 | mask - } else { - self.0[col].0 & !mask - }; - } -} - -impl Display for Col { - fn fmt(&self, f: &mut Formatter) -> fmt::Result { - for row in 0..MATRIX_ROWS { - let val = (self.0 & (1 << row)) >> row; - write!(f, "{:b}", val)? - } - Ok(()) - } -} - type Kso = ( Pin, Pin, @@ -186,58 +161,25 @@ impl Scanner { _ => unreachable!(), } } - fn read_voltage(&mut self) -> usize { - let _adc_read: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); - 33000 - } - pub fn measure_key(&mut self, row: usize, col: usize) -> (usize, usize) { - for col in 0..MATRIX_COLS { - self.drive_col(col, PinState::High); - } + /// Scan one column at a time so USB is serviced between columns. + fn scan_column(&mut self, col: usize) -> [u16; MATRIX_ROWS] { self.drive_col(col, PinState::Low); - - self.mux.select_row(row); - // Let column and mux settle a bit - cortex_m::asm::delay(2000); - let adc_read: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); - - self.drive_col(col, PinState::High); - - let voltage_10k = ((adc_read as usize) * 3300) / 4096; - (voltage_10k / 1_000, voltage_10k % 1_000) - } - pub fn scan(&mut self) -> Matrix { - let mut matrix = Matrix::default(); - - // Initialize all cols as high - for col in 0..MATRIX_COLS { - self.drive_col(col, PinState::High); + let mut voltages = [3300; MATRIX_ROWS]; + for (row, voltage) in voltages.iter_mut().enumerate().take(SCAN_ROWS) { + self.mux.select_row(row); + // Retain the settling time used by the original single-key reader. + cortex_m::asm::delay(2000); + let sample: u16 = self.adc.0.read(&mut self.adc.1).unwrap(); + *voltage = ((sample as u32 * 3300) / 4096) as u16; } - - for col in 0..MATRIX_COLS { - self.drive_col(col, PinState::Low); - - for row in 0..MATRIX_ROWS { - self.mux.select_row(row); - - if self.read_voltage() < ADC_THRESHOLD { - matrix.set(row, col, true); - } - } - - self.drive_col(col, PinState::High); - } - - matrix.set(3, 4, true); - matrix.set(0, 4, true); - matrix + self.drive_col(col, PinState::High); + voltages } } #[entry] fn main() -> ! { let mut pac = pac::Peripherals::take().unwrap(); - let core = pac::CorePeripherals::take().unwrap(); let mut watchdog = Watchdog::new(pac.WATCHDOG); let sio = Sio::new(pac.SIO); @@ -399,7 +341,7 @@ fn main() -> ! { } } - let mut scan_timer = timer.get_counter().ticks(); + let mut tick_timer = timer.get_counter().ticks(); let mut capslock_timer = timer.get_counter().ticks(); caps_led.set_high().unwrap(); @@ -419,6 +361,12 @@ fn main() -> ! { adc: (adc, adc_x), }; + for col in 0..MATRIX_COLS { + scanner.drive_col(col, PinState::High); + } + let mut keys = keymap::Keys::new(); + let mut voltages = [[3300; MATRIX_COLS]; MATRIX_ROWS]; + let mut scan_col = 0; let mut usb_initialized; let mut usb_suspended = false; loop { @@ -448,89 +396,50 @@ fn main() -> ! { capslock_timer = timer.get_counter().ticks(); } - let mut keycode: Option = None; - if timer.get_counter().ticks() > scan_timer + 250_000 { - cfg_if::cfg_if! { - if #[cfg(any(feature = "ansi", feature = "iso", feature = "jis"))] { - let left = scanner.measure_key(6, 11); - let up = scanner.measure_key(1, 13); - let down = scanner.measure_key(1, 8); - let right = scanner.measure_key(2, 15); - let caps = scanner.measure_key(4, 4); - - let left_p = left.0 < 2 || (left.0 == 2 && left.1 < 290); - let right_p = right.0 < 2 || (right.0 == 2 && right.1 < 290); - let up_p = up.0 < 2 || (up.0 == 2 && up.1 < 290); - let down_p = down.0 < 2 || (down.0 == 2 && down.1 < 290); - let caps_p = caps.0 < 2 || (caps.0 == 2 && caps.1 < 290); - - if left_p { - keycode = Some(Keyboard::LeftArrow); - } else if right_p { - keycode = Some(Keyboard::RightArrow); - } else if up_p { - keycode = Some(Keyboard::UpArrow); - } else if down_p { - keycode = None; - rp2040_hal::rom_data::reset_to_usb_boot(0, 0); - } else if caps_p { - keycode = Some(Keyboard::CapsLock); - } else { - keycode = None; - } - } - } - - cfg_if::cfg_if! { - if #[cfg(any(feature = "numpad", feature = "macropad"))] { - let one = scanner.measure_key(0, 3); - let two = scanner.measure_key(0, 7); - let three = scanner.measure_key(1, 4); - let four = scanner.measure_key(2, 6); - - let one_p = one.0 < 2 || (one.0 == 2 && one.1 < 290); - let two_p = two.0 < 2 || (two.0 == 2 && two.1 < 290); - let three_p = three.0 < 2 || (three.0 == 2 && three.1 < 290); - let four_p = four.0 < 2 || (four.0 == 2 && four.1 < 290); - - if one_p { - keycode = Some(Keyboard::Keyboard1); - } else if two_p { - keycode = Some(Keyboard::Keyboard2); - } else if three_p { - keycode = Some(Keyboard::Keyboard3); - } else if four_p { - keycode = Some(Keyboard::Keyboard4); - } else { - keycode = None; - } - } - } - - scan_timer = timer.get_counter().ticks(); + let readings = scanner.scan_column(scan_col); + for row in 0..MATRIX_ROWS { + voltages[row][scan_col] = readings[row]; + } + scan_col += 1; + if scan_col == SCAN_COLS { + let pressed = if sleep.is_high().unwrap() { + keymap::interpret(&voltages) + } else { + [[false; MATRIX_COLS]; MATRIX_ROWS] + }; + keys.update(pressed, timer.get_counter().ticks(), &LAYOUT); + scan_col = 0; } if !usb_suspended { let _ = keyboard_hid.device().read_report(); - // Setup the report for the control channel - let keycodes = if let Some(keycode) = keycode { - [keycode] - } else { - [Keyboard::NoEventIndicated] - }; - match keyboard_hid.device().write_report(keycodes) { + // Retry the full held state if the USB endpoint was busy. + match keyboard_hid + .device() + .write_report(keys.pressed().map(Keyboard::from)) + { Err(UsbHidError::WouldBlock) | Err(UsbHidError::Duplicate) | Ok(_) => {} Err(e) => panic!("Failed to write keyboard report: {:?}", e), } - match keyboard_hid.tick() { - Err(UsbHidError::WouldBlock) | Ok(_) => {} - Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } + // The HID idle timer expects a 1 ms tick, independently of scan speed. + let now = timer.get_counter().ticks(); + while now - tick_timer >= 1_000 { + tick_timer += 1_000; + if !usb_suspended { + match keyboard_hid.tick() { + Err(UsbHidError::WouldBlock) | Ok(_) => {} + Err(e) => panic!("Failed to process keyboard tick: {:?}", e), + } } } - // Wake the host. - if keycode.is_some() && usb_suspended && usb_dev.remote_wakeup_enabled() { + if keys.any_pressed() + && sleep.is_high().unwrap() + && usb_suspended + && usb_dev.remote_wakeup_enabled() + { usb_dev.bus().remote_wakeup(); } @@ -559,35 +468,7 @@ fn main() -> ! { let _ = usb_initialized; let _ = usb_suspended; - //let kb = Matrix::default(); - //let kb = scanner.scan(); - keyboard_hid.poll(); - - // let mut buf = [0u8; 64]; - // match serial.read(&mut buf) { - // Err(_e) => { - // // Do nothing - // } - // Ok(0) => { - // // Do nothing - // } - // Ok(_count) => { - // match buf[0] { - // b'r' => rp2040_hal::rom_data::reset_to_usb_boot(0, 0), - // _ => (), - // } - // //let mut text: String<64> = String::new(); - // //write!(&mut text, " 01234567\r\n").unwrap(); - // //let _ = serial.write(text.as_bytes()); - - // //for col in 0..MATRIX_COLS { - // // let mut text: String<64> = String::new(); - // // write!(&mut text, "{:2}: {}\r\n", col, kb.0[col]).unwrap(); - // // let _ = serial.write(text.as_bytes()); - // //} - // } - // } } else { match usb_dev.state() { // No new data From 3d94f101dd1a2c295b79a64112b393f553f37d4b Mon Sep 17 00:00:00 2001 From: Daniel Schaefer Date: Fri, 13 Nov 2026 17:28:00 +0800 Subject: [PATCH 16/16] keyboard: Follow host Caps Lock LED state --- keyboard/src/main.rs | 48 +++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/keyboard/src/main.rs b/keyboard/src/main.rs index 545cde6b..165f42e9 100644 --- a/keyboard/src/main.rs +++ b/keyboard/src/main.rs @@ -25,7 +25,7 @@ //use defmt::*; use crate::rgb_matrix::LedMatrix; use defmt_rtt as _; -use embedded_hal::digital::{InputPin, OutputPin, StatefulOutputPin}; +use embedded_hal::digital::{InputPin, OutputPin}; use embedded_hal_02::adc::OneShot; use rp2040_hal::gpio::bank0::Gpio28; use rp2040_hal::gpio::{self, FunctionSioInput, PullUp}; @@ -342,8 +342,10 @@ fn main() -> ! { } let mut tick_timer = timer.get_counter().ticks(); - let mut capslock_timer = timer.get_counter().ticks(); - caps_led.set_high().unwrap(); + let mut backlight_timer = timer.get_counter().ticks(); + let mut backlight_on = true; + let mut caps_lock = false; + caps_led.set_low().unwrap(); let adc = Adc::new(pac.ADC, &mut pac.RESETS); let adc_x = rp2040_hal::adc::AdcPin::new(pins.analog_in.into_pull_up_input()).unwrap(); @@ -372,28 +374,25 @@ fn main() -> ! { loop { let _ = sleep.is_high(); - // Turn back on when not suspended anymore - if !usb_suspended { - if caps_led.is_set_low().unwrap() { - caps_led.set_high().unwrap(); - #[cfg(any(feature = "ansi", feature = "macropad"))] - matrix.device.fill(0xFF); - } + // Keep the RGB status animation independent of the Caps Lock indicator. + if !usb_suspended && !backlight_on { + #[cfg(any(feature = "ansi", feature = "macropad"))] + let _ = matrix.device.fill(0xFF); + backlight_on = true; } // Blink when in USB Suspend // 500_000us = 500ms = 0.5s - if usb_suspended && timer.get_counter().ticks() > capslock_timer + 500_000 { - if caps_led.is_set_high().unwrap() { + if usb_suspended && timer.get_counter().ticks() > backlight_timer + 500_000 { + if backlight_on { #[cfg(any(feature = "ansi", feature = "macropad"))] - matrix.device.fill(0x00); - caps_led.set_low().unwrap(); + let _ = matrix.device.fill(0x00); } else { - caps_led.set_high().unwrap(); #[cfg(any(feature = "ansi", feature = "macropad"))] - matrix.device.fill(0xFF); + let _ = matrix.device.fill(0xFF); } - capslock_timer = timer.get_counter().ticks(); + backlight_on = !backlight_on; + backlight_timer = timer.get_counter().ticks(); } let readings = scanner.scan_column(scan_col); @@ -412,7 +411,9 @@ fn main() -> ! { } if !usb_suspended { - let _ = keyboard_hid.device().read_report(); + if let Ok(leds) = keyboard_hid.device().read_report() { + caps_lock = leds.caps_lock; + } // Retry the full held state if the USB endpoint was busy. match keyboard_hid @@ -488,5 +489,16 @@ fn main() -> ! { let _ = usb_initialized; let _ = usb_suspended; } + // The host owns lock state, including changes from another keyboard. + // Clear stale state on USB reset, and blank the indicator in suspend. + if matches!( + usb_dev.state(), + UsbDeviceState::Default | UsbDeviceState::Addressed + ) { + caps_lock = false; + } + caps_led + .set_state(PinState::from(caps_lock && !usb_suspended)) + .unwrap(); } }