7 #include <util/delay.h>
10 #include "controller.h"
11 #include "matrix_skel.h"
13 // matrix is active low. (key on: 0/key off: 1)
14 // row: Hi-Z(unselected)/low output(selected)
15 // PD0, PC7, PD7, PF6, PD6, PD1, PD2, PC6, PF7
16 // col: input w/pullup
19 // matrix state buffer
20 static uint8_t *matrix;
21 static uint8_t *matrix_prev;
22 static uint8_t _matrix0[MATRIX_ROWS];
23 static uint8_t _matrix1[MATRIX_ROWS];
25 static bool matrix_has_ghost_in_row(uint8_t row);
26 static uint8_t read_col(void);
27 static void unselect_rows(void);
28 static void select_row(uint8_t row);
43 // this must be called once before matrix_scan.
44 void matrix_init(void)
46 // initialize row and col
51 // initialize matrix state: all keys off
52 for (int i=0; i < MATRIX_ROWS; i++) _matrix0[i] = 0x00;
53 for (int i=0; i < MATRIX_ROWS; i++) _matrix1[i] = 0x00;
55 matrix_prev = _matrix1;
66 for (int i = 0; i < MATRIX_ROWS; i++) {
68 _delay_us(30); // without this wait read unstable value.
69 matrix[i] = ~read_col();
75 bool matrix_is_modified(void)
77 for (int i = 0; i < MATRIX_ROWS; i++) {
78 if (matrix[i] != matrix_prev[i])
84 bool matrix_has_ghost(void)
86 for (int i = 0; i < MATRIX_ROWS; i++) {
87 if (matrix_has_ghost_in_row(i))
94 bool matrix_is_on(int row, int col)
96 return (matrix[row] & (1<<col));
100 uint16_t matrix_get_row(int row)
105 void matrix_print(void)
107 print("\nr/c 01234567\n");
108 for (int row = 0; row < matrix_rows(); row++) {
109 phex(row); print(": ");
110 pbin_reverse(matrix_get_row(row));
111 if (matrix_has_ghost_in_row(row)) {
118 int matrix_key_count(void)
121 for (int i = 0; i < MATRIX_ROWS; i++) {
122 count += bitpop(matrix[i]);
127 static bool matrix_has_ghost_in_row(uint8_t row)
129 // no ghost exists in case less than 2 keys on
130 if (((matrix[row] - 1) & matrix[row]) == 0)
133 // ghost exists in case same state as other row
134 for (int i=0; i < MATRIX_ROWS; i++) {
135 if (i != row && (matrix[i] & matrix[row]) == matrix[row])
141 static uint8_t read_col(void)
146 static void unselect_rows(void)
156 static void select_row(uint8_t row)