ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
adc_sensor_esp32.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2
3#include "adc_sensor.h"
4#include "esphome/core/log.h"
5#include <cinttypes>
6
7namespace esphome::adc {
8
9static const char *const TAG = "adc";
10
11adc_oneshot_unit_handle_t ADCSensor::shared_adc_handles[2] = {nullptr, nullptr};
12
13const LogString *attenuation_to_str(adc_atten_t attenuation) {
14 switch (attenuation) {
15 case ADC_ATTEN_DB_0:
16 return LOG_STR("0 dB");
17 case ADC_ATTEN_DB_2_5:
18 return LOG_STR("2.5 dB");
19 case ADC_ATTEN_DB_6:
20 return LOG_STR("6 dB");
21 case ADC_ATTEN_DB_12_COMPAT:
22 return LOG_STR("12 dB");
23 default:
24 return LOG_STR("Unknown Attenuation");
25 }
26}
27
28const LogString *adc_unit_to_str(adc_unit_t unit) {
29 switch (unit) {
30 case ADC_UNIT_1:
31 return LOG_STR("ADC1");
32 case ADC_UNIT_2:
33 return LOG_STR("ADC2");
34 default:
35 return LOG_STR("Unknown ADC Unit");
36 }
37}
38
40 // Check if another sensor already initialized this ADC unit
41 if (ADCSensor::shared_adc_handles[this->adc_unit_] == nullptr) {
42 adc_oneshot_unit_init_cfg_t init_config = {}; // Zero initialize
43 init_config.unit_id = this->adc_unit_;
44 init_config.ulp_mode = ADC_ULP_MODE_DISABLE;
45#if USE_ESP32_VARIANT_ESP32C2 || USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 || \
46 USE_ESP32_VARIANT_ESP32C6 || USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2
47 init_config.clk_src = ADC_DIGI_CLK_SRC_DEFAULT;
48#endif // USE_ESP32_VARIANT_ESP32C2 || USE_ESP32_VARIANT_ESP32C3 || USE_ESP32_VARIANT_ESP32C5 ||
49 // USE_ESP32_VARIANT_ESP32C6 || USE_ESP32_VARIANT_ESP32C61 || USE_ESP32_VARIANT_ESP32H2
50 esp_err_t err = adc_oneshot_new_unit(&init_config, &ADCSensor::shared_adc_handles[this->adc_unit_]);
51 if (err != ESP_OK) {
52 ESP_LOGE(TAG, "Error initializing %s: %d", LOG_STR_ARG(adc_unit_to_str(this->adc_unit_)), err);
53 this->mark_failed();
54 return;
55 }
56 }
57 this->adc_handle_ = ADCSensor::shared_adc_handles[this->adc_unit_];
58
60
61 adc_oneshot_chan_cfg_t config = {
62 .atten = this->attenuation_,
63 .bitwidth = ADC_BITWIDTH_DEFAULT,
64 };
65 esp_err_t err = adc_oneshot_config_channel(this->adc_handle_, this->channel_, &config);
66 if (err != ESP_OK) {
67 ESP_LOGE(TAG, "Error configuring channel: %d", err);
68 this->mark_failed();
69 return;
70 }
71 this->setup_flags_.config_complete = true;
72
73 // Initialize ADC calibration
74 if (this->calibration_handle_ == nullptr) {
75 adc_cali_handle_t handle = nullptr;
76
77#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
78 adc_cali_curve_fitting_config_t cali_config = {}; // Zero initialize first
79#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
80 cali_config.chan = this->channel_;
81#endif // ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
82 cali_config.unit_id = this->adc_unit_;
83 cali_config.atten = this->attenuation_;
84 cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
85
86 err = adc_cali_create_scheme_curve_fitting(&cali_config, &handle);
87 if (err == ESP_OK) {
90 ESP_LOGV(TAG, "Using curve fitting calibration");
91 } else {
92 ESP_LOGW(TAG, "Curve fitting calibration failed with error %d, will use uncalibrated readings", err);
94 }
95#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
96 adc_cali_line_fitting_config_t cali_config = {
97 .unit_id = this->adc_unit_,
98 .atten = this->attenuation_,
99 .bitwidth = ADC_BITWIDTH_DEFAULT,
100#if !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32C2)
101 .default_vref = 1100, // Default reference voltage in mV
102#endif // !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32C2)
103 };
104 err = adc_cali_create_scheme_line_fitting(&cali_config, &handle);
105 if (err == ESP_OK) {
108 ESP_LOGV(TAG, "Using line fitting calibration");
109 } else {
110 ESP_LOGW(TAG, "Line fitting calibration failed with error %d, will use uncalibrated readings", err);
112 }
113#else // No calibration scheme available
114 (void) handle;
115 ESP_LOGD(TAG, "No calibration scheme for this variant, readings are uncalibrated");
117#endif
118 }
119
120 this->setup_flags_.init_complete = true;
121}
122
124 LOG_SENSOR("", "ADC Sensor", this);
125 LOG_PIN(" Pin: ", this->pin_);
126#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED) || defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
127 const char *calibration_status = this->setup_flags_.calibration_complete ? "OK" : "FAILED";
128#else
129 const char *calibration_status = "N/A"; // This variant has no calibration scheme
130#endif
131 ESP_LOGCONFIG(TAG,
132 " Channel: %d\n"
133 " Unit: %s\n"
134 " Attenuation: %s\n"
135 " Samples: %i\n"
136 " Sampling mode: %s\n"
137 " Setup Status:\n"
138 " Handle Init: %s\n"
139 " Config: %s\n"
140 " Calibration: %s\n"
141 " Overall Init: %s",
142 this->channel_, LOG_STR_ARG(adc_unit_to_str(this->adc_unit_)),
143 this->autorange_ ? "Auto" : LOG_STR_ARG(attenuation_to_str(this->attenuation_)), this->sample_count_,
144 LOG_STR_ARG(sampling_mode_to_str(this->sampling_mode_)),
145 this->setup_flags_.handle_init_complete ? "OK" : "FAILED",
146 this->setup_flags_.config_complete ? "OK" : "FAILED", calibration_status,
147 this->setup_flags_.init_complete ? "OK" : "FAILED");
148
149 LOG_UPDATE_INTERVAL(this);
150}
151
153 if (this->autorange_) {
154 return this->sample_autorange_();
155 } else {
156 return this->sample_fixed_attenuation_();
157 }
158}
159
161 auto aggr = Aggregator<uint32_t>(this->sampling_mode_);
162
163 for (uint8_t sample = 0; sample < this->sample_count_; sample++) {
164 int raw;
165 esp_err_t err = adc_oneshot_read(this->adc_handle_, this->channel_, &raw);
166
167 if (err != ESP_OK) {
168 ESP_LOGW(TAG, "ADC read failed with error %d", err);
169 continue;
170 }
171
172 if (raw == -1) {
173 ESP_LOGW(TAG, "Invalid ADC reading");
174 continue;
175 }
176
177 aggr.add_sample(raw);
178 }
179
180 uint32_t final_value = aggr.aggregate();
181
182 if (this->output_raw_) {
183 return final_value;
184 }
185
186 if (this->calibration_handle_ != nullptr) {
187 int voltage_mv;
188 esp_err_t err = adc_cali_raw_to_voltage(this->calibration_handle_, final_value, &voltage_mv);
189 if (err == ESP_OK) {
190 return voltage_mv / 1000.0f;
191 } else {
192 ESP_LOGW(TAG, "ADC calibration conversion failed with error %d, disabling calibration", err);
193 if (this->calibration_handle_ != nullptr) {
194#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
195 adc_cali_delete_scheme_curve_fitting(this->calibration_handle_);
196#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
197 adc_cali_delete_scheme_line_fitting(this->calibration_handle_);
198#endif
199 this->calibration_handle_ = nullptr;
200 }
201 }
202 }
203
204 return final_value * 3.3f / 4095.0f;
205}
206
208 // Auto-range mode
209 auto read_atten = [this](adc_atten_t atten) -> std::pair<int, float> {
210 // First reconfigure the attenuation for this reading
211 adc_oneshot_chan_cfg_t config = {
212 .atten = atten,
213 .bitwidth = ADC_BITWIDTH_DEFAULT,
214 };
215
216 esp_err_t err = adc_oneshot_config_channel(this->adc_handle_, this->channel_, &config);
217
218 if (err != ESP_OK) {
219 ESP_LOGW(TAG, "Error configuring ADC channel for autorange: %d", err);
220 return {-1, 0.0f};
221 }
222
223 // Need to recalibrate for the new attenuation
224 if (this->calibration_handle_ != nullptr) {
225 // Delete old calibration handle
226#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
227 adc_cali_delete_scheme_curve_fitting(this->calibration_handle_);
228#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
229 adc_cali_delete_scheme_line_fitting(this->calibration_handle_);
230#endif
231 this->calibration_handle_ = nullptr;
232 }
233
234 // Create new calibration handle for this attenuation
235 adc_cali_handle_t handle = nullptr;
236
237#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
238 adc_cali_curve_fitting_config_t cali_config = {};
239#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
240 cali_config.chan = this->channel_;
241#endif
242 cali_config.unit_id = this->adc_unit_;
243 cali_config.atten = atten;
244 cali_config.bitwidth = ADC_BITWIDTH_DEFAULT;
245
246 err = adc_cali_create_scheme_curve_fitting(&cali_config, &handle);
247 ESP_LOGVV(TAG, "Autorange atten=%d: Calibration handle creation %s (err=%d)", atten,
248 (err == ESP_OK) ? "SUCCESS" : "FAILED", err);
249#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
250 adc_cali_line_fitting_config_t cali_config = {
251 .unit_id = this->adc_unit_,
252 .atten = atten,
253 .bitwidth = ADC_BITWIDTH_DEFAULT,
254#if !defined(USE_ESP32_VARIANT_ESP32S2) && !defined(USE_ESP32_VARIANT_ESP32C2)
255 .default_vref = 1100,
256#endif
257 };
258 err = adc_cali_create_scheme_line_fitting(&cali_config, &handle);
259 ESP_LOGVV(TAG, "Autorange atten=%d: Calibration handle creation %s (err=%d)", atten,
260 (err == ESP_OK) ? "SUCCESS" : "FAILED", err);
261#endif
262
263 int raw;
264 err = adc_oneshot_read(this->adc_handle_, this->channel_, &raw);
265 ESP_LOGVV(TAG, "Autorange atten=%d: Raw ADC read %s, value=%d (err=%d)", atten,
266 (err == ESP_OK) ? "SUCCESS" : "FAILED", raw, err);
267
268 if (err != ESP_OK) {
269 ESP_LOGW(TAG, "ADC read failed in autorange with error %d", err);
270 if (handle != nullptr) {
271#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
272 adc_cali_delete_scheme_curve_fitting(handle);
273#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
274 adc_cali_delete_scheme_line_fitting(handle);
275#endif
276 }
277 return {-1, 0.0f};
278 }
279
280 float voltage = 0.0f;
281 if (handle != nullptr) {
282 int voltage_mv;
283 err = adc_cali_raw_to_voltage(handle, raw, &voltage_mv);
284 if (err == ESP_OK) {
285 voltage = voltage_mv / 1000.0f;
286 ESP_LOGVV(TAG, "Autorange atten=%d: CALIBRATED - raw=%d -> %dmV -> %.6fV", atten, raw, voltage_mv, voltage);
287 } else {
288 voltage = raw * 3.3f / 4095.0f;
289 ESP_LOGVV(TAG, "Autorange atten=%d: UNCALIBRATED FALLBACK - raw=%d -> %.6fV (3.3V ref)", atten, raw, voltage);
290 }
291 // Clean up calibration handle
292#if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED)
293 adc_cali_delete_scheme_curve_fitting(handle);
294#elif defined(ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED)
295 adc_cali_delete_scheme_line_fitting(handle);
296#endif
297 } else {
298 voltage = raw * 3.3f / 4095.0f;
299 ESP_LOGVV(TAG, "Autorange atten=%d: NO CALIBRATION - raw=%d -> %.6fV (3.3V ref)", atten, raw, voltage);
300 }
301
302 return {raw, voltage};
303 };
304
305 auto [raw12, mv12] = read_atten(ADC_ATTEN_DB_12);
306 if (raw12 == -1) {
307 ESP_LOGE(TAG, "Failed to read ADC in autorange mode");
308 return NAN;
309 }
310
311 int raw6 = 4095, raw2 = 4095, raw0 = 4095;
312 float mv6 = 0, mv2 = 0, mv0 = 0;
313
314 if (raw12 < 4095) {
315 auto [raw6_val, mv6_val] = read_atten(ADC_ATTEN_DB_6);
316 raw6 = raw6_val;
317 mv6 = mv6_val;
318
319 if (raw6 < 4095 && raw6 != -1) {
320 auto [raw2_val, mv2_val] = read_atten(ADC_ATTEN_DB_2_5);
321 raw2 = raw2_val;
322 mv2 = mv2_val;
323
324 if (raw2 < 4095 && raw2 != -1) {
325 auto [raw0_val, mv0_val] = read_atten(ADC_ATTEN_DB_0);
326 raw0 = raw0_val;
327 mv0 = mv0_val;
328 }
329 }
330 }
331
332 if (raw0 == -1 || raw2 == -1 || raw6 == -1 || raw12 == -1) {
333 return NAN;
334 }
335
336 const int adc_half = 2048;
337 const uint32_t c12 = std::min(raw12, adc_half);
338
339 const int32_t c6_signed = adc_half - std::abs(raw6 - adc_half);
340 const uint32_t c6 = (c6_signed > 0) ? c6_signed : 0; // Clamp to prevent underflow
341
342 const int32_t c2_signed = adc_half - std::abs(raw2 - adc_half);
343 const uint32_t c2 = (c2_signed > 0) ? c2_signed : 0; // Clamp to prevent underflow
344
345 const uint32_t c0 = std::min(4095 - raw0, adc_half);
346 const uint32_t csum = c12 + c6 + c2 + c0;
347
348 ESP_LOGVV(TAG, "Autorange summary:");
349 ESP_LOGVV(TAG, " Raw readings: 12db=%d, 6db=%d, 2.5db=%d, 0db=%d", raw12, raw6, raw2, raw0);
350 ESP_LOGVV(TAG, " Voltages: 12db=%.6f, 6db=%.6f, 2.5db=%.6f, 0db=%.6f", mv12, mv6, mv2, mv0);
351 ESP_LOGVV(TAG, " Coefficients: c12=%" PRIu32 ", c6=%" PRIu32 ", c2=%" PRIu32 ", c0=%" PRIu32 ", sum=%" PRIu32, c12,
352 c6, c2, c0, csum);
353
354 if (csum == 0) {
355 ESP_LOGE(TAG, "Invalid weight sum in autorange calculation");
356 return NAN;
357 }
358
359 const float final_result = (mv12 * c12 + mv6 * c6 + mv2 * c2 + mv0 * c0) / csum;
360 ESP_LOGV(TAG,
361 "Autorange final: (%.6f*%" PRIu32 " + %.6f*%" PRIu32 " + %.6f*%" PRIu32 " + %.6f*%" PRIu32 ")/%" PRIu32
362 " = %.6fV",
363 mv12, c12, mv6, c6, mv2, c2, mv0, c0, csum, final_result);
364
365 return final_result;
366}
367
368} // namespace esphome::adc
369
370#endif // USE_ESP32
uint8_t raw[35]
Definition bl0939.h:0
void mark_failed()
Mark this component as failed.
struct esphome::adc::ADCSensor::SetupFlags setup_flags_
float sample() override
Perform a single ADC sampling operation and return the measured value.
adc_oneshot_unit_handle_t adc_handle_
Definition adc_sensor.h:140
void setup() override
Set up the ADC sensor by initializing hardware and calibration parameters.
InternalGPIOPin * pin_
Definition adc_sensor.h:133
void dump_config() override
Output the configuration details of the ADC sensor for debugging purposes.
SamplingMode sampling_mode_
Definition adc_sensor.h:134
static adc_oneshot_unit_handle_t shared_adc_handles[2]
Definition adc_sensor.h:152
adc_channel_t channel_
Definition adc_sensor.h:143
adc_cali_handle_t calibration_handle_
Definition adc_sensor.h:141
const LogString * attenuation_to_str(adc_atten_t attenuation)
const LogString * sampling_mode_to_str(SamplingMode mode)
const LogString * adc_unit_to_str(adc_unit_t unit)
static void uint32_t
spi_device_handle_t handle