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.

90 lines
2.4 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 = 4;
  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. if (index == 0) return MAGNITUDE_CURRENT;
  33. if (index == 1) return MAGNITUDE_POWER_APPARENT;
  34. if (index == 2) return MAGNITUDE_ENERGY;
  35. if (index == 3) return MAGNITUDE_ENERGY_DELTA;
  36. _error = SENSOR_ERROR_OUT_OF_RANGE;
  37. return MAGNITUDE_NONE;
  38. }
  39. // Current value for slot # index
  40. double value(unsigned char index) {
  41. _error = SENSOR_ERROR_OK;
  42. // Cache the value
  43. static unsigned long last = 0;
  44. static double current = 0;
  45. static unsigned long energy_delta = 0;
  46. if ((last == 0) || (millis() - last > 1000)) {
  47. current = read(0, _pivot);
  48. energy_delta = current * _voltage * (millis() - last) / 1000;
  49. _energy += energy_delta;
  50. last = millis();
  51. }
  52. if (index == 0) return current;
  53. if (index == 1) return current * _voltage;
  54. if (index == 2) return _energy;
  55. if (index == 3) return energy_delta;
  56. _error = SENSOR_ERROR_OUT_OF_RANGE;
  57. return 0;
  58. }
  59. protected:
  60. unsigned int readADC(unsigned char channel) {
  61. return analogRead(_gpio);
  62. }
  63. unsigned char _gpio;
  64. unsigned long _energy = 0;
  65. double _pivot = 0;
  66. };