Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

matrix.c 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * scan matrix
  3. */
  4. #include <avr/io.h>
  5. #include <util/delay.h>
  6. #include "keymap.h"
  7. #include "matrix.h"
  8. #include "print.h"
  9. // matrix is active low. (key on: 0/key off: 1)
  10. //
  11. // HHKB has no ghost and no bounce.
  12. // row: HC4051 select input channel(0-8)
  13. // PB0, PB1, PB2(A, B, C)
  14. // col: LS145 select low output line(0-8)
  15. // PB3, PB4, PB5, PB6(A, B, C, D)
  16. // use D as ENABLE: (enable: 0/unenable: 1)
  17. // key: KEY: (on: 0/ off:1)
  18. // UNKNOWN: unknown whether input or output
  19. // PE6,PE7(KEY, UNKNOWN)
  20. #define COL_ENABLE (1<<6)
  21. #define KEY_SELELCT(ROW, COL) (PORTB = COL_ENABLE|(((COL)&0x07)<<3)|((ROW)&0x07))
  22. #define KEY_ENABLE (PORTB &= ~COL_ENABLE)
  23. #define KEY_UNABLE (PORTB |= COL_ENABLE)
  24. #define KEY_ON ((PINE&(1<<6)) ? false : true)
  25. // matrix state buffer
  26. uint8_t *matrix;
  27. uint8_t *matrix_prev;
  28. static uint8_t _matrix0[MATRIX_ROWS];
  29. static uint8_t _matrix1[MATRIX_ROWS];
  30. // this must be called once before matrix_scan.
  31. void matrix_init(void)
  32. {
  33. // row & col output(PB0-6)
  34. DDRB = 0xFF;
  35. PORTB = KEY_SELELCT(0, 0);
  36. // KEY & VALID input with pullup(PE6,7)
  37. DDRE = 0x3F;
  38. PORTE = 0xC0;
  39. // initialize matrix state: all keys off
  40. for (int i=0; i < MATRIX_ROWS; i++) _matrix0[i] = 0xFF;
  41. for (int i=0; i < MATRIX_ROWS; i++) _matrix1[i] = 0xFF;
  42. matrix = _matrix0;
  43. matrix_prev = _matrix1;
  44. }
  45. uint8_t matrix_scan(void)
  46. {
  47. uint8_t *tmp;
  48. tmp = matrix_prev;
  49. matrix_prev = matrix;
  50. matrix = tmp;
  51. for (int row = 0; row < MATRIX_ROWS; row++) {
  52. for (int col = 0; col < MATRIX_COLS; col++) {
  53. KEY_SELELCT(row, col);
  54. _delay_us(50); // from logic analyzer chart
  55. KEY_ENABLE;
  56. _delay_us(10); // from logic analyzer chart
  57. if (KEY_ON) {
  58. matrix[row] &= ~(1<<col);
  59. } else {
  60. matrix[row] |= (1<<col);
  61. }
  62. KEY_UNABLE;
  63. _delay_us(150); // from logic analyzer chart
  64. }
  65. }
  66. return 1;
  67. }
  68. bool matrix_is_modified(void) {
  69. for (int i=0; i <MATRIX_ROWS; i++) {
  70. if (matrix[i] != matrix_prev[i])
  71. return true;
  72. }
  73. return false;
  74. }
  75. bool matrix_has_ghost(void) {
  76. return false;
  77. }
  78. bool matrix_has_ghost_in_row(uint8_t row) {
  79. return false;
  80. }