2 Copyright 2012 Jun Wako <wakojun@gmail.com>
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include <util/delay.h>
34 static uint8_t debouncing = DEBOUNCE;
36 /* matrix state(1:on, 0:off) */
37 static matrix_row_t matrix[MATRIX_ROWS];
38 static matrix_row_t matrix_debouncing[MATRIX_ROWS];
40 static matrix_row_t read_cols(void);
41 static void init_cols(void);
42 static void unselect_rows(void);
43 static void select_row(uint8_t row);
47 uint8_t matrix_rows(void)
53 uint8_t matrix_cols(void)
58 void matrix_init(void)
60 // initialize row and col
64 // initialize matrix state: all keys off
65 for (uint8_t i=0; i < MATRIX_ROWS; i++) {
67 matrix_debouncing[i] = 0;
71 uint8_t matrix_scan(void)
73 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
75 _delay_us(30); // without this wait read unstable value.
76 matrix_row_t cols = read_cols();
77 if (matrix_debouncing[i] != cols) {
78 matrix_debouncing[i] = cols;
80 debug("bounce!: "); debug_hex(debouncing); debug("\n");
82 debouncing = DEBOUNCE;
91 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
92 matrix[i] = matrix_debouncing[i];
101 bool matrix_is_on(uint8_t row, uint8_t col)
103 return (matrix[row] & ((matrix_row_t)1<<col));
107 matrix_row_t matrix_get_row(uint8_t row)
112 void matrix_print(void)
114 print("\nr/c 0123456789ABCDEF\n");
115 for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
116 phex(row); print(": ");
117 pbin_reverse16(matrix_get_row(row));
122 /* Column pin configuration
123 * col: 0 1 2 3 4 5 6 7
124 * pin: B0 B1 B2 B3 B4 B5 B6 B7
126 static void init_cols(void)
128 // Input with pull-up(DDR:0, PORT:1)
133 /* Returns status of switches(1:on, 0:off) */
134 static matrix_row_t read_cols(void)
136 // Invert because PIN indicates 'switch on' with low(0) and 'off' with high(1)
140 /* Row pin configuration
141 * row: 0 1 2 3 4 5 6 7
142 * pin: D0 D1 D2 D3 D4 D5 D6 C2
144 static void unselect_rows(void)
146 // Hi-Z(DDR:0, PORT:0) to unselect
148 PORTD &= ~0b01111111;
150 PORTD &= ~0b00000100;
153 static void select_row(uint8_t row)
155 // Output low(DDR:1, PORT:0) to select