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.

93 lines
2.8 KiB

  1. // -----------------------------------------------------------------------------
  2. // SHT3X Sensor over I2C (Wemos)
  3. // Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #if SENSOR_SUPPORT && SHT3X_I2C_SUPPORT
  6. #pragma once
  7. #include "Arduino.h"
  8. #include "I2CSensor.h"
  9. class SHT3XI2CSensor : public I2CSensor {
  10. public:
  11. // ---------------------------------------------------------------------
  12. // Public
  13. // ---------------------------------------------------------------------
  14. SHT3XI2CSensor(): I2CSensor() {
  15. _sensor_id = SENSOR_SHT3X_I2C_ID;
  16. _count = 2;
  17. }
  18. // ---------------------------------------------------------------------
  19. // Sensor API
  20. // ---------------------------------------------------------------------
  21. // Initialization method, must be idempotent
  22. void begin() {
  23. if (!_dirty) return;
  24. _dirty = false;
  25. // I2C auto-discover
  26. unsigned char addresses[] = {0x45};
  27. _address = _begin_i2c(_address, sizeof(addresses), addresses);
  28. if (_address == 0) return;
  29. }
  30. // Descriptive name of the sensor
  31. String description() {
  32. char buffer[25];
  33. snprintf(buffer, sizeof(buffer), "SHT3X @ I2C (0x%02X)", _address);
  34. return String(buffer);
  35. }
  36. // Type for slot # index
  37. unsigned char type(unsigned char index) {
  38. if (index < _count) {
  39. _error = SENSOR_ERROR_OK;
  40. if (index == 0) return MAGNITUDE_TEMPERATURE;
  41. if (index == 1) return MAGNITUDE_HUMIDITY;
  42. }
  43. _error = SENSOR_ERROR_OUT_OF_RANGE;
  44. return MAGNITUDE_NONE;
  45. }
  46. // Pre-read hook (usually to populate registers with up-to-date data)
  47. void pre() {
  48. _error = SENSOR_ERROR_OK;
  49. unsigned char buffer[6];
  50. i2c_write_uint8(_address, 0x2C, 0x06);
  51. delay(500);
  52. i2c_read_buffer(_address, buffer, 6);
  53. // cTemp msb, cTemp lsb, cTemp crc, humidity msb, humidity lsb, humidity crc
  54. _temperature = ((((buffer[0] * 256.0) + buffer[1]) * 175) / 65535.0) - 45;
  55. _humidity = ((((buffer[3] * 256.0) + buffer[4]) * 100) / 65535.0);
  56. }
  57. // Current value for slot # index
  58. double value(unsigned char index) {
  59. _error = SENSOR_ERROR_OK;
  60. if (index == 0) return _temperature;
  61. if (index == 1) return _humidity;
  62. _error = SENSOR_ERROR_OUT_OF_RANGE;
  63. return 0;
  64. }
  65. protected:
  66. double _temperature = 0;
  67. unsigned char _humidity = 0;
  68. };
  69. #endif // SENSOR_SUPPORT && SHT3X_I2C_SUPPORT