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.

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