Code cleanup

This commit is contained in:
Christoffer Martinsson 2023-07-03 21:27:56 +02:00
parent 8d2d31fa42
commit be65b842fb
4 changed files with 115 additions and 53 deletions

View File

@ -1,3 +1,9 @@
//! Project: CMtec CMDR Keyboard 42
//! Date: 2023-07-01
//! Author: Christoffer Martinsson
//! Email: cm@cmtec.se
//! License: Please refer to LICENSE in root directory
use core::convert::Infallible; use core::convert::Infallible;
use cortex_m::delay::Delay; use cortex_m::delay::Delay;
use embedded_hal::digital::v2::*; use embedded_hal::digital::v2::*;
@ -7,6 +13,7 @@ use embedded_hal::digital::v2::*;
/// # Example /// # Example
/// ``` /// ```
/// let button_matrix: ButtonMatrix<4, 6, 48> = ButtonMatrix::new(row_pins, col_pins, 5); /// 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> { pub struct ButtonMatrix<'a, const R: usize, const C: usize, const N: usize> {
rows: &'a [&'a dyn InputPin<Error = Infallible>; R], rows: &'a [&'a dyn InputPin<Error = Infallible>; R],
cols: &'a mut [&'a mut dyn OutputPin<Error = Infallible>; C], cols: &'a mut [&'a mut dyn OutputPin<Error = Infallible>; C],
@ -62,6 +69,11 @@ impl<'a, const R: usize, const C: usize, const N: usize> ButtonMatrix<'a, R, C,
} }
} }
/// Processes a column of the button matrix.
///
/// # Arguments
///
/// * `col_index` - The index of the column to process.
fn process_column(&mut self, col_index: usize) { fn process_column(&mut self, col_index: usize) {
for row_index in 0..self.rows.len() { for row_index in 0..self.rows.len() {
let button_index: usize = col_index + (row_index * C); let button_index: usize = col_index + (row_index * C);

View File

@ -1,3 +1,9 @@
//! Project: CMtec CMDR Keyboard 42
//! Date: 2023-07-01
//! Author: Christoffer Martinsson
//! Email: cm@cmtec.se
//! License: Please refer to LICENSE in root directory
// Button index map: // Button index map:
// ------------------------------------- ------------------------------------- // ------------------------------------- -------------------------------------
// | 0 | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 10 | 11 | // | 0 | 1 | 2 | 3 | 4 | 5 | | 6 | 7 | 8 | 9 | 10 | 11 |
@ -25,11 +31,15 @@
use crate::NUMBER_OF_KEYS; use crate::NUMBER_OF_KEYS;
use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::page::Keyboard;
// Function (Fn) buttons index (need two buttons) /// Function (Fn) buttons index (need two buttons)
// Button 41 are used both as Fn and RightAlt (AltGr) for better ergonomics. /// Button 41 are used both as Fn and RightAlt (AltGr) for better ergonomics.
// This means that RightAlt is only available on layer 1 keys. /// This means that RightAlt is only available on layer 1 keys.
pub const FN_BUTTONS: [u8; 3] = [40, 43, 44]; pub const FN_BUTTONS: [u8; 3] = [40, 43, 44];
// Button map to HID key (three Function layers)
/// GUI (Windows) buttons [index, layer]
pub const GUI_LOCK_BUTTON: [u8; 2] = [7, 2];
/// Button map to HID key (three Function layers)
pub const MAP: [[Keyboard; NUMBER_OF_KEYS]; 3] = [ pub const MAP: [[Keyboard; NUMBER_OF_KEYS]; 3] = [
[ [
// Function layer 0 // Function layer 0
@ -148,7 +158,7 @@ pub const MAP: [[Keyboard; NUMBER_OF_KEYS]; 3] = [
Keyboard::F15, // 4 Keyboard::F15, // 4
Keyboard::F16, // 5 Keyboard::F16, // 5
Keyboard::Grave, // 6 § Keyboard::Grave, // 6 §
Keyboard::NoEventIndicated, // 7 Keyboard::NoEventIndicated, // 7 GUI lock
Keyboard::LeftGUI, // 8 Keyboard::LeftGUI, // 8
Keyboard::NoEventIndicated, // 9 Keyboard::NoEventIndicated, // 9
Keyboard::CapsLock, // 10 Keyboard::CapsLock, // 10

View File

@ -1,8 +1,8 @@
// Project: CMtec CMDR Keyboard 42 //! Project: CMtec CMDR Keyboard 42
// Date: 2023-07-01 //! Date: 2023-07-01
// Author: Christoffer Martinsson //! Author: Christoffer Martinsson
// Email: cm@cmtec.se //! Email: cm@cmtec.se
// License: Please refer to LICENSE in root directory //! License: Please refer to LICENSE in root directory
#![no_std] #![no_std]
#![no_main] #![no_main]
@ -11,7 +11,6 @@ mod button_matrix;
mod layout; mod layout;
mod status_led; mod status_led;
use crate::status_led::{StatusMode, Ws2812StatusLed};
use button_matrix::ButtonMatrix; use button_matrix::ButtonMatrix;
use core::convert::Infallible; use core::convert::Infallible;
use cortex_m::delay::Delay; use cortex_m::delay::Delay;
@ -23,6 +22,7 @@ use rp2040_hal::{
gpio::{Function, FunctionConfig, PinId, ValidPinMode}, gpio::{Function, FunctionConfig, PinId, ValidPinMode},
pio::StateMachineIndex, pio::StateMachineIndex,
}; };
use status_led::{StatusMode, Ws2812StatusLed};
use usb_device::class_prelude::*; use usb_device::class_prelude::*;
use usb_device::prelude::*; use usb_device::prelude::*;
use usbd_human_interface_device::page::Keyboard; use usbd_human_interface_device::page::Keyboard;
@ -55,8 +55,10 @@ pub struct KeyboardButton {
#[entry] #[entry]
fn main() -> ! { fn main() -> ! {
// Grab our singleton objects
let mut pac = pac::Peripherals::take().unwrap(); let mut pac = pac::Peripherals::take().unwrap();
let core = pac::CorePeripherals::take().unwrap();
// Set up the watchdog driver - needed by the clock setup code
let mut watchdog = Watchdog::new(pac.WATCHDOG); let mut watchdog = Watchdog::new(pac.WATCHDOG);
// Configure clocks and PLLs // Configure clocks and PLLs
@ -72,8 +74,12 @@ fn main() -> ! {
.ok() .ok()
.unwrap(); .unwrap();
// Configure GPIOs let core = pac::CorePeripherals::take().unwrap();
// The single-cycle I/O block controls our GPIO pins
let sio = Sio::new(pac.SIO); let sio = Sio::new(pac.SIO);
// Set the pins to their default state
let pins = Pins::new( let pins = Pins::new(
pac.IO_BANK0, pac.IO_BANK0,
pac.PADS_BANK0, pac.PADS_BANK0,
@ -81,7 +87,7 @@ fn main() -> ! {
&mut pac.RESETS, &mut pac.RESETS,
); );
// Create button matrix // Setting up array with pins connected to button rows
let button_matrix_row_pins: &[&dyn InputPin<Error = Infallible>; KEY_ROWS] = &[ let button_matrix_row_pins: &[&dyn InputPin<Error = Infallible>; KEY_ROWS] = &[
&pins.gp0.into_pull_up_input(), &pins.gp0.into_pull_up_input(),
&pins.gp1.into_pull_up_input(), &pins.gp1.into_pull_up_input(),
@ -89,6 +95,7 @@ fn main() -> ! {
&pins.gp28.into_pull_up_input(), &pins.gp28.into_pull_up_input(),
]; ];
// Setting up array with pins connected to button columns
let button_matrix_col_pins: &mut [&mut dyn OutputPin<Error = Infallible>; KEY_COLS] = &mut [ let button_matrix_col_pins: &mut [&mut dyn OutputPin<Error = Infallible>; KEY_COLS] = &mut [
&mut pins.gp12.into_push_pull_output(), &mut pins.gp12.into_push_pull_output(),
&mut pins.gp13.into_push_pull_output(), &mut pins.gp13.into_push_pull_output(),
@ -104,6 +111,7 @@ fn main() -> ! {
&mut pins.gp11.into_push_pull_output(), &mut pins.gp11.into_push_pull_output(),
]; ];
// Create button matrix object that scans all the PCB buttons
let mut button_matrix: ButtonMatrix<KEY_ROWS, KEY_COLS, NUMBER_OF_KEYS> = let mut button_matrix: ButtonMatrix<KEY_ROWS, KEY_COLS, NUMBER_OF_KEYS> =
ButtonMatrix::new(button_matrix_row_pins, button_matrix_col_pins, 5); ButtonMatrix::new(button_matrix_row_pins, button_matrix_col_pins, 5);
@ -155,7 +163,9 @@ fn main() -> ! {
// Create variables to track caps lock and fn mode // Create variables to track caps lock and fn mode
let mut caps_lock_active: bool = false; let mut caps_lock_active: bool = false;
let mut fn_mode: u8 = 0; let mut fn_mode: u8;
let mut gui_lock_active: bool = false;
let mut gui_lock_trigger_index: u8 = 0;
// Initialize button matrix // Initialize button matrix
button_matrix.init_pins(); button_matrix.init_pins();
@ -175,7 +185,7 @@ fn main() -> ! {
loop { loop {
if status_led_count_down.wait().is_ok() { if status_led_count_down.wait().is_ok() {
update_status_led(&mut status_led, fn_mode, caps_lock_active); update_status_led(&mut status_led, caps_lock_active, gui_lock_active);
} }
if usb_hid_report_count_down.wait().is_ok() { if usb_hid_report_count_down.wait().is_ok() {
@ -184,13 +194,18 @@ fn main() -> ! {
fn_mode = get_fn_mode(pressed_keys); fn_mode = get_fn_mode(pressed_keys);
if caps_lock_active == false { if caps_lock_active == false {
update_status_led(&mut status_led, fn_mode, caps_lock_active); update_status_led(&mut status_led, caps_lock_active, gui_lock_active);
} }
for (index, key) in pressed_keys.iter().enumerate() { for (index, key) in pressed_keys.iter().enumerate() {
buttons[index].pressed = *key; buttons[index].pressed = *key;
} }
let keyboard_report = get_keyboard_report(&mut buttons, fn_mode); let keyboard_report = get_keyboard_report(
&mut buttons,
fn_mode,
&mut gui_lock_active,
&mut gui_lock_trigger_index,
);
match keyboard.device().write_report(keyboard_report) { match keyboard.device().write_report(keyboard_report) {
Err(UsbHidError::WouldBlock) => {} Err(UsbHidError::WouldBlock) => {}
@ -233,22 +248,18 @@ fn main() -> ! {
/// Update status LED colour based on function layer and capslock /// Update status LED colour based on function layer and capslock
/// ///
/// # Arguments /// Normal = green (NORMAL)
/// * `status_led` - Reference to status LED /// GUI lock = blue (GUI LOCK)
/// * `fn_mode` - Current function layer
/// * `caps_lock_active` - Is capslock active
///
/// # Results
///
/// Fn0 = green (OK)
/// Fn1 = blue (ACTIVE1)
/// Fn2 = orange (ACTIVE2)
/// Capslock active = flashing red (WARNING) /// Capslock active = flashing red (WARNING)
/// Error = steady red (ERROR) /// Error = steady red (ERROR)
///
/// # Arguments
/// * `status_led` - Reference to status LED
/// * `caps_lock_active` - Is capslock active
fn update_status_led<P, SM, I>( fn update_status_led<P, SM, I>(
status_led: &mut Ws2812StatusLed<P, SM, I>, status_led: &mut Ws2812StatusLed<P, SM, I>,
fn_mode: u8,
caps_lock_active: bool, caps_lock_active: bool,
gui_lock_active: bool,
) where ) where
P: PIOExt + FunctionConfig, P: PIOExt + FunctionConfig,
I: PinId, I: PinId,
@ -257,13 +268,10 @@ fn update_status_led<P, SM, I>(
{ {
if caps_lock_active { if caps_lock_active {
status_led.update(StatusMode::WARNING); status_led.update(StatusMode::WARNING);
} else if gui_lock_active {
status_led.update(StatusMode::ACTIVITY);
} else { } else {
match fn_mode { status_led.update(StatusMode::NORMAL);
0 => status_led.update(StatusMode::OK),
1 => status_led.update(StatusMode::ACTIVE1),
2 => status_led.update(StatusMode::ACTIVE2),
_ => status_led.update(StatusMode::ERROR),
}
} }
} }
@ -273,10 +281,6 @@ fn update_status_led<P, SM, I>(
/// # Arguments /// # Arguments
/// ///
/// * `pressed_keys` - Array of pressed keys /// * `pressed_keys` - Array of pressed keys
///
/// # Results
///
/// * Fn mode (0, 1 or 2)
fn get_fn_mode(pressed_keys: [bool; NUMBER_OF_KEYS]) -> u8 { fn get_fn_mode(pressed_keys: [bool; NUMBER_OF_KEYS]) -> u8 {
// Check how many Fn keys are pressed // Check how many Fn keys are pressed
let mut active_fn_keys = layout::FN_BUTTONS let mut active_fn_keys = layout::FN_BUTTONS
@ -298,13 +302,13 @@ fn get_fn_mode(pressed_keys: [bool; NUMBER_OF_KEYS]) -> u8 {
/// ///
/// * `matrix_keys` - Array of pressed keys /// * `matrix_keys` - Array of pressed keys
/// * `fn_mode` - Current function layer /// * `fn_mode` - Current function layer
/// /// * `gui_lock` - Is GUI lock active
/// # Results /// * `gui_lock_index` - Index of the key pressed after GUI lock was activated
///
/// * Keyboard report
fn get_keyboard_report( fn get_keyboard_report(
matrix_keys: &mut [KeyboardButton; NUMBER_OF_KEYS], matrix_keys: &mut [KeyboardButton; NUMBER_OF_KEYS],
fn_mode: u8, fn_mode: u8,
gui_lock_active: &mut bool,
gui_lock_trigger_index: &mut u8,
) -> [Keyboard; NUMBER_OF_KEYS] { ) -> [Keyboard; NUMBER_OF_KEYS] {
let mut keyboard_report: [Keyboard; NUMBER_OF_KEYS] = let mut keyboard_report: [Keyboard; NUMBER_OF_KEYS] =
[Keyboard::NoEventIndicated; NUMBER_OF_KEYS]; [Keyboard::NoEventIndicated; NUMBER_OF_KEYS];
@ -315,8 +319,36 @@ fn get_keyboard_report(
key.fn_mode = fn_mode; key.fn_mode = fn_mode;
} }
// Check if GUI lock button is pressed
if key.pressed != key.previous_pressed
&& key.pressed
&& index == layout::GUI_LOCK_BUTTON[0] as usize
&& *gui_lock_active == false
&& fn_mode == layout::GUI_LOCK_BUTTON[1]
{
*gui_lock_active = true;
key.previous_pressed = key.pressed;
continue;
}
key.previous_pressed = key.pressed; key.previous_pressed = key.pressed;
/// Index of GUI key in keyboard report
/// Index 36, 37, 38, 45, 46, 47 are not used by any other keys
const GUI_REPORT_INDEX: usize = 47;
// If GUI lock is active, set LeftGUI key to pressed
// when next button is pressed. Keep LeftGUI pressed
// until next button is released
if *gui_lock_active && key.pressed {
*gui_lock_trigger_index = index as u8;
keyboard_report[GUI_REPORT_INDEX] = Keyboard::LeftGUI;
} else if *gui_lock_trigger_index as usize == index && key.pressed {
keyboard_report[GUI_REPORT_INDEX] = Keyboard::LeftGUI;
} else if *gui_lock_trigger_index as usize == index && key.pressed == false {
*gui_lock_active = false;
}
if key.pressed { if key.pressed {
keyboard_report[index] = layout::MAP[key.fn_mode as usize][index]; keyboard_report[index] = layout::MAP[key.fn_mode as usize][index];
} }

View File

@ -1,3 +1,9 @@
//! Project: CMtec CMDR Keyboard 42
//! Date: 2023-07-01
//! Author: Christoffer Martinsson
//! Email: cm@cmtec.se
//! License: Please refer to LICENSE in root directory
use rp2040_hal::{ use rp2040_hal::{
gpio::{Function, FunctionConfig, Pin, PinId, ValidPinMode}, gpio::{Function, FunctionConfig, Pin, PinId, ValidPinMode},
pio::{PIOExt, StateMachineIndex, UninitStateMachine, PIO}, pio::{PIOExt, StateMachineIndex, UninitStateMachine, PIO},
@ -8,22 +14,24 @@ use ws2812_pio::Ws2812Direct;
/// Status LED modes /// Status LED modes
/// ///
/// * OFF = Syatem offline /// * OFF = Syatem offline
/// * OK = All system Ok /// * NORMAL = All system Ok
/// * ACTIVE1 = System active 1 /// * ACTIVITY = System activity
/// * ACTIVE2 = System active 2 /// * OTHER = Other activity
/// * WARNING = Warning /// * WARNING = Warning
/// * ERROR = Error /// * ERROR = Error
/// * BOOTLOADER = Bootloader active /// * BOOTLOADER = Bootloader active
#[allow(dead_code)]
#[derive(PartialEq, Eq, Copy, Clone)] #[derive(PartialEq, Eq, Copy, Clone)]
pub enum StatusMode { pub enum StatusMode {
OFF = 0, OFF = 0,
OK = 1, NORMAL = 1,
ACTIVE1 = 2, ACTIVITY = 2,
ACTIVE2 = 3, OTHER = 3,
WARNING = 4, WARNING = 4,
ERROR = 5, ERROR = 5,
BOOTLOADER = 6, BOOTLOADER = 6,
} }
#[warn(dead_code)]
/// Status LED driver /// Status LED driver
/// This driver uses the PIO state machine to drive a WS2812 LED /// This driver uses the PIO state machine to drive a WS2812 LED
@ -83,9 +91,9 @@ where
/// Depending on the mode, the LED will be set to a different colour /// Depending on the mode, the LED will be set to a different colour
/// ///
/// * OFF = off /// * OFF = off
/// * OK = green /// * NORMAL = green
/// * ACTIVE1 = blue /// * ACTIVITY = blue
/// * ACTIVE2 = orange /// * OTHER = orange
/// * WARNING = red (flashing) /// * WARNING = red (flashing)
/// * ERROR = red /// * ERROR = red
/// * BOOTLOADER = purple /// * BOOTLOADER = purple