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.

104 lines
2.8 KiB

  1. // -----------------------------------------------------------------------------
  2. // Eergy monitor sensor
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. #include "Arduino.h"
  6. #include "BaseSensor.h"
  7. #include "EmonSensor.h"
  8. class EmonAnalogSensor : public EmonSensor {
  9. public:
  10. EmonAnalogSensor(unsigned char gpio, double voltage, unsigned char bits, double ref, double ratio): EmonSensor(voltage, bits, ref, ratio) {
  11. // Cache
  12. _gpio = gpio;
  13. _count = _magnitudes;
  14. // Prepare GPIO
  15. pinMode(gpio, INPUT);
  16. // warmup
  17. read(_gpio);
  18. }
  19. // Descriptive name of the sensor
  20. String name() {
  21. char buffer[20];
  22. snprintf(buffer, sizeof(buffer), "EMON @ GPIO%d", _gpio);
  23. return String(buffer);
  24. }
  25. // Descriptive name of the slot # index
  26. String slot(unsigned char index) {
  27. return name();
  28. }
  29. // Type for slot # index
  30. magnitude_t type(unsigned char index) {
  31. _error = SENSOR_ERROR_OK;
  32. unsigned char i=0;
  33. #if EMON_REPORT_CURRENT
  34. if (index == i++) return MAGNITUDE_CURRENT;
  35. #endif
  36. #if EMON_REPORT_POWER
  37. if (index == i++) return MAGNITUDE_POWER_APPARENT;
  38. #endif
  39. #if EMON_REPORT_ENERGY
  40. if (index == i) return MAGNITUDE_ENERGY;
  41. #endif
  42. _error = SENSOR_ERROR_OUT_OF_RANGE;
  43. return MAGNITUDE_NONE;
  44. }
  45. // Current value for slot # index
  46. double value(unsigned char index) {
  47. _error = SENSOR_ERROR_OK;
  48. // Cache the value
  49. static unsigned long last = 0;
  50. static double current = 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. #if EMON_REPORT_ENERGY
  79. unsigned long _energy = 0;
  80. #endif
  81. };