1#![no_std]
2#![doc = include_str!("../README.md")]
3
4use embedded_hal::digital::{InputPin, OutputPin};
5
6pub type Millis = u64;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ActiveLevel {
13 High,
15 Low,
17}
18
19impl ActiveLevel {
20 #[inline]
21 const fn state_from_high(self, is_high: bool) -> ButtonState {
22 match (self, is_high) {
23 (Self::High, true) | (Self::Low, false) => ButtonState::Pressed,
24 (Self::High, false) | (Self::Low, true) => ButtonState::Released,
25 }
26 }
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ColumnDrive {
32 ActiveLow,
34 ActiveHigh,
36}
37
38impl ColumnDrive {
39 #[inline]
40 const fn level_for(self, active: bool) -> bool {
41 match (self, active) {
42 (Self::ActiveHigh, true) | (Self::ActiveLow, false) => true,
43 (Self::ActiveHigh, false) | (Self::ActiveLow, true) => false,
44 }
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ButtonState {
51 Pressed,
53 Released,
55}
56
57impl ButtonState {
58 #[inline]
60 pub const fn is_pressed(self) -> bool {
61 matches!(self, Self::Pressed)
62 }
63
64 #[inline]
66 pub const fn is_released(self) -> bool {
67 matches!(self, Self::Released)
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct MatrixConfig {
74 pub debounce_ms: Millis,
77 pub row_active_level: ActiveLevel,
79 pub column_drive: ColumnDrive,
81}
82
83impl MatrixConfig {
84 pub const DEFAULT_DEBOUNCE_MS: Millis = 20;
86
87 #[inline]
90 pub const fn active_low() -> Self {
91 Self {
92 debounce_ms: Self::DEFAULT_DEBOUNCE_MS,
93 row_active_level: ActiveLevel::Low,
94 column_drive: ColumnDrive::ActiveLow,
95 }
96 }
97
98 #[inline]
101 pub const fn active_high() -> Self {
102 Self {
103 row_active_level: ActiveLevel::High,
104 column_drive: ColumnDrive::ActiveHigh,
105 ..Self::active_low()
106 }
107 }
108
109 #[inline]
111 pub const fn with_debounce_ms(mut self, debounce_ms: Millis) -> Self {
112 self.debounce_ms = debounce_ms;
113 self
114 }
115
116 #[inline]
118 pub const fn with_row_active_level(mut self, row_active_level: ActiveLevel) -> Self {
119 self.row_active_level = row_active_level;
120 self
121 }
122
123 #[inline]
125 pub const fn with_column_drive(mut self, column_drive: ColumnDrive) -> Self {
126 self.column_drive = column_drive;
127 self
128 }
129}
130
131impl Default for MatrixConfig {
132 #[inline]
133 fn default() -> Self {
134 Self::active_low()
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum ButtonEventKind {
141 Pressed,
143 Released,
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
149pub struct ButtonMatrixEvent<NAME> {
150 pub name: NAME,
152 pub row: usize,
154 pub column: usize,
156 pub kind: ButtonEventKind,
158 pub held_ms: Option<Millis>,
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168pub struct PressedKey<NAME> {
169 pub name: NAME,
171 pub row: usize,
173 pub column: usize,
175 pub held_ms: Millis,
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180struct EventSlot {
181 kind: ButtonEventKind,
182 held_ms: Option<Millis>,
183}
184
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187pub struct ButtonMatrixEvents<NAME, const ROWS: usize, const COLS: usize> {
188 names: [[NAME; COLS]; ROWS],
189 slots: [[Option<EventSlot>; COLS]; ROWS],
190 count: usize,
191}
192
193impl<NAME, const ROWS: usize, const COLS: usize> ButtonMatrixEvents<NAME, ROWS, COLS>
194where
195 NAME: Copy,
196{
197 #[inline]
198 const fn new(names: [[NAME; COLS]; ROWS]) -> Self {
199 Self {
200 names,
201 slots: [[None; COLS]; ROWS],
202 count: 0,
203 }
204 }
205
206 #[inline]
207 fn push(&mut self, row: usize, column: usize, kind: ButtonEventKind, held_ms: Option<Millis>) {
208 if self.slots[row][column].is_none() {
209 self.count += 1;
210 }
211
212 self.slots[row][column] = Some(EventSlot { kind, held_ms });
213 }
214
215 #[inline]
217 pub const fn count(&self) -> usize {
218 self.count
219 }
220
221 #[inline]
223 pub const fn is_empty(&self) -> bool {
224 self.count == 0
225 }
226
227 #[inline]
230 pub fn event_at(&self, row: usize, column: usize) -> Option<ButtonMatrixEvent<NAME>> {
231 if row >= ROWS || column >= COLS {
232 return None;
233 }
234
235 self.slots[row][column].map(|slot| ButtonMatrixEvent {
236 name: self.names[row][column],
237 row,
238 column,
239 kind: slot.kind,
240 held_ms: slot.held_ms,
241 })
242 }
243
244 #[inline]
246 pub const fn iter(&self) -> ButtonMatrixEventIter<'_, NAME, ROWS, COLS> {
247 ButtonMatrixEventIter {
248 events: self,
249 row: 0,
250 column: 0,
251 }
252 }
253}
254
255pub struct ButtonMatrixEventIter<'a, NAME, const ROWS: usize, const COLS: usize> {
257 events: &'a ButtonMatrixEvents<NAME, ROWS, COLS>,
258 row: usize,
259 column: usize,
260}
261
262impl<NAME, const ROWS: usize, const COLS: usize> Iterator
263 for ButtonMatrixEventIter<'_, NAME, ROWS, COLS>
264where
265 NAME: Copy,
266{
267 type Item = ButtonMatrixEvent<NAME>;
268
269 fn next(&mut self) -> Option<Self::Item> {
270 while self.row < ROWS {
271 while self.column < COLS {
272 let row = self.row;
273 let column = self.column;
274 self.column += 1;
275
276 if let Some(event) = self.events.event_at(row, column) {
277 return Some(event);
278 }
279 }
280
281 self.row += 1;
282 self.column = 0;
283 }
284
285 None
286 }
287}
288
289#[derive(Debug, Clone, Copy, PartialEq, Eq)]
290struct KeySlot {
291 raw_state: ButtonState,
292 raw_changed_at: Millis,
293 stable_state: ButtonState,
294 pressed_at: Option<Millis>,
295}
296
297impl KeySlot {
298 #[inline]
299 const fn new() -> Self {
300 Self {
301 raw_state: ButtonState::Released,
302 raw_changed_at: 0,
303 stable_state: ButtonState::Released,
304 pressed_at: None,
305 }
306 }
307}
308
309#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub enum MatrixError<RowError, ColumnError> {
312 Column {
314 column: usize,
316 source: ColumnError,
318 },
319 Row {
321 row: usize,
323 column: usize,
325 source: RowError,
327 },
328}
329
330pub struct ButtonMatrix<ROW, COL, NAME, const ROWS: usize, const COLS: usize> {
336 rows: [ROW; ROWS],
337 columns: [COL; COLS],
338 names: [[NAME; COLS]; ROWS],
339 config: MatrixConfig,
340 keys: [[KeySlot; COLS]; ROWS],
341}
342
343impl<ROW, COL, NAME, const ROWS: usize, const COLS: usize>
344 ButtonMatrix<ROW, COL, NAME, ROWS, COLS>
345{
346 #[inline]
348 pub const fn new(rows: [ROW; ROWS], columns: [COL; COLS], names: [[NAME; COLS]; ROWS]) -> Self {
349 Self::with_config(rows, columns, names, MatrixConfig::active_low())
350 }
351
352 #[inline]
354 pub const fn with_config(
355 rows: [ROW; ROWS],
356 columns: [COL; COLS],
357 names: [[NAME; COLS]; ROWS],
358 config: MatrixConfig,
359 ) -> Self {
360 Self {
361 rows,
362 columns,
363 names,
364 config,
365 keys: [[KeySlot::new(); COLS]; ROWS],
366 }
367 }
368
369 #[inline]
371 pub const fn config(&self) -> MatrixConfig {
372 self.config
373 }
374
375 #[inline]
377 pub fn set_config(&mut self, config: MatrixConfig) {
378 self.config = config;
379 }
380
381 #[inline]
383 pub const fn debounce_ms(&self) -> Millis {
384 self.config.debounce_ms
385 }
386
387 #[inline]
389 pub fn set_debounce_ms(&mut self, debounce_ms: Millis) {
390 self.config.debounce_ms = debounce_ms;
391 }
392
393 #[inline]
395 pub const fn row_active_level(&self) -> ActiveLevel {
396 self.config.row_active_level
397 }
398
399 #[inline]
401 pub fn set_row_active_level(&mut self, row_active_level: ActiveLevel) {
402 self.config.row_active_level = row_active_level;
403 }
404
405 #[inline]
407 pub const fn column_drive(&self) -> ColumnDrive {
408 self.config.column_drive
409 }
410
411 #[inline]
413 pub fn set_column_drive(&mut self, column_drive: ColumnDrive) {
414 self.config.column_drive = column_drive;
415 }
416
417 #[inline]
419 pub fn name(&self, row: usize, column: usize) -> Option<NAME>
420 where
421 NAME: Copy,
422 {
423 if row >= ROWS || column >= COLS {
424 return None;
425 }
426
427 Some(self.names[row][column])
428 }
429
430 #[inline]
432 pub fn state(&self, row: usize, column: usize) -> Option<ButtonState> {
433 if row >= ROWS || column >= COLS {
434 return None;
435 }
436
437 Some(self.keys[row][column].stable_state)
438 }
439
440 #[inline]
442 pub fn is_pressed(&self, row: usize, column: usize) -> bool {
443 self.state(row, column).is_some_and(ButtonState::is_pressed)
444 }
445
446 #[inline]
449 pub fn held_ms(&self, row: usize, column: usize, now_ms: Millis) -> Option<Millis> {
450 if row >= ROWS || column >= COLS {
451 return None;
452 }
453
454 self.keys[row][column]
455 .pressed_at
456 .map(|pressed_at| elapsed(now_ms, pressed_at))
457 }
458
459 #[inline]
461 pub const fn pressed_keys(
462 &self,
463 now_ms: Millis,
464 ) -> PressedKeys<'_, ROW, COL, NAME, ROWS, COLS> {
465 PressedKeys {
466 matrix: self,
467 now_ms,
468 row: 0,
469 column: 0,
470 }
471 }
472
473 #[inline]
475 pub fn rows_mut(&mut self) -> &mut [ROW; ROWS] {
476 &mut self.rows
477 }
478
479 #[inline]
481 pub fn columns_mut(&mut self) -> &mut [COL; COLS] {
482 &mut self.columns
483 }
484
485 #[inline]
487 pub fn into_parts(self) -> ([ROW; ROWS], [COL; COLS], [[NAME; COLS]; ROWS]) {
488 (self.rows, self.columns, self.names)
489 }
490}
491
492impl<ROW, COL, NAME, const ROWS: usize, const COLS: usize> ButtonMatrix<ROW, COL, NAME, ROWS, COLS>
493where
494 ROW: InputPin,
495 COL: OutputPin,
496 NAME: Copy,
497{
498 pub fn scan(
504 &mut self,
505 now_ms: Millis,
506 ) -> Result<ButtonMatrixEvents<NAME, ROWS, COLS>, MatrixError<ROW::Error, COL::Error>> {
507 let mut events = ButtonMatrixEvents::new(self.names);
508
509 self.set_all_columns_inactive()?;
510
511 for column in 0..COLS {
512 self.set_column_active(column, true)?;
513
514 for row in 0..ROWS {
515 let is_high = self.rows[row]
516 .is_high()
517 .map_err(|source| MatrixError::Row {
518 row,
519 column,
520 source,
521 })?;
522 let raw_state = self.config.row_active_level.state_from_high(is_high);
523 self.update_key(row, column, raw_state, now_ms, &mut events);
524 }
525
526 self.set_column_active(column, false)?;
527 }
528
529 Ok(events)
530 }
531
532 fn set_all_columns_inactive(&mut self) -> Result<(), MatrixError<ROW::Error, COL::Error>> {
533 for column in 0..COLS {
534 self.set_column_active(column, false)?;
535 }
536
537 Ok(())
538 }
539
540 fn set_column_active(
541 &mut self,
542 column: usize,
543 active: bool,
544 ) -> Result<(), MatrixError<ROW::Error, COL::Error>> {
545 let level_is_high = self.config.column_drive.level_for(active);
546
547 if level_is_high {
548 self.columns[column]
549 .set_high()
550 .map_err(|source| MatrixError::Column { column, source })
551 } else {
552 self.columns[column]
553 .set_low()
554 .map_err(|source| MatrixError::Column { column, source })
555 }
556 }
557
558 fn update_key(
559 &mut self,
560 row: usize,
561 column: usize,
562 raw_state: ButtonState,
563 now_ms: Millis,
564 events: &mut ButtonMatrixEvents<NAME, ROWS, COLS>,
565 ) {
566 let key = &mut self.keys[row][column];
567
568 if raw_state != key.raw_state {
569 key.raw_state = raw_state;
570 key.raw_changed_at = now_ms;
571 }
572
573 if key.stable_state == key.raw_state
574 || elapsed(now_ms, key.raw_changed_at) < self.config.debounce_ms
575 {
576 return;
577 }
578
579 key.stable_state = key.raw_state;
580
581 match key.stable_state {
582 ButtonState::Pressed => {
583 key.pressed_at = Some(now_ms);
584 events.push(row, column, ButtonEventKind::Pressed, Some(0));
585 }
586 ButtonState::Released => {
587 let held_ms = key.pressed_at.map(|pressed_at| elapsed(now_ms, pressed_at));
588 key.pressed_at = None;
589 events.push(row, column, ButtonEventKind::Released, held_ms);
590 }
591 }
592 }
593}
594
595pub struct PressedKeys<'a, ROW, COL, NAME, const ROWS: usize, const COLS: usize> {
597 matrix: &'a ButtonMatrix<ROW, COL, NAME, ROWS, COLS>,
598 now_ms: Millis,
599 row: usize,
600 column: usize,
601}
602
603impl<ROW, COL, NAME, const ROWS: usize, const COLS: usize> Iterator
604 for PressedKeys<'_, ROW, COL, NAME, ROWS, COLS>
605where
606 NAME: Copy,
607{
608 type Item = PressedKey<NAME>;
609
610 fn next(&mut self) -> Option<Self::Item> {
611 while self.row < ROWS {
612 while self.column < COLS {
613 let row = self.row;
614 let column = self.column;
615 self.column += 1;
616
617 let key = self.matrix.keys[row][column];
618 if key.stable_state.is_pressed() {
619 return Some(PressedKey {
620 name: self.matrix.names[row][column],
621 row,
622 column,
623 held_ms: key
624 .pressed_at
625 .map(|pressed_at| elapsed(self.now_ms, pressed_at))
626 .unwrap_or(0),
627 });
628 }
629 }
630
631 self.row += 1;
632 self.column = 0;
633 }
634
635 None
636 }
637}
638
639#[inline]
640const fn elapsed(now_ms: Millis, earlier_ms: Millis) -> Millis {
641 now_ms.saturating_sub(earlier_ms)
642}
643
644#[cfg(test)]
645extern crate std;
646
647#[cfg(test)]
648mod tests {
649 use std::vec::Vec;
650
651 use embedded_hal_mock::eh1::digital::{
652 Mock as PinMock, State as PinState, Transaction as PinTransaction,
653 };
654
655 use super::*;
656
657 fn config() -> MatrixConfig {
658 MatrixConfig::active_low().with_debounce_ms(10)
659 }
660
661 fn row_pin(states: &[PinState]) -> PinMock {
662 let expectations: Vec<_> = states.iter().copied().map(PinTransaction::get).collect();
663 PinMock::new(&expectations)
664 }
665
666 fn column_pin(scan_count: usize, drive: ColumnDrive) -> PinMock {
667 let inactive = if drive.level_for(false) {
668 PinState::High
669 } else {
670 PinState::Low
671 };
672 let active = if drive.level_for(true) {
673 PinState::High
674 } else {
675 PinState::Low
676 };
677 let mut expectations = Vec::new();
678
679 for _ in 0..scan_count {
680 expectations.push(PinTransaction::set(inactive));
681 expectations.push(PinTransaction::set(active));
682 expectations.push(PinTransaction::set(inactive));
683 }
684
685 PinMock::new(&expectations)
686 }
687
688 fn assert_done<const ROWS: usize, const COLS: usize>(
689 mut rows: [PinMock; ROWS],
690 mut columns: [PinMock; COLS],
691 ) {
692 for row in &mut rows {
693 row.done();
694 }
695
696 for column in &mut columns {
697 column.done();
698 }
699 }
700
701 #[test]
702 fn reports_press_release_and_hold_time() {
703 let rows = [
704 row_pin(&[
705 PinState::High,
706 PinState::High,
707 PinState::Low,
708 PinState::High,
709 PinState::Low,
710 PinState::High,
711 PinState::High,
712 PinState::High,
713 PinState::High,
714 PinState::High,
715 ]),
716 row_pin(&[
717 PinState::High,
718 PinState::High,
719 PinState::High,
720 PinState::High,
721 PinState::High,
722 PinState::High,
723 PinState::High,
724 PinState::High,
725 PinState::High,
726 PinState::High,
727 ]),
728 ];
729 let columns = [
730 column_pin(5, ColumnDrive::ActiveLow),
731 column_pin(5, ColumnDrive::ActiveLow),
732 ];
733 let names = [["A", "B"], ["C", "D"]];
734 let mut matrix = ButtonMatrix::with_config(rows, columns, names, config());
735
736 assert!(matrix.scan(0).unwrap().is_empty());
737 assert!(matrix.scan(5).unwrap().is_empty());
738
739 let events = matrix.scan(15).unwrap();
740 let event = events.event_at(0, 0).unwrap();
741 assert_eq!(event.name, "A");
742 assert_eq!(event.kind, ButtonEventKind::Pressed);
743 assert_eq!(event.held_ms, Some(0));
744 assert!(matrix.is_pressed(0, 0));
745 assert_eq!(matrix.held_ms(0, 0, 25), Some(10));
746
747 assert!(matrix.scan(50).unwrap().is_empty());
748
749 let events = matrix.scan(60).unwrap();
750 let event = events.event_at(0, 0).unwrap();
751 assert_eq!(event.name, "A");
752 assert_eq!(event.kind, ButtonEventKind::Released);
753 assert_eq!(event.held_ms, Some(45));
754 assert_eq!(matrix.state(0, 0), Some(ButtonState::Released));
755
756 let (rows, columns, _) = matrix.into_parts();
757 assert_done(rows, columns);
758 }
759
760 #[test]
761 fn returns_multiple_events_from_one_scan() {
762 let rows = [
763 row_pin(&[
764 PinState::High,
765 PinState::High,
766 PinState::Low,
767 PinState::High,
768 PinState::Low,
769 PinState::High,
770 ]),
771 row_pin(&[
772 PinState::High,
773 PinState::High,
774 PinState::High,
775 PinState::Low,
776 PinState::High,
777 PinState::Low,
778 ]),
779 ];
780 let columns = [
781 column_pin(3, ColumnDrive::ActiveLow),
782 column_pin(3, ColumnDrive::ActiveLow),
783 ];
784 let names = [["A", "B"], ["C", "D"]];
785 let mut matrix = ButtonMatrix::with_config(rows, columns, names, config());
786
787 assert!(matrix.scan(0).unwrap().is_empty());
788 assert!(matrix.scan(10).unwrap().is_empty());
789
790 let events = matrix.scan(20).unwrap();
791 assert_eq!(events.count(), 2);
792
793 let events: Vec<_> = events.iter().collect();
794 assert_eq!(
795 events,
796 [
797 ButtonMatrixEvent {
798 name: "A",
799 row: 0,
800 column: 0,
801 kind: ButtonEventKind::Pressed,
802 held_ms: Some(0),
803 },
804 ButtonMatrixEvent {
805 name: "D",
806 row: 1,
807 column: 1,
808 kind: ButtonEventKind::Pressed,
809 held_ms: Some(0),
810 },
811 ]
812 );
813
814 let pressed: Vec<_> = matrix.pressed_keys(25).collect();
815 assert_eq!(
816 pressed,
817 [
818 PressedKey {
819 name: "A",
820 row: 0,
821 column: 0,
822 held_ms: 5,
823 },
824 PressedKey {
825 name: "D",
826 row: 1,
827 column: 1,
828 held_ms: 5,
829 },
830 ]
831 );
832
833 let (rows, columns, _) = matrix.into_parts();
834 assert_done(rows, columns);
835 }
836
837 #[test]
838 fn supports_enum_key_names() {
839 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
840 enum Key {
841 Up,
842 Down,
843 Left,
844 Right,
845 }
846
847 let rows = [
848 row_pin(&[
849 PinState::High,
850 PinState::High,
851 PinState::High,
852 PinState::Low,
853 PinState::High,
854 PinState::Low,
855 ]),
856 row_pin(&[
857 PinState::High,
858 PinState::High,
859 PinState::High,
860 PinState::High,
861 PinState::High,
862 PinState::High,
863 ]),
864 ];
865 let columns = [
866 column_pin(3, ColumnDrive::ActiveLow),
867 column_pin(3, ColumnDrive::ActiveLow),
868 ];
869 let names = [[Key::Up, Key::Down], [Key::Left, Key::Right]];
870 let mut matrix = ButtonMatrix::with_config(rows, columns, names, config());
871
872 assert_eq!(matrix.name(0, 1), Some(Key::Down));
873 assert!(matrix.scan(0).unwrap().is_empty());
874 assert!(matrix.scan(10).unwrap().is_empty());
875
876 let events = matrix.scan(20).unwrap();
877 let event = events.event_at(0, 1).unwrap();
878 assert_eq!(event.name, Key::Down);
879 assert_eq!(event.kind, ButtonEventKind::Pressed);
880
881 let (rows, columns, _) = matrix.into_parts();
882 assert_done(rows, columns);
883 }
884
885 #[test]
886 fn supports_active_high_matrices() {
887 let rows = [row_pin(&[
888 PinState::Low,
889 PinState::Low,
890 PinState::High,
891 PinState::Low,
892 PinState::High,
893 PinState::Low,
894 ])];
895 let columns = [
896 column_pin(3, ColumnDrive::ActiveHigh),
897 column_pin(3, ColumnDrive::ActiveHigh),
898 ];
899 let names = [["A", "B"]];
900 let config = MatrixConfig::active_high().with_debounce_ms(5);
901 let mut matrix = ButtonMatrix::with_config(rows, columns, names, config);
902
903 assert!(matrix.scan(0).unwrap().is_empty());
904 assert!(matrix.scan(5).unwrap().is_empty());
905
906 let events = matrix.scan(10).unwrap();
907 let event = events.event_at(0, 0).unwrap();
908 assert_eq!(event.name, "A");
909 assert_eq!(event.kind, ButtonEventKind::Pressed);
910
911 let (rows, columns, _) = matrix.into_parts();
912 assert_done(rows, columns);
913 }
914}