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.

74 lines
2.1 KiB

  1. /*
  2. Copyright 2021 Chad Austin <chad@chadaustin.me>
  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. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /*
  15. Symmetric per-row debounce algorithm. Changes only apply when
  16. DEBOUNCE milliseconds have elapsed since the last change.
  17. */
  18. #include "matrix.h"
  19. #include "timer.h"
  20. #include "quantum.h"
  21. #include <stdlib.h>
  22. #ifndef DEBOUNCE
  23. # define DEBOUNCE 5
  24. #endif
  25. static uint16_t last_time;
  26. // [row] milliseconds until key's state is considered debounced.
  27. static uint8_t* countdowns;
  28. // [row]
  29. static matrix_row_t* last_raw;
  30. void debounce_init(uint8_t num_rows) {
  31. countdowns = (uint8_t*)calloc(num_rows, sizeof(uint8_t));
  32. last_raw = (matrix_row_t*)calloc(num_rows, sizeof(matrix_row_t));
  33. last_time = timer_read();
  34. }
  35. void debounce_free(void) {
  36. free(countdowns);
  37. countdowns = NULL;
  38. free(last_raw);
  39. last_raw = NULL;
  40. }
  41. void debounce(matrix_row_t raw[], matrix_row_t cooked[], uint8_t num_rows, bool changed) {
  42. uint16_t now = timer_read();
  43. uint16_t elapsed16 = TIMER_DIFF_16(now, last_time);
  44. last_time = now;
  45. uint8_t elapsed = (elapsed16 > 255) ? 255 : elapsed16;
  46. uint8_t* countdown = countdowns;
  47. for (uint8_t row = 0; row < num_rows; ++row, ++countdown) {
  48. matrix_row_t raw_row = raw[row];
  49. if (raw_row != last_raw[row]) {
  50. *countdown = DEBOUNCE;
  51. last_raw[row] = raw_row;
  52. } else if (*countdown > elapsed) {
  53. *countdown -= elapsed;
  54. } else if (*countdown) {
  55. cooked[row] = raw_row;
  56. *countdown = 0;
  57. }
  58. }
  59. }
  60. bool debounce_active(void) {
  61. return true;
  62. }