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
3.0 KiB

  1. // -----------------------------------------------------------------------------
  2. // DHT Sensor
  3. // -----------------------------------------------------------------------------
  4. #pragma once
  5. #include "Arduino.h"
  6. #include "BaseSensor.h"
  7. #include <OneWire.h>
  8. #include <DallasTemperature.h>
  9. #define DS18B20_OK 0
  10. #define DS18B20_NOT_FOUND 1
  11. #define DS18B20_OUT_OF_RANGE 2
  12. #define DS18B20_CONVERSION_ERROR 3
  13. class DS18B20Sensor : public BaseSensor {
  14. public:
  15. DS18B20Sensor(unsigned char gpio, bool pull_up = false): BaseSensor() {
  16. _gpio = gpio;
  17. if (pull_up) pinMode(_gpio, INPUT_PULLUP);
  18. init();
  19. }
  20. // Pre-read hook (usually to populate registers with up-to-date data)
  21. void pre() {
  22. _device->requestTemperatures();
  23. // TODO: enable?
  24. /*
  25. while (!_device->isConversionComplete()) {
  26. delay(1);
  27. }
  28. */
  29. }
  30. // Descriptive name of the sensor
  31. String name() {
  32. char buffer[20];
  33. snprintf(buffer, sizeof(buffer), "DS18B20 %s@ GPIO%d",
  34. _device->isParasitePowerMode() ? "(P) " : "",
  35. _gpio
  36. );
  37. return String(buffer);
  38. }
  39. // Descriptive name of the slot # index
  40. String slot(unsigned char index) {
  41. if (index < _count) {
  42. DeviceAddress address;
  43. _device->getAddress(address, index);
  44. char buffer[40];
  45. snprintf(buffer, sizeof(buffer), "%02X%02X%02X%02X%02X%02X%02X%02X @ %s",
  46. address[0], address[1], address[2], address[3],
  47. address[4], address[5], address[6], address[7],
  48. name().c_str()
  49. );
  50. return String(buffer);
  51. }
  52. _error = DS18B20_OUT_OF_RANGE;
  53. return String();
  54. }
  55. // Type for slot # index
  56. magnitude_t type(unsigned char index) {
  57. if (index < _count) return MAGNITUDE_TEMPERATURE;
  58. _error = DS18B20_OUT_OF_RANGE;
  59. return MAGNITUDE_NONE;
  60. }
  61. // Current value for slot # index
  62. double value(unsigned char index) {
  63. if (index < _count) {
  64. double t = _device->getTempCByIndex(index);
  65. if (t != DEVICE_DISCONNECTED_C) {
  66. _error = DS18B20_OK;
  67. return t;
  68. }
  69. _error = DS18B20_CONVERSION_ERROR;
  70. }
  71. _error = DS18B20_OUT_OF_RANGE;
  72. return 0;
  73. }
  74. protected:
  75. void init() {
  76. OneWire * wire = new OneWire(_gpio);
  77. _device = new DallasTemperature(wire);
  78. _device->begin();
  79. _device->setWaitForConversion(false);
  80. _count = _device->getDeviceCount();
  81. if (_count == 0) _error = DS18B20_NOT_FOUND;
  82. }
  83. unsigned char _gpio;
  84. DallasTemperature * _device;
  85. };