debounce.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <string.h>
  2. #include "config.h"
  3. #include "matrix.h"
  4. #include "timer.h"
  5. #include "quantum.h"
  6. #ifndef DEBOUNCING_DELAY
  7. # define DEBOUNCING_DELAY 5
  8. #endif
  9. //Debouncing counters
  10. typedef uint8_t debounce_counter_t;
  11. #define DEBOUNCE_COUNTER_MODULO 250
  12. #define DEBOUNCE_COUNTER_INACTIVE 251
  13. static debounce_counter_t *debounce_counters;
  14. void debounce_init(uint8_t num_rows)
  15. {
  16. debounce_counters = malloc(num_rows*MATRIX_COLS);
  17. memset(debounce_counters, DEBOUNCE_COUNTER_INACTIVE, num_rows*MATRIX_COLS);
  18. }
  19. void update_debounce_counters(uint8_t num_rows, uint8_t current_time)
  20. {
  21. for (uint8_t row = 0; row < num_rows; row++)
  22. {
  23. for (uint8_t col = 0; col < MATRIX_COLS; col++)
  24. {
  25. if (debounce_counters[row*MATRIX_COLS + col] != DEBOUNCE_COUNTER_INACTIVE)
  26. {
  27. if (TIMER_DIFF(current_time, debounce_counters[row*MATRIX_COLS + col], DEBOUNCE_COUNTER_MODULO) >= DEBOUNCING_DELAY) {
  28. debounce_counters[row*MATRIX_COLS + col] = DEBOUNCE_COUNTER_INACTIVE;
  29. }
  30. }
  31. }
  32. }
  33. }
  34. void transfer_matrix_values(matrix_row_t raw[], matrix_row_t cooked[], uint8_t num_rows, uint8_t current_time)
  35. {
  36. for (uint8_t row = 0; row < num_rows; row++)
  37. {
  38. matrix_row_t delta = raw[row] ^ cooked[row];
  39. for (uint8_t col = 0; col < MATRIX_COLS; col++)
  40. {
  41. if (debounce_counters[row*MATRIX_COLS + col] == DEBOUNCE_COUNTER_INACTIVE && (delta & (1<<col)))
  42. {
  43. debounce_counters[row*MATRIX_COLS + col] = current_time;
  44. cooked[row] ^= (1 << col);
  45. }
  46. }
  47. }
  48. }
  49. void debounce(matrix_row_t raw[], matrix_row_t cooked[], uint8_t num_rows, bool changed)
  50. {
  51. uint8_t current_time = timer_read() % DEBOUNCE_COUNTER_MODULO;
  52. update_debounce_counters(num_rows, current_time);
  53. transfer_matrix_values(raw, cooked, num_rows, current_time);
  54. }