ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
mcp4728.cpp
Go to the documentation of this file.
1#include "mcp4728.h"
2
4#include "esphome/core/log.h"
5
6namespace esphome::mcp4728 {
7
8ESPHOME_LOG_TAG(TAG, "mcp4728");
9
11 auto err = this->write(nullptr, 0);
12 if (err != i2c::ERROR_OK) {
13 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
14 return;
15 }
16}
17
19 ESP_LOGCONFIG(TAG, "MCP4728:");
20 LOG_I2C_DEVICE(this);
21}
22
24 if (this->update_) {
25 this->update_ = false;
26 if (this->store_in_eeprom_) {
27 if (!this->seq_write_()) {
28 this->status_set_error();
29 } else {
30 this->status_clear_error();
31 }
32 } else {
33 if (!this->multi_write_()) {
34 this->status_set_error();
35 } else {
36 this->status_clear_error();
37 }
38 }
39 }
40}
41
42void MCP4728Component::write_channel(uint8_t channel, float state) {
43 auto value = static_cast<uint16_t>(roundf(state * 4095));
44 ESP_LOGV(TAG, "Setting MCP4728 channel %c to %d!", 'A' + channel, value);
45 this->reg_[channel].data = value;
46 this->update_ = true;
47}
48
50 i2c::ErrorCode err[4];
51 for (uint8_t i = 0; i < 4; ++i) {
52 uint8_t wd[3];
53 wd[0] = ((uint8_t) CMD::MULTI_WRITE | (i << 1)) & 0xFE;
54 wd[1] = ((uint8_t) reg_[i].vref << 7) | ((uint8_t) reg_[i].pd << 5) | ((uint8_t) reg_[i].gain << 4) |
55 (reg_[i].data >> 8);
56 wd[2] = reg_[i].data & 0xFF;
57 err[i] = this->write(wd, sizeof(wd));
58 }
59 bool ok = true;
60 for (auto &e : err) {
61 if (e != i2c::ERROR_OK) {
62 ok = false;
63 break;
64 }
65 }
66 return ok;
67}
68
70 uint8_t wd[9];
71 wd[0] = (uint8_t) CMD::SEQ_WRITE;
72 for (uint8_t i = 0; i < 4; i++) {
73 wd[i * 2 + 1] = ((uint8_t) reg_[i].vref << 7) | ((uint8_t) reg_[i].pd << 5) | ((uint8_t) reg_[i].gain << 4) |
74 (reg_[i].data >> 8);
75 wd[i * 2 + 2] = reg_[i].data & 0xFF;
76 }
77 auto err = this->write(wd, sizeof(wd));
78 return err == i2c::ERROR_OK;
79}
80
82 MCP4728PwrDown pd) {
83 this->reg_[channel].vref = vref;
84 this->reg_[channel].pd = pd;
85 this->reg_[channel].gain = gain;
86 this->update_ = true;
87}
88
89} // namespace esphome::mcp4728
void mark_failed()
Mark this component as failed.
void status_clear_error()
Definition component.h:315
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
void configure_channel(MCP4728ChannelIdx channel, MCP4728Vref vref, MCP4728Gain gain, MCP4728PwrDown pd)
Definition mcp4728.cpp:81
void write_channel(uint8_t channel, float state)
Definition mcp4728.cpp:42
bool state
Definition fan.h:2
AlsGain501 gain
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
ESPHOME_LOG_TAG(TAG, "mcp4728")
uint32_t value
Definition hal.cpp:41