ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
mcp9808.cpp
Go to the documentation of this file.
1#include "mcp9808.h"
2#include "esphome/core/log.h"
3
4namespace esphome {
5namespace mcp9808 {
6
7static const uint8_t MCP9808_REG_AMBIENT_TEMP = 0x05;
8static const uint8_t MCP9808_REG_MANUF_ID = 0x06;
9static const uint8_t MCP9808_REG_DEVICE_ID = 0x07;
10
11static const uint16_t MCP9808_MANUF_ID = 0x0054;
12static const uint16_t MCP9808_DEV_ID = 0x0400;
13
14static const uint8_t MCP9808_AMBIENT_CLEAR_FLAGS = 0x1F;
15static const uint8_t MCP9808_AMBIENT_CLEAR_SIGN = 0x0F;
16static const uint8_t MCP9808_AMBIENT_TEMP_NEGATIVE = 0x10;
17
18static const char *const TAG = "mcp9808";
19
21 uint16_t manu = 0;
22 if (!this->read_byte_16(MCP9808_REG_MANUF_ID, &manu) || manu != MCP9808_MANUF_ID) {
23 this->mark_failed();
24 ESP_LOGE(TAG, "Incorrect manufacturer ID (%X) for '%s'", manu, this->name_.c_str());
25 return;
26 }
27 uint16_t dev_id = 0;
28 if (!this->read_byte_16(MCP9808_REG_DEVICE_ID, &dev_id) || dev_id != MCP9808_DEV_ID) {
29 this->mark_failed();
30 ESP_LOGE(TAG, "Incorrect device ID (%X) for '%s'", dev_id, this->name_.c_str());
31 return;
32 }
33}
35 ESP_LOGCONFIG(TAG, "%s:", this->name_.c_str());
36 LOG_I2C_DEVICE(this);
37 if (this->is_failed()) {
38 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL_FOR, this->name_.c_str());
39 }
40 LOG_UPDATE_INTERVAL(this);
41 LOG_SENSOR(" ", "Temperature", this);
42}
44 uint16_t raw_temp;
45 if (!this->read_byte_16(MCP9808_REG_AMBIENT_TEMP, &raw_temp)) {
46 this->status_set_warning();
47 return;
48 }
49 if (raw_temp == 0xFFFF) {
50 this->status_set_warning();
51 return;
52 }
53
54 float temp = NAN;
55 uint8_t msb = (uint8_t) ((raw_temp & 0xff00) >> 8);
56 uint8_t lsb = raw_temp & 0x00ff;
57
58 msb = msb & MCP9808_AMBIENT_CLEAR_FLAGS;
59
60 if ((msb & MCP9808_AMBIENT_TEMP_NEGATIVE) == MCP9808_AMBIENT_TEMP_NEGATIVE) {
61 msb = msb & MCP9808_AMBIENT_CLEAR_SIGN;
62 temp = (256 - ((uint16_t) (msb) *16 + lsb / 16.0f)) * -1;
63 } else {
64 temp = (uint16_t) (msb) *16 + lsb / 16.0f;
65 }
66
67 if (std::isnan(temp)) {
68 this->status_set_warning();
69 return;
70 }
71
72 ESP_LOGD(TAG, "%s: Got temperature=%.4f°C", this->name_.c_str(), temp);
73 this->publish_state(temp);
75}
77
78} // namespace mcp9808
79} // namespace esphome
virtual void mark_failed()
Mark this component as failed.
bool is_failed() const
void status_set_warning(const char *message=nullptr)
void status_clear_warning()
constexpr const char * c_str() const
Definition string_ref.h:69
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:250
float get_setup_priority() const override
Definition mcp9808.cpp:76
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:45
u_int8_t raw_temp
const float DATA
For components that import data from directly connected sensors like DHT.
Definition component.cpp:50
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7