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.

105 lines
2.9 KiB

  1. // -----------------------------------------------------------------------------
  2. // Energy Monitor Sensor using builtin ADC
  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. #include "EmonSensor.h"
  9. class EmonAnalogSensor : public EmonSensor {
  10. public:
  11. EmonAnalogSensor(unsigned char gpio, double voltage, unsigned char bits, double ref, double ratio): EmonSensor(voltage, bits, ref, ratio) {
  12. // Cache
  13. _gpio = gpio;
  14. _count = _magnitudes;
  15. // Prepare GPIO
  16. pinMode(gpio, INPUT);
  17. // warmup
  18. read(_gpio, _pivot);
  19. }
  20. // Descriptive name of the sensor
  21. String name() {
  22. char buffer[20];
  23. snprintf(buffer, sizeof(buffer), "EMON @ GPIO%d", _gpio);
  24. return String(buffer);
  25. }
  26. // Descriptive name of the slot # index
  27. String slot(unsigned char index) {
  28. return name();
  29. }
  30. // Type for slot # index
  31. magnitude_t type(unsigned char index) {
  32. _error = SENSOR_ERROR_OK;
  33. unsigned char i=0;
  34. #if EMON_REPORT_CURRENT
  35. if (index == i++) return MAGNITUDE_CURRENT;
  36. #endif
  37. #if EMON_REPORT_POWER
  38. if (index == i++) return MAGNITUDE_POWER_APPARENT;
  39. #endif
  40. #if EMON_REPORT_ENERGY
  41. if (index == i) return MAGNITUDE_ENERGY;
  42. #endif
  43. _error = SENSOR_ERROR_OUT_OF_RANGE;
  44. return MAGNITUDE_NONE;
  45. }
  46. // Current value for slot # index
  47. double value(unsigned char index) {
  48. _error = SENSOR_ERROR_OK;
  49. // Cache the value
  50. static unsigned long last = 0;
  51. if ((last == 0) || (millis() - last > 1000)) {
  52. _current = read(0, _pivot);
  53. #if EMON_REPORT_ENERGY
  54. _energy += (_current * _voltage * (millis() - last) / 1000);
  55. #endif
  56. last = millis();
  57. }
  58. // Report
  59. unsigned char i=0;
  60. #if EMON_REPORT_CURRENT
  61. if (index == i++) return _current;
  62. #endif
  63. #if EMON_REPORT_POWER
  64. if (index == i++) return _current * _voltage;
  65. #endif
  66. #if EMON_REPORT_ENERGY
  67. if (index == i) return _energy;
  68. #endif
  69. _error = SENSOR_ERROR_OUT_OF_RANGE;
  70. return 0;
  71. }
  72. protected:
  73. unsigned int readADC(unsigned char channel) {
  74. return analogRead(_gpio);
  75. }
  76. unsigned char _gpio;
  77. double _pivot = 0;
  78. double _current;
  79. #if EMON_REPORT_ENERGY
  80. unsigned long _energy = 0;
  81. #endif
  82. };