matrix.c (2871B)
1 /* Copyright 2023 ebastler and elpekenin 2 * 3 * This program is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published by 5 * the Free Software Foundation, either version 2 of the License, or 6 * (at your option) any later version. 7 * 8 * This program is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16 17 #include "matrix.h" 18 #include "pca9555.h" 19 #include "timer.h" 20 21 // PCA9555 i2c address, 0x20: A0 = 0, A1 = 0, A2 = 0 22 #define IC1 0x20 23 24 // Define how long to wait to reach the IO expander after connection loss again 25 // Since this board is modular, it should not spam unnecessary i2c requests if used without a module 26 #define RETRY_TIMESPAN 2000 27 28 typedef enum { 29 PLUGGED, 30 DOUBTFUL, 31 UNPLUGGED 32 } expander_status_t; 33 34 void pca9555_setup(void) { 35 // Initialize the expander, no need to set ports to inputs as that is the default behavior 36 pca9555_init(IC1); 37 } 38 39 void matrix_init_custom(void) { 40 // Encoder pushbutton on the MCU is connected to PD2 41 gpio_set_pin_input_high(D2); 42 pca9555_setup(); 43 } 44 45 bool matrix_scan_custom(matrix_row_t current_matrix[]) { 46 static expander_status_t status = DOUBTFUL; 47 static uint32_t retry_timer = 0; 48 49 // initialize one byte filled with 1 50 uint8_t pin_states = 0xFF; 51 52 53 if (status != UNPLUGGED || timer_elapsed32(retry_timer) > RETRY_TIMESPAN) { 54 // If the chip was unplugged before, it needs to be re-initialized 55 if(status==UNPLUGGED) { 56 pca9555_setup(); 57 } 58 // Read the entire port into this byte, 1 = not pressed, 0 = pressed 59 bool ret = pca9555_read_pins(IC1, PCA9555_PORT0, &pin_states); 60 61 // Update state 62 if (ret) { 63 status = PLUGGED; 64 } else { 65 switch (status) { 66 case PLUGGED: 67 status = DOUBTFUL; 68 break; 69 70 case DOUBTFUL: 71 status = UNPLUGGED; 72 break; 73 74 // If we've diagnosed as unplugged, update timer to not read I2C 75 case UNPLUGGED: 76 retry_timer = timer_read32(); 77 } 78 } 79 } 80 81 // Shift pin states by 1 to make room for the switch connected to the MCU, then OR them together and invert (as QMK uses inverted logic compared to the electrical levels) 82 matrix_row_t data = ~(pin_states << 1 | gpio_read_pin(D2)); 83 84 bool changed = current_matrix[0] != data; 85 current_matrix[0] = data; 86 87 return changed; 88 }