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.

89 lines
2.6 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. // I2C auto-discover
  25. unsigned char addresses[] = {0x45};
  26. _address = _begin_i2c(_address, sizeof(addresses), addresses);
  27. if (_address == 0) return;
  28. _ready = true;
  29. _dirty = false;
  30. }
  31. // Descriptive name of the sensor
  32. String description() {
  33. char buffer[25];
  34. snprintf(buffer, sizeof(buffer), "SHT3X @ I2C (0x%02X)", _address);
  35. return String(buffer);
  36. }
  37. // Type for slot # index
  38. unsigned char type(unsigned char index) {
  39. if (index == 0) return MAGNITUDE_TEMPERATURE;
  40. if (index == 1) return MAGNITUDE_HUMIDITY;
  41. return MAGNITUDE_NONE;
  42. }
  43. // Pre-read hook (usually to populate registers with up-to-date data)
  44. void pre() {
  45. _error = SENSOR_ERROR_OK;
  46. unsigned char buffer[6];
  47. i2c_write_uint8(_address, 0x2C, 0x06);
  48. delay(500);
  49. i2c_read_buffer(_address, buffer, 6);
  50. // cTemp msb, cTemp lsb, cTemp crc, humidity msb, humidity lsb, humidity crc
  51. _temperature = ((((buffer[0] * 256.0) + buffer[1]) * 175) / 65535.0) - 45;
  52. _humidity = ((((buffer[3] * 256.0) + buffer[4]) * 100) / 65535.0);
  53. }
  54. // Current value for slot # index
  55. double value(unsigned char index) {
  56. if (index == 0) return _temperature;
  57. if (index == 1) return _humidity;
  58. return 0;
  59. }
  60. protected:
  61. double _temperature = 0;
  62. unsigned char _humidity = 0;
  63. };
  64. #endif // SENSOR_SUPPORT && SHT3X_I2C_SUPPORT