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