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.

79 lines
2.1 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. // Prepare GPIO
  14. pinMode(gpio, INPUT);
  15. // warmup
  16. read(EMON_ANALOG_WARMUP_VALUE, EMON_ANALOG_WARMUP_MODE, _gpio);
  17. }
  18. // Descriptive name of the sensor
  19. String name() {
  20. char buffer[20];
  21. snprintf(buffer, sizeof(buffer), "ANALOG EMON @ GPIO%d", _gpio);
  22. return String(buffer);
  23. }
  24. // Descriptive name of the slot # index
  25. String slot(unsigned char index) {
  26. return name();
  27. }
  28. // Type for slot # index
  29. magnitude_t type(unsigned char index) {
  30. _error = SENSOR_ERROR_OK;
  31. if (index == 0) return MAGNITUDE_CURRENT;
  32. if (index == 1) return MAGNITUDE_POWER_APPARENT;
  33. _error = SENSOR_ERROR_OUT_OF_RANGE;
  34. return MAGNITUDE_NONE;
  35. }
  36. // Current value for slot # index
  37. double value(unsigned char index) {
  38. _error = SENSOR_ERROR_OK;
  39. // Cache the value
  40. static unsigned long last = 0;
  41. static double current = 0;
  42. if ((last == 0) || (millis() - last > 1000)) {
  43. current = read(EMON_ANALOG_READ_VALUE, EMON_ANALOG_READ_MODE, _gpio);
  44. last = millis();
  45. }
  46. if (index == 0) return current;
  47. if (index == 1) return current * _voltage;
  48. _error = SENSOR_ERROR_OUT_OF_RANGE;
  49. return 0;
  50. }
  51. protected:
  52. unsigned int readADC(unsigned char port) {
  53. return analogRead(port);
  54. }
  55. unsigned char _gpio;
  56. };