ESPHome 2026.5.1
Loading...
Searching...
No Matches
mcp3221_sensor.cpp
Go to the documentation of this file.
1#include "mcp3221_sensor.h"
2#include "esphome/core/hal.h"
3#include "esphome/core/log.h"
4
5namespace esphome::mcp3221 {
6
7static const char *const TAG = "mcp3221";
8
10 uint8_t data[2];
11 if (this->read(data, 2) != i2c::ERROR_OK) {
12 ESP_LOGW(TAG, "Read failed");
13 this->status_set_warning();
14 return NAN;
15 }
17
18 uint16_t value = encode_uint16(data[0], data[1]);
19 float voltage = value * this->reference_voltage_ / 4096.0f;
20
21 return voltage;
22}
23
25 float v = this->sample();
26 this->publish_state(v);
27}
28
29} // namespace esphome::mcp3221
void status_clear_warning()
Definition component.h:306
ErrorCode read(uint8_t *data, size_t len) const
reads an array of bytes from the device using an I2CBus
Definition i2c.h:163
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
@ 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