ESPHome 2026.11.0-dev
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
7ESPHOME_LOG_TAG(TAG, "mcp3221");
8
10 uint8_t data[2];
11 if (!this->status_comm_result(this->read(data, 2) == i2c::ERROR_OK)) {
12 ESP_LOGW(TAG, "Read failed");
13 return NAN;
14 }
15
16 uint16_t value = encode_uint16(data[0], data[1]);
17 float voltage = value * this->reference_voltage_ / 4096.0f;
18
19 return voltage;
20}
21
23 float v = this->sample();
24 this->publish_state(v);
25}
26
27} // namespace esphome::mcp3221
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
ErrorCode read(uint8_t *data, size_t len) const
reads an array of bytes from the device using an I2CBus
Definition i2c.h:175
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
@ ERROR_OK
No error found during execution of method.
Definition i2c_bus.h:15
ESPHOME_LOG_TAG(TAG, "mcp3221")
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:998