matrix.c (2308B)
1 /* 2 * Copyright 2018-2023 Jack Humbert <jack.humb@gmail.com> 3 * 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. 8 * 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. 13 * 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/>. 16 */ 17 18 #include "matrix.h" 19 #include "wait.h" 20 21 /* matrix state(1:on, 0:off) */ 22 static pin_t matrix_row_pins[MATRIX_ROWS] = MATRIX_ROW_PINS; 23 static pin_t matrix_col_pins[MATRIX_COLS] = MATRIX_COL_PINS; 24 25 static matrix_row_t matrix_inverted[MATRIX_COLS]; 26 27 void matrix_init_custom(void) { 28 // actual matrix setup - cols 29 for (int i = 0; i < MATRIX_COLS; i++) { 30 gpio_set_pin_output(matrix_col_pins[i]); 31 gpio_write_pin_low(matrix_col_pins[i]); 32 } 33 34 // rows 35 for (int i = 0; i < MATRIX_ROWS; i++) { 36 gpio_set_pin_input_low(matrix_row_pins[i]); 37 } 38 } 39 40 bool matrix_scan_custom(matrix_row_t current_matrix[]) { 41 bool changed = false; 42 43 // actual matrix 44 for (int col = 0; col < MATRIX_COLS; col++) { 45 matrix_row_t data = 0; 46 47 // strobe col 48 gpio_write_pin_high(matrix_col_pins[col]); 49 50 // need wait to settle pin state 51 wait_us(20); 52 53 // read row data 54 for (int row = 0; row < MATRIX_ROWS; row++) { 55 data |= (gpio_read_pin(matrix_row_pins[row]) << row); 56 } 57 58 // unstrobe col 59 gpio_write_pin_low(matrix_col_pins[col]); 60 61 if (matrix_inverted[col] != data) { 62 matrix_inverted[col] = data; 63 } 64 } 65 66 for (int row = 0; row < MATRIX_ROWS; row++) { 67 matrix_row_t old = current_matrix[row]; 68 current_matrix[row] = 0; 69 for (int col = 0; col < MATRIX_COLS; col++) { 70 current_matrix[row] |= ((matrix_inverted[col] & (1 << row) ? 1 : 0) << col); 71 } 72 changed |= old != current_matrix[row]; 73 } 74 75 return changed; 76 }