7 #include <util/delay.h>
13 #if (MATRIX_COLS > 16)
14 # error "MATRIX_COLS must not exceed 16"
16 #if (MATRIX_ROWS > 255)
17 # error "MATRIX_ROWS must not exceed 255"
21 // matrix state buffer(1:on, 0:off)
22 #if (MATRIX_COLS <= 8)
23 static uint8_t *matrix;
24 static uint8_t *matrix_prev;
25 static uint8_t _matrix0[MATRIX_ROWS];
26 static uint8_t _matrix1[MATRIX_ROWS];
28 static uint16_t *matrix;
29 static uint16_t *matrix_prev;
30 static uint16_t _matrix0[MATRIX_ROWS];
31 static uint16_t _matrix1[MATRIX_ROWS];
34 #ifdef MATRIX_HAS_GHOST
35 static bool matrix_has_ghost_in_row(uint8_t row);
37 static uint8_t read_col(void);
38 static void unselect_rows(void);
39 static void select_row(uint8_t row);
43 uint8_t matrix_rows(void)
49 uint8_t matrix_cols(void)
54 void matrix_init(void)
56 // initialize row and col
58 // Input with pull-up(DDR:0, PORT:1)
62 // initialize matrix state: all keys off
63 for (uint8_t i=0; i < MATRIX_ROWS; i++) _matrix0[i] = 0x00;
64 for (uint8_t i=0; i < MATRIX_ROWS; i++) _matrix1[i] = 0x00;
66 matrix_prev = _matrix1;
69 uint8_t matrix_scan(void)
77 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
80 _delay_us(30); // without this wait read unstable value.
81 matrix[i] = ~read_col();
87 bool matrix_is_modified(void)
89 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
90 if (matrix[i] != matrix_prev[i])
97 bool matrix_has_ghost(void)
99 #ifdef MATRIX_HAS_GHOST
100 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
101 if (matrix_has_ghost_in_row(i))
109 bool matrix_is_on(uint8_t row, uint8_t col)
111 return (matrix[row] & (1<<col));
115 #if (MATRIX_COLS <= 8)
116 uint8_t matrix_get_row(uint8_t row)
118 uint16_t matrix_get_row(uint8_t row)
124 void matrix_print(void)
126 print("\nr/c 01234567\n");
127 for (uint8_t row = 0; row < matrix_rows(); row++) {
128 phex(row); print(": ");
129 #if (MATRIX_COLS <= 8)
130 pbin_reverse(matrix_get_row(row));
132 pbin_reverse16(matrix_get_row(row));
134 #ifdef MATRIX_HAS_GHOST
135 if (matrix_has_ghost_in_row(row)) {
143 uint8_t matrix_key_count(void)
146 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
147 #if (MATRIX_COLS <= 8)
148 count += bitpop(matrix[i]);
150 count += bitpop16(matrix[i]);
156 #ifdef MATRIX_HAS_GHOST
158 static bool matrix_has_ghost_in_row(uint8_t row)
160 // no ghost exists in case less than 2 keys on
161 if (((matrix[row] - 1) & matrix[row]) == 0)
164 // ghost exists in case same state as other row
165 for (uint8_t i=0; i < MATRIX_ROWS; i++) {
166 if (i != row && (matrix[i] & matrix[row]) == matrix[row])
174 static uint8_t read_col(void)
180 static void unselect_rows(void)
182 // Hi-Z(DDR:0, PORT:0) to unselect
183 DDRC &= ~0b11000000; // PC: 7,6
184 PORTC &= ~0b11000000;
185 DDRD &= ~0b11000111; // PD: 7,6,2,1,0
186 PORTD &= ~0b11000111;
187 DDRF &= ~0b11000000; // PF: 7,6
188 PORTF &= ~0b11000000;
192 static void select_row(uint8_t row)
194 // Output low(DDR:1, PORT:0) to select
195 // row: 0 1 2 3 4 5 6 7 8
196 // pin: PD0, PC7, PD7, PF6, PD6, PD1, PD2, PC6, PF7