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.

94 lines
2.7 KiB

  1. // -----------------------------------------------------------------------------
  2. // SHT3X Sensor over I2C (Wemos)
  3. // Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #if SENSOR_SUPPORT && SHT3X_I2C_SUPPORT
  6. #pragma once
  7. #undef I2C_SUPPORT
  8. #define I2C_SUPPORT 1 // Explicitly request I2C support.
  9. #include <Arduino.h>
  10. #include "../utils.h"
  11. #include "I2CSensor.h"
  12. class SHT3XI2CSensor : public I2CSensor {
  13. public:
  14. // ---------------------------------------------------------------------
  15. // Public
  16. // ---------------------------------------------------------------------
  17. SHT3XI2CSensor(): I2CSensor() {
  18. _sensor_id = SENSOR_SHT3X_I2C_ID;
  19. _count = 2;
  20. }
  21. // ---------------------------------------------------------------------
  22. // Sensor API
  23. // ---------------------------------------------------------------------
  24. // Initialization method, must be idempotent
  25. void begin() {
  26. if (!_dirty) return;
  27. // I2C auto-discover
  28. unsigned char addresses[] = {0x45};
  29. _address = _begin_i2c(_address, sizeof(addresses), addresses);
  30. if (_address == 0) return;
  31. _ready = true;
  32. _dirty = false;
  33. }
  34. // Descriptive name of the sensor
  35. String description() {
  36. char buffer[25];
  37. snprintf(buffer, sizeof(buffer), "SHT3X @ I2C (0x%02X)", _address);
  38. return String(buffer);
  39. }
  40. // Type for slot # index
  41. unsigned char type(unsigned char index) {
  42. if (index == 0) return MAGNITUDE_TEMPERATURE;
  43. if (index == 1) return MAGNITUDE_HUMIDITY;
  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. nice_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. if (index == 0) return _temperature;
  60. if (index == 1) return _humidity;
  61. return 0;
  62. }
  63. protected:
  64. double _temperature = 0;
  65. unsigned char _humidity = 0;
  66. };
  67. #endif // SENSOR_SUPPORT && SHT3X_I2C_SUPPORT