matrix.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 "printf.h"
  8. #include "backlight.h"
  9. #include "matrix.h"
  10. /* Clueboard2
  11. *
  12. * Column pins are input with internal pull-down.
  13. * Row pins are output and strobe with high.
  14. * Key is high or 1 when it turns on.
  15. *
  16. * col: { PA3, PA2 }
  17. * row: { PA1 }
  18. */
  19. /* matrix state(1:on, 0:off) */
  20. static matrix_row_t matrix[MATRIX_ROWS];
  21. static matrix_row_t matrix_debouncing[MATRIX_ROWS];
  22. static bool debouncing = false;
  23. static uint16_t debouncing_time = 0;
  24. void matrix_init(void) {
  25. printf("matrix init\n");
  26. //debug_matrix = true;
  27. /* Column(sense) */
  28. palSetPadMode(GPIOA, 3, PAL_MODE_INPUT_PULLDOWN);
  29. palSetPadMode(GPIOA, 2, PAL_MODE_INPUT_PULLDOWN);
  30. /* Row(strobe) */
  31. palSetPadMode(GPIOA, 1, PAL_MODE_OUTPUT_PUSHPULL);
  32. palSetPad(GPIOA, 1); // 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. /* Setup the backlight */
  38. palSetPadMode(GPIOA, 4, PAL_MODE_OUTPUT_PUSHPULL);
  39. palSetPadMode(GPIOB, 7, PAL_MODE_OUTPUT_PUSHPULL);
  40. // Set them low to turn off the LEDs
  41. palClearPad(GPIOA, 4);
  42. palClearPad(GPIOB, 7);
  43. }
  44. uint8_t matrix_scan(void) {
  45. matrix_row_t data = 0;
  46. // read col data: { PA3, PA2 }
  47. data = (palReadPad(GPIOA, 3) | (palReadPad(GPIOA, 2) << 1));
  48. if (matrix_debouncing[0] != data) {
  49. matrix_debouncing[0] = data;
  50. debouncing = true;
  51. debouncing_time = timer_read();
  52. }
  53. if (debouncing && timer_elapsed(debouncing_time) > DEBOUNCE) {
  54. matrix[0] = matrix_debouncing[0];
  55. debouncing = false;
  56. }
  57. return 1;
  58. }
  59. bool matrix_is_on(uint8_t row, uint8_t col) {
  60. return (matrix[row] & (1<<col));
  61. }
  62. matrix_row_t matrix_get_row(uint8_t row) {
  63. return matrix[row];
  64. }
  65. void matrix_print(void) {
  66. printf("\nr/c 01234567\n");
  67. for (uint8_t row = 0; row < MATRIX_ROWS; row++) {
  68. printf("%X0: ", row);
  69. matrix_row_t data = matrix_get_row(row);
  70. for (int col = 0; col < MATRIX_COLS; col++) {
  71. if (data & (1<<col))
  72. printf("1");
  73. else
  74. printf("0");
  75. }
  76. printf("\n");
  77. }
  78. }