ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
bh1900nux.cpp
Go to the documentation of this file.
2#include "esphome/core/log.h"
3#include "bh1900nux.h"
4
6
7ESPHOME_LOG_TAG(TAG, "bh1900nux.sensor");
8
9// I2C Registers
10static const uint8_t TEMPERATURE_REG = 0x00;
11static const uint8_t CONFIG_REG = 0x01; // Not used and supported yet
12static const uint8_t TEMPERATURE_LOW_REG = 0x02; // Not used and supported yet
13static const uint8_t TEMPERATURE_HIGH_REG = 0x03; // Not used and supported yet
14static const uint8_t SOFT_RESET_REG = 0x04;
15
16// I2C Command payloads
17static const uint8_t SOFT_RESET_PAYLOAD = 0x01; // Soft Reset value
18
19static const float SENSOR_RESOLUTION = 0.0625f; // Sensor resolution per bit in degrees celsius
20
22 // Initialize I2C device
23 i2c::ErrorCode result_code =
24 this->write_register(SOFT_RESET_REG, &SOFT_RESET_PAYLOAD, 1); // Software Reset to check communication
25 if (result_code != i2c::ERROR_OK) {
26 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
27 return;
28 }
29}
30
32 uint8_t temperature_raw[2];
33 if (this->read_register(TEMPERATURE_REG, temperature_raw, 2) != i2c::ERROR_OK) {
34 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
35 return;
36 }
37
38 // Combined raw value, unsigned and unaligned 16 bit
39 // Temperature is represented in just 12 bits, shift needed
40 int16_t raw_temperature_register_value = encode_value<int16_t>(temperature_raw);
41 raw_temperature_register_value >>= 4;
42 float temperature_value = raw_temperature_register_value * SENSOR_RESOLUTION; // Apply sensor resolution
43
44 this->publish_state(temperature_value);
45}
46
48 LOG_SENSOR("", "BH1900NUX", this);
49 LOG_I2C_DEVICE(this);
50 LOG_UPDATE_INTERVAL(this);
51}
52
53} // namespace esphome::bh1900nux
void mark_failed()
Mark this component as failed.
ErrorCode write_register(uint8_t a_register, const uint8_t *data, size_t len) const
writes an array of bytes to a specific register in the I²C device
Definition i2c.cpp:37
ErrorCode read_register(uint8_t a_register, uint8_t *data, size_t len)
reads an array of bytes from a specific register in the I²C device
Definition i2c.cpp:28
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
ESPHOME_LOG_TAG(TAG, "bh1900nux.sensor")
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:13
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
constexpr T encode_value(const uint8_t *bytes)
Encode a value from its constituent bytes (from most to least significant) in an array with length si...
Definition helpers.h:1019