ESPHome 2025.12.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
4namespace esphome {
5namespace bh1900nux {
6
7static const char *const 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(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_uint16(temperature_raw[0], temperature_raw[1]);
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 bh1900nux
54} // namespace esphome
virtual 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:44
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:35
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:75
ErrorCode
Error codes returned by I2CBus and I2CDevice methods.
Definition i2c_bus.h:31
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:33
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:394