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.

109 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. changed = false;
  52. pending = true;
  53. //_event = EVENT_SINGLE_CLICK;
  54. }
  55. // pressed
  56. } else {
  57. _last_start = _this_start;
  58. _this_start = millis();
  59. _event = EVENT_PRESSED;
  60. }
  61. }
  62. }
  63. if (pending && (millis() - _this_start > DOUBLE_CLICK_DELAY) && (!changed) && (_status == _defaultStatus)) {
  64. pending = false;
  65. changed = true;
  66. _event = EVENT_SINGLE_CLICK;
  67. }
  68. if (changed) {
  69. if (_callback) {
  70. _callback(_pin, EVENT_CHANGED);
  71. _callback(_pin, _event);
  72. }
  73. }
  74. return changed;
  75. }
  76. bool DebounceEvent::pressed() {
  77. return (_status != _defaultStatus);
  78. }
  79. uint8_t DebounceEvent::getEvent() {
  80. return _event;
  81. }