matrix.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <stdint.h>
  2. #include <stdbool.h>
  3. #include <string.h>
  4. #include "hal.h"
  5. #include "timer.h"
  6. #include "wait.h"
  7. #include "print.h"
  8. #include "matrix.h"
  9. /* Clueboard SimonTester
  10. *
  11. * Column pins are input with internal pull-down.
  12. * Row pins are output and strobe with high.
  13. * Key is high or 1 when it turns on.
  14. *
  15. * col: { PA5, PA4, PB6, PB3 }
  16. * row: { PA7 }
  17. */
  18. /* matrix state(1:on, 0:off) */
  19. static matrix_row_t matrix[MATRIX_ROWS];
  20. static matrix_row_t matrix_debouncing[MATRIX_ROWS];
  21. static bool debouncing = false;
  22. static uint16_t debouncing_time = 0;
  23. void matrix_init(void) {
  24. //debug_matrix = true;
  25. /* Column(sense) */
  26. palSetPadMode(GPIOA, 5, PAL_MODE_INPUT_PULLDOWN);
  27. palSetPadMode(GPIOA, 4, PAL_MODE_INPUT_PULLDOWN);
  28. palSetPadMode(GPIOB, 7, PAL_MODE_INPUT_PULLDOWN);
  29. palSetPadMode(GPIOB, 3, PAL_MODE_INPUT_PULLDOWN);
  30. /* Row(strobe) */
  31. palSetPadMode(GPIOA, 7, PAL_MODE_OUTPUT_PUSHPULL);
  32. palSetPad(GPIOA, 7); // Only one row, so leave it in strobe state all the time
  33. // I did it this way so hardware hackers would have another
  34. // pin to play with.
  35. memset(matrix, 0, MATRIX_ROWS);
  36. memset(matrix_debouncing, 0, MATRIX_ROWS);
  37. }
  38. uint8_t matrix_scan(void) {
  39. for (int row = 0; row < MATRIX_ROWS; row++) {
  40. matrix_row_t data = 0;
  41. // read col data: { PA5, PA4, PB6, PB3 }
  42. data = (palReadPad(GPIOA, 5) |
  43. palReadPad(GPIOA, 4) |
  44. palReadPad(GPIOB, 6) |
  45. palReadPad(GPIOB, 3));
  46. if (matrix_debouncing[row] != data) {
  47. matrix_debouncing[row] = data;
  48. debouncing = true;
  49. debouncing_time = timer_read();
  50. }
  51. }
  52. if (debouncing && timer_elapsed(debouncing_time) > DEBOUNCE) {
  53. for (int row = 0; row < MATRIX_ROWS; row++) {
  54. matrix[row] = matrix_debouncing[row];
  55. }
  56. debouncing = false;
  57. }
  58. return 1;
  59. }
  60. bool matrix_is_on(uint8_t row, uint8_t col) {
  61. return (matrix[row] & (1<<col));
  62. }
  63. matrix_row_t matrix_get_row(uint8_t row) {
  64. return matrix[row];
  65. }
  66. void matrix_print(void) {
  67. xprintf("\nr/c 01234567\n");
  68. for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
  69. xprintf("%X0: ", row);
  70. matrix_row_t data = matrix_get_row(row);
  71. for (int col = 0; col < MATRIX_COLS; col++) {
  72. if (data & (1<<col))
  73. xprintf("1");
  74. else
  75. xprintf("0");
  76. }
  77. xprintf("\n");
  78. }
  79. }