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.

78 lines
2.0 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. bool changed = false;
  33. if (digitalRead(_pin) != _status) {
  34. delay(_delay);
  35. uint8_t newStatus = digitalRead(_pin);
  36. if (newStatus != _status) {
  37. changed = true;
  38. _status = newStatus;
  39. // raise events if callback defined
  40. if (_callback) {
  41. // raise change event
  42. _callback(_pin, EVENT_CHANGED);
  43. if (_status == _defaultStatus) {
  44. // raise released event
  45. _callback(_pin, EVENT_RELEASED);
  46. } else {
  47. // raise pressed event
  48. _callback(_pin, EVENT_PRESSED);
  49. }
  50. }
  51. }
  52. }
  53. return changed;
  54. }
  55. bool DebounceEvent::pressed() {
  56. return (_status != _defaultStatus);
  57. }