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>
35 static bool debouncing = false;
36 static uint16_t debouncing_time = 0;
38 /* matrix state(1:on, 0:off) */
39 static matrix_row_t matrix[MATRIX_ROWS];
40 static matrix_row_t matrix_debouncing[MATRIX_ROWS];
42 static matrix_row_t read_cols(void);
43 static void init_cols(void);
44 static void unselect_rows(void);
45 static void select_row(uint8_t row);
48 #define LED_ON() do { DDRC |= (1<<5); PORTC |= (1<<5); } while (0)
49 #define LED_OFF() do { DDRC &= ~(1<<5); PORTC &= ~(1<<5); } while (0)
50 #define LED_TGL() do { DDRC |= (1<<5); PINC |= (1<<5); } while (0)
52 void matrix_init(void)
54 // initialize row and col
58 // initialize matrix state: all keys off
59 for (uint8_t i=0; i < MATRIX_ROWS; i++) {
61 matrix_debouncing[i] = 0;
71 uint8_t matrix_scan(void)
73 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
75 _delay_us(30); // delay for settling
76 matrix_row_t cols = read_cols();
77 if (matrix_debouncing[i] != cols) {
79 dprintf("bounce: %d %d@%02X\n", timer_elapsed(debouncing_time), i, matrix_debouncing[i]^cols);
81 matrix_debouncing[i] = cols;
83 debouncing_time = timer_read();
88 if (debouncing && timer_elapsed(debouncing_time) >= DEBOUNCE) {
89 for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
90 matrix[i] = matrix_debouncing[i];
99 matrix_row_t matrix_get_row(uint8_t row)
104 /* Column pin configuration
105 * col: 0 1 2 3 4 5 6 7
106 * pin: B0 B1 B2 B3 B4 B5 B6 B7
108 static void init_cols(void)
110 // Input with pull-up(DDR:0, PORT:1)
115 /* Returns status of switches(1:on, 0:off) */
116 static matrix_row_t read_cols(void)
118 // Invert because PIN indicates 'switch on' with low(0) and 'off' with high(1)
122 /* Row pin configuration
123 * row: 0 1 2 3 4 5 6 7
124 * pin: D0 D1 D2 D3 D4 D5 D6 C2
126 static void unselect_rows(void)
128 // Hi-Z(DDR:0, PORT:0) to unselect
130 PORTD &= ~0b01111111;
132 PORTC &= ~0b00000100;
135 static void select_row(uint8_t row)
137 // Output low(DDR:1, PORT:0) to select