ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
hyt271.cpp
Go to the documentation of this file.
1#include "hyt271.h"
2#include "esphome/core/log.h"
3#include "esphome/core/hal.h"
4
5namespace esphome::hyt271 {
6
7ESPHOME_LOG_TAG(TAG, "hyt271");
8
9static constexpr uint32_t WAIT_CONVERT_TIMEOUT_ID = 0;
10
11static const uint8_t HYT271_ADDRESS = 0x28;
12
14 ESP_LOGCONFIG(TAG, "HYT271:");
15 LOG_I2C_DEVICE(this);
16 LOG_UPDATE_INTERVAL(this);
17 LOG_SENSOR(" ", "Temperature", this->temperature_);
18 LOG_SENSOR(" ", "Humidity", this->humidity_);
19}
21 uint8_t raw_data[4] = {0, 0, 0, 0};
22
23 if (this->write(&raw_data[0], 0) != i2c::ERROR_OK) {
24 this->status_set_warning();
25 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
26 return;
27 }
28 this->set_timeout(WAIT_CONVERT_TIMEOUT_ID, 50, [this]() {
29 uint8_t raw_data[4];
30 if (this->read(raw_data, 4) != i2c::ERROR_OK) {
31 this->status_set_warning();
32 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
33 return;
34 }
35 uint16_t raw_temperature = ((raw_data[2] << 8) | raw_data[3]) >> 2;
36 uint16_t raw_humidity = ((raw_data[0] & 0x3F) << 8) | raw_data[1];
37
38 float temperature = ((float(raw_temperature)) * (165.0f / 16383.0f)) - 40.0f;
39 float humidity = (float(raw_humidity)) * (100.0f / 16383.0f);
40
41 ESP_LOGD(TAG, "Got Temperature=%.1f°C Humidity=%.1f%%", temperature, humidity);
42
43 if (this->temperature_ != nullptr)
44 this->temperature_->publish_state(temperature);
45 if (this->humidity_ != nullptr)
46 this->humidity_->publish_state(humidity);
48 });
49}
50} // namespace esphome::hyt271
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void status_clear_warning()
Definition component.h:296
void update() override
Update the sensor values (temperature+humidity).
Definition hyt271.cpp:20
sensor::Sensor * temperature_
Definition hyt271.h:19
sensor::Sensor * humidity_
Definition hyt271.h:20
ErrorCode write(const uint8_t *data, size_t len) const
writes an array of bytes to a device using an I2CBus
Definition i2c.h:195
ErrorCode read(uint8_t *data, size_t len) const
reads an array of bytes from the device using an I2CBus
Definition i2c.h:175
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
ESPHOME_LOG_TAG(TAG, "hyt271")
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
static void uint32_t
uint16_t temperature
Definition sun_gtil2.cpp:12