ESPHome 2026.8.0-dev
Loading...
Searching...
No Matches
internal_temperature_esp32.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "esphome/core/log.h"
5
6#include <soc/soc_caps.h>
7
8#if defined(USE_ESP32_VARIANT_ESP32)
9// there is no official API available on the original ESP32
10extern "C" {
12}
13#elif SOC_TEMP_SENSOR_SUPPORTED
14#include "driver/temperature_sensor.h"
15#endif
16
18
19static const char *const TAG = "internal_temperature.esp32";
20
22 float temperature = NAN;
23 bool success = false;
24#if defined(USE_ESP32_VARIANT_ESP32)
25 uint8_t raw = temprature_sens_read();
26 ESP_LOGV(TAG, "Raw temperature value: %d", raw);
27 temperature = (raw - 32) / 1.8f;
28 success = (raw != 128);
29#elif SOC_TEMP_SENSOR_SUPPORTED
30 esp_err_t result = temperature_sensor_get_celsius(this->tsens_, &temperature);
31 success = (result == ESP_OK);
32 if (!success) {
33 ESP_LOGE(TAG, "Reading failed (%d)", result);
34 }
35#endif // USE_ESP32_VARIANT
36
37 if (success && std::isfinite(temperature)) {
38 this->publish_state(temperature);
39 } else {
40 ESP_LOGD(TAG, "Ignoring invalid temperature (success=%d, value=%.1f)", success, temperature);
41 if (!this->has_state()) {
42 this->publish_state(NAN);
43 }
44 }
45}
46
48#if SOC_TEMP_SENSOR_SUPPORTED
49 temperature_sensor_config_t tsens_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80);
50
51 esp_err_t result = temperature_sensor_install(&tsens_config, &this->tsens_);
52 if (result != ESP_OK) {
53 ESP_LOGE(TAG, "Install failed (%d)", result);
54 this->mark_failed();
55 return;
56 }
57
58 result = temperature_sensor_enable(this->tsens_);
59 if (result != ESP_OK) {
60 ESP_LOGE(TAG, "Enabling failed (%d)", result);
61 this->mark_failed();
62 return;
63 }
64#endif // USE_ESP32_VARIANT
65}
66
67} // namespace esphome::internal_temperature
68
69#endif // USE_ESP32
uint8_t raw[35]
Definition bl0939.h:0
void mark_failed()
Mark this component as failed.
bool has_state() const
void publish_state(float state)
Publish a new state to the front-end.
Definition sensor.cpp:68
uint8_t temprature_sens_read()
uint16_t temperature
Definition sun_gtil2.cpp:12