ESPHome 2026.5.0b1
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::mcp9808 {
5
6static const uint8_t MCP9808_REG_AMBIENT_TEMP = 0x05;
7static const uint8_t MCP9808_REG_MANUF_ID = 0x06;
8static const uint8_t MCP9808_REG_DEVICE_ID = 0x07;
9
10static const uint16_t MCP9808_MANUF_ID = 0x0054;
11static const uint16_t MCP9808_DEV_ID = 0x0400;
12
13static const uint8_t MCP9808_AMBIENT_CLEAR_FLAGS = 0x1F;
14static const uint8_t MCP9808_AMBIENT_CLEAR_SIGN = 0x0F;
15static const uint8_t MCP9808_AMBIENT_TEMP_NEGATIVE = 0x10;
16
17static const char *const TAG = "mcp9808";
18
20 uint16_t manu = 0;
21 if (!this->read_byte_16(MCP9808_REG_MANUF_ID, &manu) || manu != MCP9808_MANUF_ID) {
22 this->mark_failed();
23 ESP_LOGE(TAG, "Incorrect manufacturer ID (%X) for '%s'", manu, this->name_.c_str());
24 return;
25 }
26 uint16_t dev_id = 0;
27 if (!this->read_byte_16(MCP9808_REG_DEVICE_ID, &dev_id) || dev_id != MCP9808_DEV_ID) {
28 this->mark_failed();
29 ESP_LOGE(TAG, "Incorrect device ID (%X) for '%s'", dev_id, this->name_.c_str());
30 return;
31 }
32}
34 ESP_LOGCONFIG(TAG, "%s:", this->name_.c_str());
35 LOG_I2C_DEVICE(this);
36 if (this->is_failed()) {
37 ESP_LOGE(TAG, ESP_LOG_MSG_COMM_FAIL_FOR, this->name_.c_str());
38 }
39 LOG_UPDATE_INTERVAL(this);
40 LOG_SENSOR(" ", "Temperature", this);
41}
43 uint16_t raw_temp;
44 if (!this->read_byte_16(MCP9808_REG_AMBIENT_TEMP, &raw_temp)) {
45 this->status_set_warning();
46 return;
47 }
48 if (raw_temp == 0xFFFF) {
49 this->status_set_warning();
50 return;
51 }
52
53 float temp = NAN;
54 uint8_t msb = (uint8_t) ((raw_temp & 0xff00) >> 8);
55 uint8_t lsb = raw_temp & 0x00ff;
56
57 msb = msb & MCP9808_AMBIENT_CLEAR_FLAGS;
58
59 if ((msb & MCP9808_AMBIENT_TEMP_NEGATIVE) == MCP9808_AMBIENT_TEMP_NEGATIVE) {
60 msb = msb & MCP9808_AMBIENT_CLEAR_SIGN;
61 temp = (256 - ((uint16_t) (msb) *16 + lsb / 16.0f)) * -1;
62 } else {
63 temp = (uint16_t) (msb) *16 + lsb / 16.0f;
64 }
65
66 if (std::isnan(temp)) {
67 this->status_set_warning();
68 return;
69 }
70
71 ESP_LOGD(TAG, "%s: Got temperature=%.4f°C", this->name_.c_str(), temp);
72 this->publish_state(temp);
74}
75
76} // namespace esphome::mcp9808
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:284
void status_clear_warning()
Definition component.h:306
constexpr const char * c_str() const
Definition string_ref.h:73
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:249
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
u_int8_t raw_temp