ESPHome 2026.11.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::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
17ESPHOME_LOG_TAG(TAG, "mcp9808");
18
20 uint16_t manu = 0;
21 if (!this->read_byte_16(MCP9808_REG_MANUF_ID, &manu)) {
22 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
23 return;
24 }
25 if (manu != MCP9808_MANUF_ID) {
26 ESP_LOGE(TAG, "Incorrect manufacturer ID (%X) for '%s'", manu, LOG_STR_ARG(this->get_log_name()));
27 this->mark_failed(LOG_STR("Wrong chip ID"));
28 return;
29 }
30 uint16_t dev_id = 0;
31 if (!this->read_byte_16(MCP9808_REG_DEVICE_ID, &dev_id)) {
32 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
33 return;
34 }
35 if (dev_id != MCP9808_DEV_ID) {
36 ESP_LOGE(TAG, "Incorrect device ID (%X) for '%s'", dev_id, LOG_STR_ARG(this->get_log_name()));
37 this->mark_failed(LOG_STR("Wrong chip ID"));
38 return;
39 }
40}
42 ESP_LOGCONFIG(TAG, "%s:", LOG_STR_ARG(this->get_log_name()));
43 LOG_I2C_DEVICE(this);
44 LOG_UPDATE_INTERVAL(this);
45 LOG_SENSOR(" ", "Temperature", this);
46}
48 uint16_t raw_temp;
49 if (!this->read_byte_16(MCP9808_REG_AMBIENT_TEMP, &raw_temp)) {
50 this->status_set_warning();
51 return;
52 }
53 if (raw_temp == 0xFFFF) {
54 this->status_set_warning();
55 return;
56 }
57
58 float temp = NAN;
59 uint8_t msb = (uint8_t) ((raw_temp & 0xff00) >> 8);
60 uint8_t lsb = raw_temp & 0x00ff;
61
62 msb = msb & MCP9808_AMBIENT_CLEAR_FLAGS;
63
64 if ((msb & MCP9808_AMBIENT_TEMP_NEGATIVE) == MCP9808_AMBIENT_TEMP_NEGATIVE) {
65 msb = msb & MCP9808_AMBIENT_CLEAR_SIGN;
66 temp = (256 - ((uint16_t) (msb) * 16 + lsb / 16.0f)) * -1;
67 } else {
68 temp = (uint16_t) (msb) * 16 + lsb / 16.0f;
69 }
70
71 if (!this->status_comm_result(!std::isnan(temp), nullptr))
72 return;
73
74 ESP_LOGD(TAG, "%s: Got temperature=%.4f°C", LOG_STR_ARG(this->get_log_name()), temp);
75 this->publish_state(temp);
76}
77
78} // namespace esphome::mcp9808
void mark_failed()
Mark this component as failed.
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
const LogString * get_log_name() const
Get the name for a "%s" log argument (LOG_STR_ARG).
bool read_byte_16(uint8_t a_register, uint16_t *data)
Definition i2c.h:281
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:65
u_int8_t raw_temp
ESPHOME_LOG_TAG(TAG, "mcp9808")