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.

87 lines
2.5 KiB

  1. // -----------------------------------------------------------------------------
  2. // Event Counter Sensor
  3. // Copyright (C) 2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #pragma once
  6. #include "Arduino.h"
  7. #include "BaseSensor.h"
  8. class EventSensor : public BaseSensor {
  9. public:
  10. // ---------------------------------------------------------------------
  11. // Public
  12. // ---------------------------------------------------------------------
  13. EventSensor(): BaseSensor() {
  14. _count = 1;
  15. }
  16. void setGPIO(unsigned char gpio, int mode = INPUT) {
  17. _gpio = gpio;
  18. pinMode(_gpio, mode);
  19. }
  20. void setDebounceTime(unsigned long debounce) {
  21. _debounce = debounce;
  22. }
  23. // ---------------------------------------------------------------------
  24. // Sensors API
  25. // ---------------------------------------------------------------------
  26. void InterruptHandler() {
  27. static unsigned long last = 0;
  28. if (millis() - last > _debounce) {
  29. _events = _events + 1;
  30. last = millis();
  31. }
  32. }
  33. // Descriptive name of the sensor
  34. String name() {
  35. char buffer[20];
  36. snprintf(buffer, sizeof(buffer), "EVENT @ GPIO%d", _gpio);
  37. return String(buffer);
  38. }
  39. // Descriptive name of the slot # index
  40. String slot(unsigned char index) {
  41. return name();
  42. }
  43. // Type for slot # index
  44. magnitude_t type(unsigned char index) {
  45. _error = SENSOR_ERROR_OK;
  46. if (index == 0) return MAGNITUDE_EVENTS;
  47. _error = SENSOR_ERROR_OUT_OF_RANGE;
  48. return MAGNITUDE_NONE;
  49. }
  50. // Current value for slot # index
  51. double value(unsigned char index) {
  52. _error = SENSOR_ERROR_OK;
  53. if (index == 0) {
  54. double value = _events;
  55. _events = 0;
  56. return value;
  57. };
  58. _error = SENSOR_ERROR_OUT_OF_RANGE;
  59. return 0;
  60. }
  61. protected:
  62. // ---------------------------------------------------------------------
  63. // Protected
  64. // ---------------------------------------------------------------------
  65. volatile unsigned long _events = 0;
  66. unsigned long _debounce = 0;
  67. unsigned char _gpio;
  68. };