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.

87 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. _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 == 0) return MAGNITUDE_TEMPERATURE;
  39. if (index == 1) return MAGNITUDE_HUMIDITY;
  40. return MAGNITUDE_NONE;
  41. }
  42. // Pre-read hook (usually to populate registers with up-to-date data)
  43. void pre() {
  44. _error = SENSOR_ERROR_OK;
  45. unsigned char buffer[6];
  46. i2c_write_uint8(_address, 0x2C, 0x06);
  47. delay(500);
  48. i2c_read_buffer(_address, buffer, 6);
  49. // cTemp msb, cTemp lsb, cTemp crc, humidity msb, humidity lsb, humidity crc
  50. _temperature = ((((buffer[0] * 256.0) + buffer[1]) * 175) / 65535.0) - 45;
  51. _humidity = ((((buffer[3] * 256.0) + buffer[4]) * 100) / 65535.0);
  52. }
  53. // Current value for slot # index
  54. double value(unsigned char index) {
  55. if (index == 0) return _temperature;
  56. if (index == 1) return _humidity;
  57. return 0;
  58. }
  59. protected:
  60. double _temperature = 0;
  61. unsigned char _humidity = 0;
  62. };
  63. #endif // SENSOR_SUPPORT && SHT3X_I2C_SUPPORT