ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
bh1900nux.cpp
Go to the documentation of this file.
1#include "esphome/core/log.h"
2#include "bh1900nux.h"
3
5
6static const char *const TAG = "bh1900nux.sensor";
7
8// I2C Registers
9static const uint8_t TEMPERATURE_REG = 0x00;
10static const uint8_t CONFIG_REG = 0x01; // Not used and supported yet
11static const uint8_t TEMPERATURE_LOW_REG = 0x02; // Not used and supported yet
12static const uint8_t TEMPERATURE_HIGH_REG = 0x03; // Not used and supported yet
13static const uint8_t SOFT_RESET_REG = 0x04;
14
15// I2C Command payloads
16static const uint8_t SOFT_RESET_PAYLOAD = 0x01; // Soft Reset value
17
18static const float SENSOR_RESOLUTION = 0.0625f; // Sensor resolution per bit in degrees celsius
19
21 // Initialize I2C device
22 i2c::ErrorCode result_code =
23 this->write_register(SOFT_RESET_REG, &SOFT_RESET_PAYLOAD, 1); // Software Reset to check communication
24 if (result_code != i2c::ERROR_OK) {
25 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
26 return;
27 }
28}
29
31 uint8_t temperature_raw[2];
32 if (this->read_register(TEMPERATURE_REG, temperature_raw, 2) != i2c::ERROR_OK) {
33 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL);
34 return;
35 }
36
37 // Combined raw value, unsigned and unaligned 16 bit
38 // Temperature is represented in just 12 bits, shift needed
39 int16_t raw_temperature_register_value = encode_uint16(temperature_raw[0], temperature_raw[1]);
40 raw_temperature_register_value >>= 4;
41 float temperature_value = raw_temperature_register_value * SENSOR_RESOLUTION; // Apply sensor resolution
42
43 this->publish_state(temperature_value);
44}
45
47 LOG_SENSOR("", "BH1900NUX", this);
48 LOG_I2C_DEVICE(this);
49 LOG_UPDATE_INTERVAL(this);
50}
51
52} // 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:34
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:25
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:12
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:14
constexpr uint16_t encode_uint16(uint8_t msb, uint8_t lsb)
Encode a 16-bit value given the most and least significant byte.
Definition helpers.h:859