ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
max17048.cpp
Go to the documentation of this file.
1#include "max17048.h"
2#include "esphome/core/log.h"
3
5
6// MAX17048/MAX17049 1 and 2 cell fuel gauges with ModelGauge
7// Datasheet: https://www.analog.com/media/en/technical-documentation/data-sheets/MAX17048-MAX17049.pdf
8
9ESPHOME_LOG_TAG(TAG, "max17048");
10
11static constexpr uint8_t REG_VCELL = 0x02; // cell voltage
12static constexpr uint8_t REG_SOC = 0x04; // state of charge
13static constexpr uint8_t REG_VERSION = 0x08; // 0x001x
14static constexpr uint8_t REG_CRATE = 0x16; // charge rate, signed
15
16static constexpr uint16_t VERSION_MASK = 0xFFF0;
17static constexpr uint16_t VERSION_FAMILY = 0x0010;
18
19static constexpr float VCELL_VOLTS_PER_LSB = 78.125e-6f;
20static constexpr float SOC_PERCENT_PER_LSB = 1.0f / 256.0f;
21static constexpr float CRATE_PERCENT_PER_HOUR_PER_LSB = 0.208f;
22
24 uint16_t version;
25 if (!this->read_byte_16(REG_VERSION, &version)) {
26 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
27 return;
28 }
29 if ((version & VERSION_MASK) != VERSION_FAMILY) {
30 ESP_LOGW(TAG, "Unexpected version 0x%04X", version);
31 }
32}
33
34void MAX17048Component::update() {
35 bool ok = true;
36 uint16_t raw;
37 if (this->battery_voltage_sensor_ != nullptr) {
38 if (this->read_byte_16(REG_VCELL, &raw)) {
39 this->battery_voltage_sensor_->publish_state(raw * VCELL_VOLTS_PER_LSB);
40 } else {
41 ok = false;
42 }
43 }
44 if (this->battery_level_sensor_ != nullptr) {
45 if (this->read_byte_16(REG_SOC, &raw)) {
46 this->battery_level_sensor_->publish_state(raw * SOC_PERCENT_PER_LSB);
47 } else {
48 ok = false;
49 }
50 }
51 if (this->rate_sensor_ != nullptr) {
52 if (this->read_byte_16(REG_CRATE, &raw)) {
53 this->rate_sensor_->publish_state(static_cast<int16_t>(raw) * CRATE_PERCENT_PER_HOUR_PER_LSB);
54 } else {
55 ok = false;
56 }
57 }
58 if (ok) {
60 } else {
61 this->status_set_warning(LOG_STR("Register read failed"));
62 }
63}
64
65void MAX17048Component::dump_config() {
66 ESP_LOGCONFIG(TAG, "MAX17048:");
67 LOG_I2C_DEVICE(this);
68 LOG_UPDATE_INTERVAL(this);
69 LOG_SENSOR(" ", "Battery Voltage", this->battery_voltage_sensor_);
70 LOG_SENSOR(" ", "Battery Level", this->battery_level_sensor_);
71 LOG_SENSOR(" ", "Rate", this->rate_sensor_);
72}
73
74} // namespace esphome::max17048
uint8_t raw[35]
Definition bl0939.h:0
void mark_failed()
Mark this component as failed.
virtual void setup()
Where the component's initialization should happen.
Definition component.cpp:84
void status_clear_warning()
Definition component.h:291
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:249
ESPHOME_LOG_TAG(TAG, "max17048")