Fork of the espurna firmware for `mhsw` switches
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.

111 lines
2.8 KiB

  1. /*
  2. Debounce buttons and trigger events
  3. Copyright (C) 2015 by Xose Pérez <xose dot perez at gmail dot com>
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include <Arduino.h>
  16. #include "DebounceEvent.h"
  17. DebounceEvent::DebounceEvent(uint8_t pin, callback_t callback, uint8_t defaultStatus, unsigned long delay) {
  18. // store configuration
  19. _pin = pin;
  20. _status = _defaultStatus = defaultStatus;
  21. _delay = delay;
  22. _callback = callback;
  23. // set up button
  24. if (_defaultStatus == LOW) {
  25. pinMode(_pin, INPUT);
  26. } else {
  27. pinMode(_pin, INPUT_PULLUP);
  28. }
  29. }
  30. bool DebounceEvent::loop() {
  31. // holds whether status has changed or not
  32. static bool pending = false;
  33. bool changed = false;
  34. _event = EVENT_NONE;
  35. if (digitalRead(_pin) != _status) {
  36. // Debounce
  37. delay(_delay);
  38. uint8_t newStatus = digitalRead(_pin);
  39. if (newStatus != _status) {
  40. changed = true;
  41. pending = false;
  42. _status = newStatus;
  43. // released
  44. if (_status == _defaultStatus) {
  45. // get event
  46. if (millis() - _this_start > LONG_CLICK_DELAY) {
  47. _event = EVENT_LONG_CLICK;
  48. } else if (millis() - _last_start < DOUBLE_CLICK_DELAY ) {
  49. _event = EVENT_DOUBLE_CLICK;
  50. } else {
  51. Serial.println("deferring");
  52. changed = false;
  53. pending = true;
  54. //_event = EVENT_SINGLE_CLICK;
  55. }
  56. // pressed
  57. } else {
  58. _last_start = _this_start;
  59. _this_start = millis();
  60. _event = EVENT_PRESSED;
  61. }
  62. }
  63. }
  64. if (pending && (millis() - _this_start > DOUBLE_CLICK_DELAY) && (!changed) && (_status == _defaultStatus)) {
  65. Serial.println("catched");
  66. pending = false;
  67. changed = true;
  68. _event = EVENT_SINGLE_CLICK;
  69. }
  70. if (changed) {
  71. if (_callback) {
  72. _callback(_pin, EVENT_CHANGED);
  73. _callback(_pin, _event);
  74. }
  75. }
  76. return changed;
  77. }
  78. bool DebounceEvent::pressed() {
  79. return (_status != _defaultStatus);
  80. }
  81. uint8_t DebounceEvent::getEvent() {
  82. return _event;
  83. }