matrix.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* Copyright 2018 James Laird-Wah
  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. #include <quantum.h>
  17. #include <i2c_master.h>
  18. #include <string.h>
  19. #include "model01.h"
  20. /* If no key events have occurred, the scanners will time out on reads.
  21. * So we don't want to be too permissive here. */
  22. #define I2C_TIMEOUT 10
  23. static matrix_row_t rows[MATRIX_ROWS];
  24. #define ROWS_PER_HAND (MATRIX_ROWS / 2)
  25. inline
  26. uint8_t matrix_rows(void) {
  27. return MATRIX_ROWS;
  28. }
  29. inline
  30. uint8_t matrix_cols(void) {
  31. return MATRIX_COLS;
  32. }
  33. static int i2c_read_hand(int hand) {
  34. uint8_t buf[5];
  35. i2c_status_t ret = i2c_receive(I2C_ADDR(hand), buf, sizeof(buf), I2C_TIMEOUT);
  36. if (ret != I2C_STATUS_SUCCESS)
  37. return 1;
  38. if (buf[0] != TWI_REPLY_KEYDATA)
  39. return 2;
  40. int start_row = hand ? ROWS_PER_HAND : 0;
  41. uint8_t *out = &rows[start_row];
  42. memcpy(out, &buf[1], 4);
  43. return 0;
  44. }
  45. static int i2c_set_keyscan_interval(int hand, int delay) {
  46. uint8_t buf[] = {TWI_CMD_KEYSCAN_INTERVAL, delay};
  47. i2c_status_t ret = i2c_transmit(I2C_ADDR(hand), buf, sizeof(buf), I2C_TIMEOUT);
  48. return ret;
  49. }
  50. void matrix_init(void) {
  51. /* Ensure scanner power is on - else right hand will not work */
  52. DDRC |= _BV(7);
  53. PORTC |= _BV(7);
  54. i2c_init();
  55. i2c_set_keyscan_interval(LEFT, 2);
  56. i2c_set_keyscan_interval(RIGHT, 2);
  57. memset(rows, 0, sizeof(rows));
  58. matrix_init_quantum();
  59. }
  60. uint8_t matrix_scan(void) {
  61. uint8_t ret = 0;
  62. ret |= i2c_read_hand(LEFT);
  63. ret |= i2c_read_hand(RIGHT);
  64. matrix_scan_quantum();
  65. return ret;
  66. }
  67. inline
  68. matrix_row_t matrix_get_row(uint8_t row) {
  69. return rows[row];
  70. }
  71. void matrix_print(void) {
  72. print("\nr/c 0123456789ABCDEF\n");
  73. for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
  74. phex(row); print(": ");
  75. pbin_reverse16(matrix_get_row(row));
  76. print("\n");
  77. }
  78. }
  79. /* vim: set ts=2 sw=2 et: */