diff --git a/rp2040_42/.cargo/config b/rp2040_42/.cargo/config.toml similarity index 82% rename from rp2040_42/.cargo/config rename to rp2040_42/.cargo/config.toml index ed10a10..e548cb6 100644 --- a/rp2040_42/.cargo/config +++ b/rp2040_42/.cargo/config.toml @@ -1,13 +1,9 @@ # # Cargo Configuration for the https://github.com/rp-rs/rp-hal.git repository. # -# Copyright (c) The RP-RS Developers, 2021 -# # You might want to make a similar file in your own repository if you are # writing programs for Raspberry Silicon microcontrollers. # -# This file is MIT or Apache-2.0 as per the repository README.md file -# [build] # Set the default target to match the Cortex-M0+ in the RP2040 @@ -23,13 +19,12 @@ target = "thumbv6m-none-eabi" # script. This is usually provided by the cortex-m-rt crate, and by default # the version in that crate will include a file called `memory.x` which # describes the particular memory layout for your specific chip. -# * inline-threshold=5 makes the compiler more aggressive and inlining functions # * no-vectorize-loops turns off the loop vectorizer (seeing as the M0+ doesn't # have SIMD) rustflags = [ "-C", "link-arg=--nmagic", "-C", "link-arg=-Tlink.x", - "-C", "inline-threshold=5", + "-C", "link-arg=-Tdefmt.x", "-C", "no-vectorize-loops", ] @@ -39,4 +34,4 @@ runner = "elf2uf2-rs -d" # This runner will find a supported SWD debug probe and flash your RP2040 over # SWD: -# runner = "probe-run --chip RP2040" +# runner = "probe-rs run --chip RP2040" diff --git a/rp2040_42/Cargo.toml b/rp2040_42/Cargo.toml index 22abcb5..12d9413 100644 --- a/rp2040_42/Cargo.toml +++ b/rp2040_42/Cargo.toml @@ -1,54 +1,60 @@ [package] -name = "rp2040" -version = "0.1.0" -edition = "2021" +name = "cmdr-keyboard-42" +version = "0.2.0" +edition = "2024" [dependencies] +# rp2040_hal dependencies copied from v0.11 cortex-m = "0.7.2" -waveshare-rp2040-zero = "0.6.0" -rp2040-boot2 = { version = "0.2.0", optional = true } -rp2040-hal = { version = "0.8.0" } -cortex-m-rt = { version = "0.7", optional = true } -panic-halt= "0.2.0" -embedded-hal ="0.2.5" -fugit = "0.3.5" -nb = "1.0.0" -smart-leds = "0.3.0" -smart-leds-trait = "0.2.1" -ws2812-pio = "0.6.0" -usbd-human-interface-device = "0.4.2" -usb-device = "0.2" -packed_struct = { version = "0.10", default-features = false } +cortex-m-rt = "0.7" +cortex-m-rtic = "1.1.4" +critical-section = {version = "1.2.0"} +defmt = "0.3" +defmt-rtt = "0.4.0" +dht-sensor = "0.2.1" +embedded-alloc = "0.5.1" +embedded-hal = "1.0.0" +embedded-hal-async = "1.0.0" +embedded-hal-bus = {version = "0.2.0", features = ["defmt-03"]} +embedded-io = "0.6.1" +embedded_hal_0_2 = {package = "embedded-hal", version = "0.2.5", features = ["unproven"]} +fugit = "0.3.6" +futures = {version = "0.3.30", default-features = false, features = ["async-await"]} +hd44780-driver = "0.4.0" +nb = "1.0" +panic-halt = "0.2.0" +panic-probe = {version = "0.3.1", features = ["print-defmt"]} pio = "0.2.0" +pio-proc = "0.2.0" +portable-atomic = {version = "1.7.0", features = ["critical-section"]} +rp2040-boot2 = "0.3.0" +rp2040-hal = {version = "0.11.0", features = ["binary-info", "critical-section-impl", "rt", "defmt"]} +static_cell = "2.1.0" -[features] -# This is the set of features we enable by default -default = ["boot2", "rt", "critical-section-impl", "rom-func-cache"] +# USB hid dependencies +usbd-human-interface-device = {version = "0.5.1"} +usb-device = "0.3" +packed_struct = { version = "0.10", default-features = false } +heapless = "0.8" -# critical section that is safe for multicore use -critical-section-impl = ["rp2040-hal/critical-section-impl"] +# ws2812-pio dependencies +ws2812-pio = "0.9.0" +smart-leds = "0.4.0" -# 2nd stage bootloaders for rp2040 -boot2 = ["rp2040-boot2"] +[lints.clippy] +too_long_first_doc_paragraph = "allow" -# Minimal startup / runtime for Cortex-M microcontrollers -rt = ["cortex-m-rt","rp2040-hal/rt"] - -# This enables a fix for USB errata 5: USB device fails to exit RESET state on busy USB bus. -# Only required for RP2040 B0 and RP2040 B1, but it doesn't hurt to enable it -rp2040-e5 = ["rp2040-hal/rp2040-e5"] - -# Memoize(cache) ROM function pointers on first use to improve performance -rom-func-cache = ["rp2040-hal/rom-func-cache"] - -# Disable automatic mapping of language features (like floating point math) to ROM functions -disable-intrinsics = ["rp2040-hal/disable-intrinsics"] - -# This enables ROM functions for f64 math that were not present in the earliest RP2040s -rom-v2-intrinsics = ["rp2040-hal/rom-v2-intrinsics"] +[profile.release] +codegen-units = 1 +debug = 0 +debug-assertions = false +incremental = false +lto = 'fat' +opt-level = 3 +overflow-checks = false [[bin]] -name = "rp2040" +name = "cmdr-keyboard-42" test = false bench = false diff --git a/rp2040_42/src/button_matrix.rs b/rp2040_42/src/button_matrix.rs index 2c7e0da..355f605 100644 --- a/rp2040_42/src/button_matrix.rs +++ b/rp2040_42/src/button_matrix.rs @@ -1,12 +1,12 @@ //! Project: CMtec CMDR Keyboard 42 -//! Date: 2023-07-01 +//! Date: 2025-03-09 //! Author: Christoffer Martinsson //! Email: cm@cmtec.se //! License: Please refer to LICENSE in root directory use core::convert::Infallible; use cortex_m::delay::Delay; -use embedded_hal::digital::v2::*; +use embedded_hal::digital::{InputPin, OutputPin}; /// Button matrix driver /// @@ -15,7 +15,7 @@ use embedded_hal::digital::v2::*; /// let button_matrix: ButtonMatrix<4, 6, 48> = ButtonMatrix::new(row_pins, col_pins, 5); /// ``` pub struct ButtonMatrix<'a, const R: usize, const C: usize, const N: usize> { - rows: &'a [&'a dyn InputPin; R], + rows: &'a mut [&'a mut dyn InputPin; R], cols: &'a mut [&'a mut dyn OutputPin; C], pressed: [bool; N], debounce: u8, @@ -31,7 +31,7 @@ impl<'a, const R: usize, const C: usize, const N: usize> ButtonMatrix<'a, R, C, /// * `cols` - An array of references to the column pins. /// * `debounce` - The debounce time in number of scans. pub fn new( - rows: &'a [&'a dyn InputPin; R], + rows: &'a mut [&'a mut dyn InputPin; R], cols: &'a mut [&'a mut dyn OutputPin; C], debounce: u8, ) -> Self { @@ -62,10 +62,10 @@ impl<'a, const R: usize, const C: usize, const N: usize> ButtonMatrix<'a, R, C, pub fn scan_matrix(&mut self, delay: &mut Delay) { for col_index in 0..self.cols.len() { self.cols[col_index].set_low().unwrap(); - delay.delay_us(10); + delay.delay_us(1); self.process_column(col_index); self.cols[col_index].set_high().unwrap(); - delay.delay_us(10); + delay.delay_us(1); } } diff --git a/rp2040_42/src/main.rs b/rp2040_42/src/main.rs index 2dc2d7e..71da6c5 100644 --- a/rp2040_42/src/main.rs +++ b/rp2040_42/src/main.rs @@ -14,31 +14,33 @@ mod status_led; use button_matrix::ButtonMatrix; use core::convert::Infallible; use cortex_m::delay::Delay; -use embedded_hal::digital::v2::*; -use embedded_hal::timer::CountDown; +use embedded_hal::digital::{InputPin, OutputPin}; +use embedded_hal_0_2::timer::CountDown; use fugit::ExtU32; use panic_halt as _; use rp2040_hal::{ - gpio::{Function, FunctionConfig, PinId, ValidPinMode}, - pio::StateMachineIndex, + Sio, + clocks::{Clock, init_clocks_and_plls}, + gpio::{AnyPin, Pins}, + pac, + pio::{PIOExt, StateMachineIndex}, + timer::Timer, + watchdog::Watchdog, }; use status_led::{StatusMode, Ws2812StatusLed}; use usb_device::class_prelude::*; use usb_device::prelude::*; use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::prelude::*; -use waveshare_rp2040_zero::entry; -use waveshare_rp2040_zero::{ - hal::{ - clocks::{init_clocks_and_plls, Clock}, - pac, - pio::PIOExt, - timer::Timer, - watchdog::Watchdog, - Sio, - }, - Pins, XOSC_CRYSTAL_FREQ, -}; + +// 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. +#[unsafe(link_section = ".boot2")] +#[unsafe(no_mangle)] +#[used] +pub static BOOT2_FIRMWARE: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080; + +const XTAL_FREQ_HZ: u32 = 12_000_000u32; // Public constants pub const KEY_ROWS: usize = 4; @@ -53,7 +55,7 @@ pub struct KeyboardButton { pub fn_mode: u8, } -#[entry] +#[rp2040_hal::entry] fn main() -> ! { // Grab our singleton objects let mut pac = pac::Peripherals::take().unwrap(); @@ -63,7 +65,7 @@ fn main() -> ! { // Configure clocks and PLLs let clocks = init_clocks_and_plls( - XOSC_CRYSTAL_FREQ, + XTAL_FREQ_HZ, pac.XOSC, pac.CLOCKS, pac.PLL_SYS, @@ -88,68 +90,50 @@ fn main() -> ! { ); // Setting up array with pins connected to button rows - let button_matrix_row_pins: &[&dyn InputPin; KEY_ROWS] = &[ - &pins.gp0.into_pull_up_input(), - &pins.gp1.into_pull_up_input(), - &pins.gp29.into_pull_up_input(), - &pins.gp28.into_pull_up_input(), + let button_matrix_row_pins: &mut [&mut dyn InputPin; KEY_ROWS] = &mut [ + &mut pins.gpio0.into_pull_up_input(), + &mut pins.gpio1.into_pull_up_input(), + &mut pins.gpio29.into_pull_up_input(), + &mut pins.gpio28.into_pull_up_input(), ]; // Setting up array with pins connected to button columns let button_matrix_col_pins: &mut [&mut dyn OutputPin; KEY_COLS] = &mut [ - &mut pins.gp12.into_push_pull_output(), - &mut pins.gp13.into_push_pull_output(), - &mut pins.gp14.into_push_pull_output(), - &mut pins.gp15.into_push_pull_output(), - &mut pins.gp26.into_push_pull_output(), - &mut pins.gp27.into_push_pull_output(), - &mut pins.gp7.into_push_pull_output(), - &mut pins.gp8.into_push_pull_output(), - &mut pins.gp6.into_push_pull_output(), - &mut pins.gp9.into_push_pull_output(), - &mut pins.gp10.into_push_pull_output(), - &mut pins.gp11.into_push_pull_output(), + &mut pins.gpio12.into_push_pull_output(), + &mut pins.gpio13.into_push_pull_output(), + &mut pins.gpio14.into_push_pull_output(), + &mut pins.gpio15.into_push_pull_output(), + &mut pins.gpio26.into_push_pull_output(), + &mut pins.gpio27.into_push_pull_output(), + &mut pins.gpio7.into_push_pull_output(), + &mut pins.gpio8.into_push_pull_output(), + &mut pins.gpio6.into_push_pull_output(), + &mut pins.gpio9.into_push_pull_output(), + &mut pins.gpio10.into_push_pull_output(), + &mut pins.gpio11.into_push_pull_output(), ]; // Create button matrix object that scans all the PCB buttons let mut button_matrix: ButtonMatrix = ButtonMatrix::new(button_matrix_row_pins, button_matrix_col_pins, 5); - // Configure USB - let usb_bus = UsbBusAllocator::new(waveshare_rp2040_zero::hal::usb::UsbBus::new( - pac.USBCTRL_REGS, - pac.USBCTRL_DPRAM, - clocks.usb_clock, - true, - &mut pac.RESETS, - )); - - let mut keyboard = UsbHidClassBuilder::new() - .add_device( - usbd_human_interface_device::device::keyboard::NKROBootKeyboardConfig::default(), - ) - .build(&usb_bus); - - let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x1209, 0x0001)) - .manufacturer("CMtec") - .product("CMDR keyboard") - .serial_number("0001") - .build(); - // Create status LED let (mut pio, sm0, _, _, _) = pac.PIO0.split(&mut pac.RESETS); let mut status_led = Ws2812StatusLed::new( - pins.neopixel.into_mode(), + pins.gpio16.into_function(), &mut pio, sm0, clocks.peripheral_clock.freq(), ); + // Set red color to statusled indicating error if not reaching assumed state (USB connect) + status_led.update(StatusMode::Error); + // Create keyboard button array let mut buttons: [KeyboardButton; NUMBER_OF_KEYS] = [KeyboardButton::default(); NUMBER_OF_KEYS]; // Create timers/delays - let timer = Timer::new(pac.TIMER, &mut pac.RESETS); + let timer = Timer::new(pac.TIMER, &mut pac.RESETS, &clocks); let mut delay = Delay::new(core.SYST, clocks.system_clock.freq().to_Hz()); let mut usb_hid_report_count_down = timer.count_down(); @@ -161,9 +145,6 @@ fn main() -> ! { let mut status_led_count_down = timer.count_down(); status_led_count_down.start(250.millis()); - // let mut start_count_down = timer.count_down(); - // start_count_down.start(5000.millis()); - // Create variables to track caps lock and fn mode let mut caps_lock_active: bool = false; let mut fn_mode: u8; @@ -187,24 +168,39 @@ fn main() -> ! { rp2040_hal::rom_data::reset_to_usb_boot(gpio_activity_pin_mask, disable_interface_mask); } + // Configure USB + let usb_bus = UsbBusAllocator::new(rp2040_hal::usb::UsbBus::new( + pac.USBCTRL_REGS, + pac.USBCTRL_DPRAM, + clocks.usb_clock, + true, + &mut pac.RESETS, + )); + + let mut keyboard = UsbHidClassBuilder::new() + .add_device( + usbd_human_interface_device::device::keyboard::NKROBootKeyboardConfig::default(), + ) + .build(&usb_bus); + + let mut usb_dev = UsbDeviceBuilder::new(&usb_bus, UsbVidPid(0x1209, 0x0001)) + .strings(&[StringDescriptors::default() + .manufacturer("CMtec") + .product("CMDR Keyboard 42") + .serial_number("0001")]) + .unwrap() + .build(); + loop { if status_led_count_down.wait().is_ok() { update_status_led(&mut status_led, &caps_lock_active, &sticky_state, &started); } - // if start_count_down.wait().is_ok() && !started { - // started = true; - // } - if usb_hid_report_count_down.wait().is_ok() { let pressed_keys = button_matrix.buttons_pressed(); fn_mode = get_fn_mode(pressed_keys); - // if !caps_lock_active && sticky_state != 2 { - // update_status_led(&mut status_led, &caps_lock_active, &sticky_state, &started); - // } - for (index, key) in pressed_keys.iter().enumerate() { buttons[index].pressed = *key; } @@ -268,9 +264,8 @@ fn update_status_led( sticky_state: &u8, started: &bool, ) where - P: PIOExt + FunctionConfig, - I: PinId, - Function

