logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

matrix.c (2630B)


  1. /*
  2. Copyright 2022 somepin
  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. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include "matrix.h"
  15. #include "sn74x138.h"
  16. static const pin_t col_pins[MATRIX_COLS] = MATRIX_COL_PINS;
  17. /* All rows use a 74HC138 3 to 8 bit demultiplexer.
  18. *
  19. * A2 A1 A0
  20. * D0 D1 D2
  21. * 0: 0 0 0
  22. * 1: 0 0 1
  23. * 2: 0 1 0
  24. * 3: 0 1 1
  25. * 4: 1 0 0
  26. * 5: 1 0 1
  27. * 6: 1 1 0
  28. */
  29. static void select_row(uint8_t row) {
  30. sn74x138_set_addr(row);
  31. }
  32. static void init_pins(void) {
  33. for (uint8_t x = 0; x < MATRIX_COLS; x++) {
  34. gpio_set_pin_input_high(col_pins[x]);
  35. }
  36. }
  37. static bool read_cols_on_row(matrix_row_t current_matrix[], uint8_t current_row) {
  38. bool matrix_changed = false;
  39. // Store last value of row prior to reading
  40. matrix_row_t last_row_value = current_matrix[current_row];
  41. // Start with a clear matrix row
  42. current_matrix[current_row] = 0;
  43. // Select row and wait for row selection to stabilize
  44. select_row(current_row);
  45. matrix_io_delay();
  46. // For each col...
  47. matrix_row_t row_shifter = MATRIX_ROW_SHIFTER;
  48. for (uint8_t col_index = 0; col_index < MATRIX_COLS; col_index++) {
  49. // Select the col pin to read (active low)
  50. uint8_t pin_state = gpio_read_pin(col_pins[col_index]);
  51. // Populate the matrix row with the state of the col pin
  52. current_matrix[current_row] |= pin_state ? 0 : (row_shifter << col_index);
  53. }
  54. // Determine if matrix changed state
  55. if ((last_row_value != current_matrix[current_row]) && !(matrix_changed)) {
  56. matrix_changed = true;
  57. }
  58. return matrix_changed;
  59. }
  60. void matrix_init_custom(void) {
  61. // initialize demultiplexer
  62. sn74x138_init();
  63. // initialize key pins
  64. init_pins();
  65. }
  66. bool matrix_scan_custom(matrix_row_t current_matrix[]) {
  67. bool changed = false;
  68. // Set row, read cols
  69. for (uint8_t current_row = 0; current_row < MATRIX_ROWS; current_row++) {
  70. changed |= read_cols_on_row(current_matrix, current_row);
  71. }
  72. return changed;
  73. }