keybrd library is an open source library for creating custom-keyboard firmware.
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

debounce_unit_test.cpp 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* test debounce() function. 16/6/1 Passed test for SAMPLE_COUNT 1, 2, and 4.
  2. copied from keybrd/src/Row::debounce()
  3. to run test:
  4. $ g++ debounce_unit_test.cpp
  5. $ ./a.out
  6. */
  7. #include <inttypes.h>
  8. #include <iostream>
  9. #define SAMPLE_COUNT 4 //number of consecutive equal bits needed to change a debounced bit
  10. uint8_t samples[SAMPLE_COUNT]; //bitwise, one bit per key, most recent readings
  11. uint8_t samplesIndex = 0; //samples[] current write index
  12. uint8_t debounced = 0; //bitwise, one bit per key
  13. uint8_t debounce(const uint8_t rowState)
  14. {
  15. uint8_t all_1 = ~0; //bitwise
  16. uint8_t all_0 = 0; //bitwise
  17. //delayMicroseconds(DELAY_MICROSECONDS); //delay between Row scans to debounce key
  18. samples[samplesIndex] = rowState; //insert rowState into samples[] ring buffer
  19. if (++samplesIndex >= SAMPLE_COUNT) //if end of ring buffer
  20. {
  21. samplesIndex = 0; //wrap samplesIndex to beginning of ring buffer
  22. }
  23. for (uint8_t j = 0; j < SAMPLE_COUNT; j++) //traverse the sample[] ring buffer
  24. {
  25. all_1 &= samples[j]; //1 if all samples are 1
  26. all_0 |= samples[j]; //0 if all samples are 0
  27. }
  28. // update newDebounce if all the samples agree with one another
  29. // if all samples=1 then newDebounced=1
  30. // elseif all samples=0 then newDebounced=0
  31. // else newDebounced=debounced i.e. no change
  32. //return all_1 | (all_0 & debounced);
  33. debounced = all_1 | (all_0 & debounced);
  34. return debounced;
  35. }
  36. int main()
  37. {
  38. //Test input and output only shows first bit of each byte.
  39. const uint8_t pressed[] = {1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0};
  40. const uint8_t bouncy[] = {1,0,0,0,0,1,0,0,1,1,1,1,0,1,1,1,1,0,0,0,0};
  41. const uint8_t SCAN_COUNT = sizeof(bouncy)/sizeof(*bouncy);
  42. uint8_t i;
  43. uint8_t newDebounced;
  44. std::cout << "button pressed: ";
  45. for (i=0; i<SCAN_COUNT; i++)
  46. {
  47. std::cout << (int)pressed[i];
  48. }
  49. std::cout << std::endl;
  50. std::cout << "bouncy signal: ";
  51. for (i=0; i<SCAN_COUNT; i++)
  52. {
  53. std::cout << (int)bouncy[i];
  54. }
  55. std::cout << std::endl;
  56. std::cout << "debounced signal: ";
  57. for (i=0; i<SCAN_COUNT; i++)
  58. {
  59. newDebounced = debounce(bouncy[i]);
  60. std::cout << (int)newDebounced;
  61. }
  62. std::cout << std::endl;
  63. }
  64. void loop() { }