: ValidPinMode, + I: AnyPin, + P: PIOExt, SM: StateMachineIndex, { if *caps_lock_active { diff --git a/rp2040_42/src/status_led.rs b/rp2040_42/src/status_led.rs index 8d95e59..e910990 100644 --- a/rp2040_42/src/status_led.rs +++ b/rp2040_42/src/status_led.rs @@ -1,11 +1,11 @@ //! Project: CMtec CMDR Keyboard 42 -//! Date: 2023-07-01 +//! Date: 2025-03-09 //! Author: Christoffer Martinsson //! Email: cm@cmtec.se //! License: Please refer to LICENSE in root directory use rp2040_hal::{ - gpio::{Function, FunctionConfig, Pin, PinId, ValidPinMode}, + gpio::AnyPin, pio::{PIOExt, StateMachineIndex, UninitStateMachine, PIO}, }; use smart_leds::{SmartLedsWrite, RGB8}; @@ -25,17 +25,16 @@ use ws2812_pio::Ws2812Direct; pub enum StatusMode { Off = 0, Normal = 1, - Activity = 2, - ActivityFlash = 3, - Other = 4, - OtherFlash = 5, - Warning = 6, - Error = 7, - Bootloader = 8, + NormalFlash = 2, + Activity = 3, + ActivityFlash = 4, + Other = 5, + OtherFlash = 6, + Warning = 7, + Error = 8, + Bootloader = 9, } #[warn(dead_code)] - -/// Status LED driver /// This driver uses the PIO state machine to drive a WS2812 LED /// /// # Example @@ -50,20 +49,19 @@ pub enum StatusMode { /// ``` pub struct Ws2812StatusLed where - I: PinId, - P: PIOExt + FunctionConfig, - Function

: ValidPinMode, + I: AnyPin, + P: PIOExt, SM: StateMachineIndex, { ws2812_direct: Ws2812Direct, state: bool, + mode: StatusMode, } impl Ws2812StatusLed where - I: PinId, - P: PIOExt + FunctionConfig, - Function

: ValidPinMode, + I: AnyPin, + P: PIOExt, SM: StateMachineIndex, { /// Creates a new instance of this driver. @@ -75,7 +73,7 @@ where /// * `sm` - PIO state machine /// * `clock_freq` - PIO clock frequency pub fn new( - pin: Pin>, + pin: I, pio: &mut PIO

, sm: UninitStateMachine<(P, SM)>, clock_freq: fugit::HertzU32, @@ -83,28 +81,40 @@ where // prepare the PIO program let ws2812_direct = Ws2812Direct::new(pin, pio, sm, clock_freq); let state = false; + let mode = StatusMode::Off; Self { ws2812_direct, state, + mode, } } + /// Get current status mode + #[allow(dead_code)] + pub fn get_mode(&self) -> StatusMode { + self.mode + } + #[warn(dead_code)] /// Update status LED /// Depending on the mode, the LED will be set to a different colour /// /// * OFF = off /// * NORMAL = green + /// * NORMALFLASH = green (flashing) /// * ACTIVITY = blue + /// * ACTIVITYFLASH = blue (flashing) /// * OTHER = orange + /// * OTHERFLASH = orange (flashing) /// * WARNING = red (flashing) /// * ERROR = red /// * BOOTLOADER = purple /// /// Make sure to call this function regularly to keep the LED flashing pub fn update(&mut self, mode: StatusMode) { - let colors: [RGB8; 9] = [ + let colors: [RGB8; 10] = [ (0, 0, 0).into(), // Off (10, 7, 0).into(), // Green + (10, 7, 0).into(), // Green (10, 4, 10).into(), // Blue (10, 4, 10).into(), // Blue (5, 10, 0).into(), // Orange @@ -114,18 +124,31 @@ where (0, 10, 10).into(), // Purple ]; - if (mode == StatusMode::ActivityFlash + if mode == StatusMode::Warning + || mode == StatusMode::NormalFlash + || mode == StatusMode::ActivityFlash || mode == StatusMode::OtherFlash - || mode == StatusMode::Warning) + || mode != self.mode + { + self.mode = mode; + } else { + return; + } + + if (mode == StatusMode::Warning + || mode == StatusMode::NormalFlash + || mode == StatusMode::ActivityFlash + || mode == StatusMode::OtherFlash) && !self.state { self.ws2812_direct .write([colors[mode as usize]].iter().copied()) .unwrap(); self.state = true; - } else if mode == StatusMode::ActivityFlash + } else if mode == StatusMode::Warning + || mode == StatusMode::NormalFlash + || mode == StatusMode::ActivityFlash || mode == StatusMode::OtherFlash - || mode == StatusMode::Warning || mode == StatusMode::Off { self.ws2812_direct