7 #include <util/delay.h>
12 #include "usb_keyboard.h"
13 #include "matrix_skel.h"
16 #if (MATRIX_COLS > 16)
17 # error "MATRIX_COLS must not exceed 16"
19 #if (MATRIX_ROWS > 255)
20 # error "MATRIX_ROWS must not exceed 255"
24 static bool _matrix_is_modified = false;
26 // matrix state buffer(1:on, 0:off)
27 #if (MATRIX_COLS <= 8)
28 static uint8_t *matrix;
29 static uint8_t _matrix0[MATRIX_ROWS];
31 static uint16_t *matrix;
32 static uint16_t _matrix0[MATRIX_ROWS];
35 #ifdef MATRIX_HAS_GHOST
36 static bool matrix_has_ghost_in_row(uint8_t row);
38 static void _register_key(uint8_t key);
42 uint8_t matrix_rows(void)
48 uint8_t matrix_cols(void)
53 void matrix_init(void)
57 // initialize matrix state: all keys off
58 for (uint8_t i=0; i < MATRIX_ROWS; i++) _matrix0[i] = 0x00;
64 debug_keyboard = true;
66 print("debug enabled.\n");
70 uint8_t matrix_scan(void)
75 static uint8_t prev_led = 0;
76 if (prev_led != usb_keyboard_leds) {
77 adb_host_kbd_led(~usb_keyboard_leds);
78 prev_led = usb_keyboard_leds;
81 _matrix_is_modified = false;
82 codes = adb_host_kbd_recv();
86 if (codes == 0) { // no keys
88 } else if (key0 == 0xFF && key1 != 0xFF) { // error
91 _matrix_is_modified = true;
93 if (key1 != 0xFF) // key1 is 0xFF when no second key.
97 if (debug_matrix && matrix_is_modified()) {
98 print("adb_host_kbd_recv: "); phex16(codes); print("\n");
103 bool matrix_is_modified(void)
105 return _matrix_is_modified;
109 bool matrix_has_ghost(void)
111 #ifdef MATRIX_HAS_GHOST
112 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
113 if (matrix_has_ghost_in_row(i))
121 bool matrix_is_on(uint8_t row, uint8_t col)
123 return (matrix[row] & (1<<col));
127 #if (MATRIX_COLS <= 8)
128 uint8_t matrix_get_row(uint8_t row)
130 uint16_t matrix_get_row(uint8_t row)
136 void matrix_print(void)
138 #if (MATRIX_COLS <= 8)
139 print("\nr/c 01234567\n");
141 print("\nr/c 0123456789ABCDEF\n");
143 for (uint8_t row = 0; row < matrix_rows(); row++) {
144 phex(row); print(": ");
145 #if (MATRIX_COLS <= 8)
146 pbin_reverse(matrix_get_row(row));
148 pbin_reverse16(matrix_get_row(row));
150 #ifdef MATRIX_HAS_GHOST
151 if (matrix_has_ghost_in_row(row)) {
159 uint8_t matrix_key_count(void)
162 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
163 #if (MATRIX_COLS <= 8)
164 count += bitpop(matrix[i]);
166 count += bitpop16(matrix[i]);
172 #ifdef MATRIX_HAS_GHOST
174 static bool matrix_has_ghost_in_row(uint8_t row)
176 // no ghost exists in case less than 2 keys on
177 if (((matrix[row] - 1) & matrix[row]) == 0)
180 // ghost exists in case same state as other row
181 for (uint8_t i=0; i < MATRIX_ROWS; i++) {
182 if (i != row && (matrix[i] & matrix[row]) == matrix[row])
190 static void _register_key(uint8_t key)
196 matrix[row] &= ~(1<<col);
198 matrix[row] |= (1<<col);