7 #include <util/delay.h>
10 #include "matrix_skel.h"
12 // matrix is active low. (key on: 0/key off: 1)
14 // HHKB has no ghost and no bounce.
15 // row: HC4051 select input channel(0-8)
16 // PB0, PB1, PB2(A, B, C)
17 // col: LS145 select low output line(0-8)
18 // PB3, PB4, PB5, PB6(A, B, C, D)
19 // use D as ENABLE: (enable: 0/unenable: 1)
20 // key: KEY: (on: 0/ off:1)
21 // KEY_PREV: (on: 1/ off: 0)
22 // PE6,PE7(KEY, KEY_PREV)
23 #define COL_ENABLE (1<<6)
24 #define KEY_SELELCT(ROW, COL) (PORTB = (PORTB&(1<<7))|COL_ENABLE|(((COL)&0x07)<<3)|((ROW)&0x07))
25 #define KEY_ENABLE (PORTB &= ~COL_ENABLE)
26 #define KEY_UNABLE (PORTB |= COL_ENABLE)
27 #define KEY_STATE (PINE&(1<<6))
28 #define KEY_PREV_ON (PORTE |= (1<<7))
29 #define KEY_PREV_OFF (PORTE &= ~(1<<7))
31 // matrix state buffer
32 static uint8_t *matrix;
33 static uint8_t *matrix_prev;
34 static uint8_t _matrix0[MATRIX_ROWS];
35 static uint8_t _matrix1[MATRIX_ROWS];
50 // this must be called once before matrix_scan.
51 void matrix_init(void)
53 // row & col output(PB0-6)
56 // KEY: input with pullup(PE6)
57 // KEY_PREV: output(PE7)
61 // initialize matrix state: all keys off
62 for (int i=0; i < MATRIX_ROWS; i++) _matrix0[i] = 0x00;
63 for (int i=0; i < MATRIX_ROWS; i++) _matrix1[i] = 0x00;
65 matrix_prev = _matrix1;
76 for (int row = 0; row < MATRIX_ROWS; row++) {
77 for (int col = 0; col < MATRIX_COLS; col++) {
78 KEY_SELELCT(row, col);
79 _delay_us(40); // from logic analyzer chart
80 if (matrix_prev[row] & (1<<col)) {
83 _delay_us(7); // from logic analyzer chart
85 _delay_us(10); // from logic analyzer chart
87 matrix[row] &= ~(1<<col);
89 matrix[row] |= (1<<col);
93 _delay_us(150); // from logic analyzer chart
99 bool matrix_is_modified(void)
101 for (int i = 0; i < MATRIX_ROWS; i++) {
102 if (matrix[i] != matrix_prev[i])
109 bool matrix_has_ghost(void)
115 bool matrix_is_on(int row, int col)
117 return (matrix[row] & (1<<col));
121 uint16_t matrix_get_row(int row)
126 void matrix_print(void)
128 print("\nr/c 01234567\n");
129 for (int row = 0; row < matrix_rows(); row++) {
130 phex(row); print(": ");
131 pbin_reverse(matrix_get_row(row));
136 int matrix_key_count(void)
139 for (int i = 0; i < MATRIX_ROWS; i++) {
140 count += bitpop(matrix[i]);