-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathkeyscan.rs
166 lines (148 loc) · 4.17 KB
/
keyscan.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use std::error::Error;
use std::thread;
use std::time::Duration;
use rppal::gpio::Gpio;
use rppal::gpio::Level;
use static_assertions::const_assert;
// BCM pin numbering
const ROWS: [u8; 8] = [13, 12, 16, 17, 20, 22, 23, 24];
const COLS: [u8; 3] = [25, 26, 27];
const ROW_PULL_DOWN_TIME_US: u64 = 10;
pub fn init_io() -> Result<(), Box<dyn Error>> {
let gpio = Gpio::new()?;
for col in &COLS {
let mut pin = gpio.get(*col)?.into_input_pullup();
pin.set_reset_on_drop(false);
}
for row in &ROWS {
let mut pin = gpio.get(*row)?.into_output();
pin.set_high();
pin.set_reset_on_drop(false);
}
Ok(())
}
fn get_bit_at(input: u32, n: u8) -> bool {
if n < 32 {
input & (1 << n) != 0
} else {
false
}
}
fn set_bit_at(output: &mut u32, n: u8) {
if n < 32 {
*output |= 1 << n;
}
}
fn clear_bit_at(output: &mut u32, n: u8) {
if n < 32 {
*output &= !(1 << n);
}
}
pub fn scan() -> Result<u32, Box<dyn Error>> {
const_assert!(ROWS.len() + COLS.len() <= 32);
let gpio = Gpio::new()?;
let mut key_idx = 0;
// a bit if set if the corresponding key is pressed
let mut keymap: u32 = 0;
for row in &ROWS {
let mut row_pin = gpio.get(*row)?.into_output();
row_pin.set_low();
thread::sleep(Duration::from_micros(ROW_PULL_DOWN_TIME_US));
for col in &COLS {
let col_pin = gpio.get(*col)?;
let is_pressed = col_pin.read() == Level::Low;
if get_bit_at(keymap, key_idx) != is_pressed {
if is_pressed {
set_bit_at(&mut keymap, key_idx);
} else {
clear_bit_at(&mut keymap, key_idx);
}
}
key_idx += 1;
}
row_pin.set_high();
}
Ok(keymap)
}
#[allow(dead_code)]
pub fn debug_print(keys: u32) {
println!("");
print!(" ");
for _col in &COLS {
print!("==");
}
println!("");
print!(" ");
for (i, _col) in COLS.iter().enumerate() {
print!("{} ", i);
}
println!("");
print!(" ");
for _col in &COLS {
print!("==");
}
println!("");
for (ir, _) in ROWS.iter().enumerate() {
for (ic, _) in COLS.iter().enumerate() {
if ic == 0 {
print!("{}: ", ir);
}
let key = get_bit_at(keys, (ir * COLS.len() + ic) as u8);
print!("{} ", if key { "x" } else { "o" });
}
println!("");
}
}
#[cfg(test)]
mod tests {
// Import names from outer (for mod tests) scope.
use super::*;
use std::thread;
use std::time::Duration;
#[test]
fn init() -> Result<(), Box<dyn Error>> {
init_io().expect("Failed to initialize scan GPIO");
Ok(())
}
#[test]
fn read() -> Result<(), Box<dyn Error>> {
init_io().expect("Failed to initialize scan GPIO");
let _keys = scan()?;
Ok(())
}
/* This test is ignored by default because it requires user interaction.
In order to pass, all keys must be pressed at least once.
Run as
cargo test all_keys -- --ignored --nocapture
*/
#[test]
#[ignore]
fn all_keys() -> Result<(), Box<dyn Error>> {
const NUM_KEYS: u32 = 22;
println!("Press all the keys at least once, in any order...");
init_io().expect("Failed to initialize scan GPIO");
let mut detected_keys: u32 = 0;
let mut last_keys: u32 = 0;
for _ in 0..5000 {
let keys = scan()?;
thread::sleep(Duration::from_millis(50));
detected_keys |= keys;
if last_keys != keys {
println!(
"{:02}/{}: detected_keys: {:x} keys: {:x} ({}) ",
detected_keys.count_ones(),
NUM_KEYS,
detected_keys,
keys,
keys
);
last_keys = keys;
debug_print(detected_keys);
}
if detected_keys.count_ones() == NUM_KEYS {
return Ok(());
}
}
Err("Not all keys were detected")?
}
}