1 /*
2  * Copyright (c) 2025 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define DT_DRV_COMPAT espressif_esp32_adc
8 
9 #include <errno.h>
10 #include <hal/adc_hal.h>
11 #include <hal/adc_oneshot_hal.h>
12 #include <hal/adc_types.h>
13 #include <soc/adc_periph.h>
14 #include <esp_adc/adc_cali.h>
15 #include <esp_adc/adc_cali_scheme.h>
16 #include <esp_clk_tree.h>
17 #include <esp_private/periph_ctrl.h>
18 #include <esp_private/sar_periph_ctrl.h>
19 #include <esp_private/adc_share_hw_ctrl.h>
20 
21 #if defined(CONFIG_ADC_ESP32_DMA)
22 #if !SOC_GDMA_SUPPORTED
23 #error "SoCs without GDMA peripheral are not supported!"
24 #endif
25 #include <zephyr/drivers/dma.h>
26 #include <zephyr/drivers/dma/dma_esp32.h>
27 #endif
28 
29 #include <zephyr/kernel.h>
30 #include <zephyr/device.h>
31 #include <zephyr/drivers/adc.h>
32 #include <zephyr/drivers/gpio.h>
33 #include <zephyr/drivers/clock_control.h>
34 
35 #include <zephyr/logging/log.h>
36 LOG_MODULE_REGISTER(adc_esp32, CONFIG_ADC_LOG_LEVEL);
37 
38 #define ADC_RESOLUTION_MIN SOC_ADC_DIGI_MIN_BITWIDTH
39 #define ADC_RESOLUTION_MAX SOC_ADC_DIGI_MAX_BITWIDTH
40 
41 #define VALID_RESOLUTION(r) ((r) >= ADC_RESOLUTION_MIN && (r) <= ADC_RESOLUTION_MAX)
42 
43 /* Default internal reference voltage */
44 #define ADC_ESP32_DEFAULT_VREF_INTERNAL (1100)
45 
46 #define ADC_DMA_BUFFER_SIZE DMA_DESCRIPTOR_BUFFER_MAX_SIZE_4B_ALIGNED
47 
48 #define ADC_CLIP_MVOLT_12DB	2550
49 
50 struct adc_esp32_conf {
51 	const struct device *clock_dev;
52 	const clock_control_subsys_t clock_subsys;
53 	adc_unit_t unit;
54 	uint8_t channel_count;
55 	const struct device *gpio_port;
56 #if defined(CONFIG_ADC_ESP32_DMA)
57 	const struct device *dma_dev;
58 	uint8_t dma_channel;
59 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
60 };
61 
62 struct adc_esp32_data {
63 	adc_oneshot_hal_ctx_t hal;
64 	adc_atten_t attenuation[SOC_ADC_MAX_CHANNEL_NUM];
65 	uint8_t resolution[SOC_ADC_MAX_CHANNEL_NUM];
66 	adc_cali_handle_t cal_handle[SOC_ADC_MAX_CHANNEL_NUM];
67 	uint16_t meas_ref_internal;
68 	uint16_t *buffer;
69 #if defined(CONFIG_ADC_ESP32_DMA)
70 	adc_hal_dma_ctx_t adc_hal_dma_ctx;
71 	uint8_t *dma_buffer;
72 	struct k_sem dma_conv_wait_lock;
73 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
74 };
75 
76 /* Convert zephyr,gain property to the ESP32 attenuation */
gain_to_atten(enum adc_gain gain,adc_atten_t * atten)77 static inline int gain_to_atten(enum adc_gain gain, adc_atten_t *atten)
78 {
79 	switch (gain) {
80 	case ADC_GAIN_1:
81 		*atten = ADC_ATTEN_DB_0;
82 		break;
83 	case ADC_GAIN_4_5:
84 		*atten = ADC_ATTEN_DB_2_5;
85 		break;
86 	case ADC_GAIN_1_2:
87 		*atten = ADC_ATTEN_DB_6;
88 		break;
89 	case ADC_GAIN_1_4:
90 		*atten = ADC_ATTEN_DB_12;
91 		break;
92 	default:
93 		return -ENOTSUP;
94 	}
95 	return 0;
96 }
97 
98 #if !defined(CONFIG_ADC_ESP32_DMA)
99 
100 /* Convert voltage by inverted attenuation to support zephyr gain values */
atten_to_gain(adc_atten_t atten,uint32_t * val_mv)101 static void atten_to_gain(adc_atten_t atten, uint32_t *val_mv)
102 {
103 	uint32_t num, den;
104 
105 	if (!val_mv) {
106 		return;
107 	}
108 
109 	switch (atten) {
110 	case ADC_ATTEN_DB_2_5: /* 1/ADC_GAIN_4_5 */
111 		num = 4;
112 		den = 5;
113 		break;
114 	case ADC_ATTEN_DB_6: /* 1/ADC_GAIN_1_2 */
115 		num = 1;
116 		den = 2;
117 		break;
118 	case ADC_ATTEN_DB_12: /* 1/ADC_GAIN_1_4 */
119 		num = 1;
120 		den = 4;
121 		break;
122 	case ADC_ATTEN_DB_0: /* 1/ADC_GAIN_1 */
123 	default:
124 		num = 1;
125 		den = 1;
126 		break;
127 	}
128 
129 	*val_mv = (*val_mv * num) / den;
130 }
131 
132 #endif /* !defined(CONFIG_ADC_ESP32_DMA) */
133 
adc_hw_calibration(adc_unit_t unit)134 static void adc_hw_calibration(adc_unit_t unit)
135 {
136 #if SOC_ADC_CALIBRATION_V1_SUPPORTED
137 	adc_hal_calibration_init(unit);
138 	for (int j = 0; j < SOC_ADC_ATTEN_NUM; j++) {
139 		adc_calc_hw_calibration_code(unit, j);
140 #if SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED
141 		/* Load the channel compensation from efuse */
142 		for (int k = 0; k < SOC_ADC_CHANNEL_NUM(unit); k++) {
143 			adc_load_hw_calibration_chan_compens(unit, k, j);
144 		}
145 #endif /* SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED */
146 	}
147 #endif /* SOC_ADC_CALIBRATION_V1_SUPPORTED */
148 }
149 
150 #if defined(CONFIG_ADC_ESP32_DMA)
151 
adc_esp32_dma_conv_done(const struct device * dma_dev,void * user_data,uint32_t channel,int status)152 static void IRAM_ATTR adc_esp32_dma_conv_done(const struct device *dma_dev, void *user_data,
153 					      uint32_t channel, int status)
154 {
155 	ARG_UNUSED(dma_dev);
156 	ARG_UNUSED(status);
157 
158 	const struct device *dev = user_data;
159 	struct adc_esp32_data *data = dev->data;
160 
161 	k_sem_give(&data->dma_conv_wait_lock);
162 }
163 
adc_esp32_dma_start(const struct device * dev,uint8_t * buf,size_t len)164 static int adc_esp32_dma_start(const struct device *dev, uint8_t *buf, size_t len)
165 {
166 	const struct adc_esp32_conf *conf = dev->config;
167 
168 	int err = 0;
169 	struct dma_config dma_cfg = {0};
170 	struct dma_status dma_status = {0};
171 	struct dma_block_config dma_blk = {0};
172 
173 	err = dma_get_status(conf->dma_dev, conf->dma_channel, &dma_status);
174 	if (err) {
175 		LOG_ERR("Unable to get dma channel[%u] status (%d)",
176 			(unsigned int)conf->dma_channel, err);
177 		return -EINVAL;
178 	}
179 
180 	if (dma_status.busy) {
181 		LOG_ERR("dma channel[%u] is busy!", (unsigned int)conf->dma_channel);
182 		return -EBUSY;
183 	}
184 
185 	unsigned int key = irq_lock();
186 
187 	dma_cfg.channel_direction = PERIPHERAL_TO_MEMORY;
188 	dma_cfg.dma_callback = adc_esp32_dma_conv_done;
189 	dma_cfg.user_data = (void *)dev;
190 	dma_cfg.dma_slot = ESP_GDMA_TRIG_PERIPH_ADC0;
191 	dma_cfg.block_count = 1;
192 	dma_cfg.head_block = &dma_blk;
193 	dma_blk.block_size = len;
194 	dma_blk.dest_address = (uint32_t)buf;
195 
196 	err = dma_config(conf->dma_dev, conf->dma_channel, &dma_cfg);
197 	if (err) {
198 		LOG_ERR("Error configuring dma (%d)", err);
199 		goto unlock;
200 	}
201 
202 	err = dma_start(conf->dma_dev, conf->dma_channel);
203 	if (err) {
204 		LOG_ERR("Error starting dma (%d)", err);
205 		goto unlock;
206 	}
207 
208 unlock:
209 	irq_unlock(key);
210 	return err;
211 }
212 
adc_esp32_dma_stop(const struct device * dev)213 static int adc_esp32_dma_stop(const struct device *dev)
214 {
215 	const struct adc_esp32_conf *conf = dev->config;
216 	unsigned int key = irq_lock();
217 	int err = 0;
218 
219 	err = dma_stop(conf->dma_dev, conf->dma_channel);
220 	if (err) {
221 		LOG_ERR("Error stopping dma (%d)", err);
222 	}
223 
224 	irq_unlock(key);
225 	return err;
226 }
227 
adc_esp32_fill_digi_pattern(const struct device * dev,const struct adc_sequence * seq,void * pattern_config,uint32_t * pattern_len,uint32_t * unit_attenuation)228 static int adc_esp32_fill_digi_pattern(const struct device *dev, const struct adc_sequence *seq,
229 				       void *pattern_config, uint32_t *pattern_len,
230 				       uint32_t *unit_attenuation)
231 {
232 	const struct adc_esp32_conf *conf = dev->config;
233 	struct adc_esp32_data *data = dev->data;
234 
235 	adc_digi_pattern_config_t *adc_digi_pattern_config =
236 		(adc_digi_pattern_config_t *)pattern_config;
237 	const uint32_t unit_atten_uninit = 999;
238 	uint32_t channel_mask = 1, channels_copy = seq->channels;
239 
240 	*pattern_len = 0;
241 	*unit_attenuation = unit_atten_uninit;
242 	for (uint8_t channel_id = 0; channel_id < conf->channel_count; channel_id++) {
243 		if (channels_copy & channel_mask) {
244 			if (*unit_attenuation == unit_atten_uninit) {
245 				*unit_attenuation = data->attenuation[channel_id];
246 			} else if (*unit_attenuation != data->attenuation[channel_id]) {
247 				LOG_ERR("Channel[%u] attenuation different of unit[%u] attenuation",
248 					(unsigned int)channel_id, (unsigned int)conf->unit);
249 				return -EINVAL;
250 			}
251 
252 			adc_digi_pattern_config->atten = data->attenuation[channel_id];
253 			adc_digi_pattern_config->channel = channel_id;
254 			adc_digi_pattern_config->unit = conf->unit;
255 			adc_digi_pattern_config->bit_width = seq->resolution;
256 			adc_digi_pattern_config++;
257 
258 			*pattern_len += 1;
259 			if (*pattern_len > SOC_ADC_PATT_LEN_MAX) {
260 				LOG_ERR("Max pattern len is %d", SOC_ADC_PATT_LEN_MAX);
261 				return -EINVAL;
262 			}
263 
264 			channels_copy &= ~channel_mask;
265 			if (!channels_copy) {
266 				break;
267 			}
268 		}
269 		channel_mask <<= 1;
270 	}
271 
272 	return 0;
273 }
274 
adc_esp32_digi_start(const struct device * dev,void * pattern_config,uint32_t pattern_len,uint32_t number_of_samplings,uint32_t sample_freq_hz,uint32_t unit_attenuation)275 static void adc_esp32_digi_start(const struct device *dev, void *pattern_config,
276 				 uint32_t pattern_len, uint32_t number_of_samplings,
277 				 uint32_t sample_freq_hz, uint32_t unit_attenuation)
278 {
279 	const struct adc_esp32_conf *conf = dev->config;
280 	struct adc_esp32_data *data = dev->data;
281 
282 	sar_periph_ctrl_adc_continuous_power_acquire();
283 	adc_lock_acquire(conf->unit);
284 
285 #if SOC_ADC_CALIBRATION_V1_SUPPORTED
286 	adc_set_hw_calibration_code(conf->unit, unit_attenuation);
287 #endif /* SOC_ADC_CALIBRATION_V1_SUPPORTED */
288 
289 #if SOC_ADC_ARBITER_SUPPORTED
290 	if (conf->unit == ADC_UNIT_2) {
291 		adc_arbiter_t config = ADC_ARBITER_CONFIG_DEFAULT();
292 
293 		adc_hal_arbiter_config(&config);
294 	}
295 #endif /* SOC_ADC_ARBITER_SUPPORTED */
296 
297 	adc_hal_digi_ctrlr_cfg_t adc_hal_digi_ctrlr_cfg;
298 	soc_module_clk_t clk_src = ADC_DIGI_CLK_SRC_DEFAULT;
299 	uint32_t clk_src_freq_hz = 0;
300 
301 	esp_clk_tree_src_get_freq_hz(clk_src, ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED,
302 				     &clk_src_freq_hz);
303 
304 	adc_hal_digi_ctrlr_cfg.conv_mode =
305 		(conf->unit == ADC_UNIT_1) ? ADC_CONV_SINGLE_UNIT_1 : ADC_CONV_SINGLE_UNIT_2;
306 	adc_hal_digi_ctrlr_cfg.clk_src = clk_src;
307 	adc_hal_digi_ctrlr_cfg.clk_src_freq_hz = clk_src_freq_hz;
308 	adc_hal_digi_ctrlr_cfg.sample_freq_hz = sample_freq_hz;
309 	adc_hal_digi_ctrlr_cfg.adc_pattern = (adc_digi_pattern_config_t *)pattern_config;
310 	adc_hal_digi_ctrlr_cfg.adc_pattern_len = pattern_len;
311 
312 	uint32_t number_of_adc_digi_samples = number_of_samplings * pattern_len;
313 
314 	adc_hal_dma_config_t adc_hal_dma_config = {
315 		.dev = (void *)GDMA_LL_GET_HW(0),
316 		.eof_desc_num = 1,
317 		.eof_step = 1,
318 		.dma_chan = conf->dma_channel,
319 		.eof_num = number_of_adc_digi_samples,
320 	};
321 
322 	adc_hal_dma_ctx_config(&data->adc_hal_dma_ctx, &adc_hal_dma_config);
323 
324 	adc_hal_set_controller(conf->unit, ADC_HAL_CONTINUOUS_READ_MODE);
325 	adc_hal_digi_init(&data->adc_hal_dma_ctx);
326 	adc_hal_digi_controller_config(&data->adc_hal_dma_ctx, &adc_hal_digi_ctrlr_cfg);
327 	adc_hal_digi_start(&data->adc_hal_dma_ctx, data->dma_buffer);
328 }
329 
adc_esp32_digi_stop(const struct device * dev)330 static void adc_esp32_digi_stop(const struct device *dev)
331 {
332 	const struct adc_esp32_conf *conf = dev->config;
333 	struct adc_esp32_data *data = dev->data;
334 
335 	adc_hal_digi_dis_intr(&data->adc_hal_dma_ctx, ADC_HAL_DMA_INTR_MASK);
336 	adc_hal_digi_clr_intr(&data->adc_hal_dma_ctx, ADC_HAL_DMA_INTR_MASK);
337 	adc_hal_digi_stop(&data->adc_hal_dma_ctx);
338 	adc_hal_digi_deinit(&data->adc_hal_dma_ctx);
339 	adc_lock_release(conf->unit);
340 	sar_periph_ctrl_adc_continuous_power_release();
341 }
342 
adc_esp32_fill_seq_buffer(const void * seq_buffer,const void * dma_buffer,uint32_t number_of_samples)343 static void adc_esp32_fill_seq_buffer(const void *seq_buffer, const void *dma_buffer,
344 				      uint32_t number_of_samples)
345 {
346 	uint16_t *sample = (uint16_t *)seq_buffer;
347 	adc_digi_output_data_t *digi_data = (adc_digi_output_data_t *)dma_buffer;
348 
349 	for (uint32_t k = 0; k < number_of_samples; k++) {
350 		*sample++ = (uint16_t)(digi_data++)->type2.data;
351 	}
352 }
353 
adc_esp32_wait_for_dma_conv_done(const struct device * dev)354 static int adc_esp32_wait_for_dma_conv_done(const struct device *dev)
355 {
356 	struct adc_esp32_data *data = dev->data;
357 	int err = 0;
358 
359 	err = k_sem_take(&data->dma_conv_wait_lock, K_FOREVER);
360 	if (err) {
361 		LOG_ERR("Error taking dma_conv_wait_lock (%d)", err);
362 	}
363 
364 	return err;
365 }
366 
367 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
368 
adc_esp32_read(const struct device * dev,const struct adc_sequence * seq)369 static int adc_esp32_read(const struct device *dev, const struct adc_sequence *seq)
370 {
371 	struct adc_esp32_data *data = dev->data;
372 
373 	uint8_t channel_id = find_lsb_set(seq->channels) - 1;
374 
375 	if (seq->buffer_size < 2) {
376 		LOG_ERR("Sequence buffer space too low '%d'", seq->buffer_size);
377 		return -ENOMEM;
378 	}
379 
380 #if !defined(CONFIG_ADC_ESP32_DMA)
381 	if (seq->channels > BIT(channel_id)) {
382 		LOG_ERR("Multi-channel readings not supported");
383 		return -ENOTSUP;
384 	}
385 #endif /* !defined(CONFIG_ADC_ESP32_DMA) */
386 
387 	if (seq->options) {
388 		if (seq->options->extra_samplings) {
389 			LOG_ERR("Extra samplings not supported");
390 			return -ENOTSUP;
391 		}
392 
393 #if !defined(CONFIG_ADC_ESP32_DMA)
394 		if (seq->options->interval_us) {
395 			LOG_ERR("Interval between samplings not supported");
396 			return -ENOTSUP;
397 		}
398 #endif /* !defined(CONFIG_ADC_ESP32_DMA) */
399 	}
400 
401 	if (!VALID_RESOLUTION(seq->resolution)) {
402 		LOG_ERR("unsupported resolution (%d)", seq->resolution);
403 		return -ENOTSUP;
404 	}
405 
406 	if (seq->calibrate) {
407 		/* TODO: Does this mean actual Vref measurement on selected GPIO ?*/
408 		LOG_ERR("calibration is not supported");
409 		return -ENOTSUP;
410 	}
411 
412 	data->resolution[channel_id] = seq->resolution;
413 
414 #if !defined(CONFIG_ADC_ESP32_DMA)
415 
416 	uint32_t acq_raw;
417 
418 	adc_oneshot_hal_setup(&data->hal, channel_id);
419 
420 #if SOC_ADC_CALIBRATION_V1_SUPPORTED
421 	adc_set_hw_calibration_code(data->hal.unit, data->attenuation[channel_id]);
422 #endif /* SOC_ADC_CALIBRATION_V1_SUPPORTED */
423 
424 	adc_oneshot_hal_convert(&data->hal, &acq_raw);
425 
426 	if (data->cal_handle[channel_id]) {
427 		if (data->meas_ref_internal > 0) {
428 			uint32_t acq_mv;
429 
430 			adc_cali_raw_to_voltage(data->cal_handle[channel_id], acq_raw, &acq_mv);
431 
432 			LOG_DBG("ADC acquisition [unit: %u, chan: %u, acq_raw: %u, acq_mv: %u]",
433 				data->hal.unit, channel_id, acq_raw, acq_mv);
434 
435 #if CONFIG_SOC_SERIES_ESP32
436 		if (data->attenuation[channel_id] == ADC_ATTEN_DB_12) {
437 			if (acq_mv > ADC_CLIP_MVOLT_12DB) {
438 				acq_mv = ADC_CLIP_MVOLT_12DB;
439 			}
440 		}
441 #endif /* CONFIG_SOC_SERIES_ESP32 */
442 
443 			/* Fit according to selected attenuation */
444 			atten_to_gain(data->attenuation[channel_id], &acq_mv);
445 			acq_raw = acq_mv * ((1 << data->resolution[channel_id]) - 1) /
446 				  data->meas_ref_internal;
447 		} else {
448 			LOG_WRN("ADC reading is uncompensated");
449 		}
450 	} else {
451 		LOG_WRN("ADC reading is uncompensated");
452 	}
453 
454 	/* Store result */
455 	data->buffer = (uint16_t *)seq->buffer;
456 	data->buffer[0] = acq_raw;
457 
458 #else /* !defined(CONFIG_ADC_ESP32_DMA) */
459 
460 	int err = 0;
461 	uint32_t adc_pattern_len, unit_attenuation;
462 	adc_digi_pattern_config_t adc_digi_pattern_config[SOC_ADC_MAX_CHANNEL_NUM];
463 
464 	err = adc_esp32_fill_digi_pattern(dev, seq, &adc_digi_pattern_config, &adc_pattern_len,
465 					  &unit_attenuation);
466 	if (err || adc_pattern_len == 0) {
467 		return -EINVAL;
468 	}
469 
470 	const struct adc_sequence_options *options = seq->options;
471 	uint32_t sample_freq_hz = SOC_ADC_SAMPLE_FREQ_THRES_HIGH, number_of_samplings = 1;
472 
473 	if (options != NULL) {
474 		number_of_samplings = seq->buffer_size / (adc_pattern_len * sizeof(uint16_t));
475 
476 		if (options->interval_us) {
477 			sample_freq_hz = MHZ(1) / options->interval_us;
478 		}
479 	}
480 
481 	if (!number_of_samplings) {
482 		LOG_ERR("buffer_size insufficient to store at least one set of samples!");
483 		return -EINVAL;
484 	}
485 
486 	if (sample_freq_hz < SOC_ADC_SAMPLE_FREQ_THRES_LOW ||
487 	    sample_freq_hz > SOC_ADC_SAMPLE_FREQ_THRES_HIGH) {
488 		LOG_ERR("ADC sampling frequency out of range: %uHz", sample_freq_hz);
489 		return -EINVAL;
490 	}
491 
492 	uint32_t number_of_adc_samples = number_of_samplings * adc_pattern_len;
493 	uint32_t number_of_adc_dma_data_bytes =
494 		number_of_adc_samples * SOC_ADC_DIGI_DATA_BYTES_PER_CONV;
495 
496 	if (number_of_adc_dma_data_bytes > ADC_DMA_BUFFER_SIZE) {
497 		LOG_ERR("dma buffer size insufficient to store a complete sequence!");
498 		return -EINVAL;
499 	}
500 
501 	err = adc_esp32_dma_start(dev, data->dma_buffer, number_of_adc_dma_data_bytes);
502 	if (err) {
503 		return err;
504 	}
505 
506 	adc_esp32_digi_start(dev, &adc_digi_pattern_config, adc_pattern_len, number_of_samplings,
507 			     sample_freq_hz, unit_attenuation);
508 
509 	err = adc_esp32_wait_for_dma_conv_done(dev);
510 	if (err) {
511 		return err;
512 	}
513 
514 	adc_esp32_digi_stop(dev);
515 
516 	err = adc_esp32_dma_stop(dev);
517 	if (err) {
518 		return err;
519 	}
520 
521 	adc_esp32_fill_seq_buffer(seq->buffer, data->dma_buffer, number_of_adc_samples);
522 
523 #endif /* !defined(CONFIG_ADC_ESP32_DMA) */
524 
525 	return 0;
526 }
527 
528 #ifdef CONFIG_ADC_ASYNC
adc_esp32_read_async(const struct device * dev,const struct adc_sequence * sequence,struct k_poll_signal * async)529 static int adc_esp32_read_async(const struct device *dev, const struct adc_sequence *sequence,
530 				struct k_poll_signal *async)
531 {
532 	(void)(dev);
533 	(void)(sequence);
534 	(void)(async);
535 
536 	return -ENOTSUP;
537 }
538 #endif /* CONFIG_ADC_ASYNC */
539 
adc_esp32_channel_setup(const struct device * dev,const struct adc_channel_cfg * cfg)540 static int adc_esp32_channel_setup(const struct device *dev, const struct adc_channel_cfg *cfg)
541 {
542 	const struct adc_esp32_conf *conf = (const struct adc_esp32_conf *)dev->config;
543 	struct adc_esp32_data *data = (struct adc_esp32_data *)dev->data;
544 	adc_atten_t old_atten = data->attenuation[cfg->channel_id];
545 
546 	if (cfg->channel_id >= conf->channel_count) {
547 		LOG_ERR("Unsupported channel id '%d'", cfg->channel_id);
548 		return -ENOTSUP;
549 	}
550 
551 	if (cfg->reference != ADC_REF_INTERNAL) {
552 		LOG_ERR("Unsupported channel reference '%d'", cfg->reference);
553 		return -ENOTSUP;
554 	}
555 
556 	if (cfg->acquisition_time != ADC_ACQ_TIME_DEFAULT) {
557 		LOG_ERR("Unsupported acquisition_time '%d'", cfg->acquisition_time);
558 		return -ENOTSUP;
559 	}
560 
561 	if (cfg->differential) {
562 		LOG_ERR("Differential channels are not supported");
563 		return -ENOTSUP;
564 	}
565 
566 	if (gain_to_atten(cfg->gain, &data->attenuation[cfg->channel_id])) {
567 		LOG_ERR("Unsupported gain value '%d'", cfg->gain);
568 		return -ENOTSUP;
569 	}
570 
571 	adc_oneshot_hal_chan_cfg_t config = {
572 		.atten = data->attenuation[cfg->channel_id],
573 		.bitwidth = data->resolution[cfg->channel_id],
574 	};
575 
576 	adc_oneshot_hal_channel_config(&data->hal, &config, cfg->channel_id);
577 
578 	if ((data->cal_handle[cfg->channel_id] == NULL) ||
579 	    (data->attenuation[cfg->channel_id] != old_atten)) {
580 #if ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED
581 		adc_cali_curve_fitting_config_t cal_config = {
582 			.unit_id = conf->unit,
583 			.chan = cfg->channel_id,
584 			.atten = data->attenuation[cfg->channel_id],
585 			.bitwidth = data->resolution[cfg->channel_id],
586 		};
587 
588 		LOG_DBG("Curve fitting calib [unit_id: %u, chan: %u, atten: %u, bitwidth: %u]",
589 			conf->unit, cfg->channel_id, data->attenuation[cfg->channel_id],
590 			data->resolution[cfg->channel_id]);
591 
592 		if (data->cal_handle[cfg->channel_id] != NULL) {
593 			/* delete pre-existing calib scheme */
594 			adc_cali_delete_scheme_curve_fitting(data->cal_handle[cfg->channel_id]);
595 		}
596 
597 		adc_cali_create_scheme_curve_fitting(&cal_config,
598 						     &data->cal_handle[cfg->channel_id]);
599 #endif /* ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED */
600 
601 #if ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED
602 		adc_cali_line_fitting_config_t cal_config = {
603 			.unit_id = conf->unit,
604 			.atten = data->attenuation[cfg->channel_id],
605 			.bitwidth = data->resolution[cfg->channel_id],
606 #if CONFIG_SOC_SERIES_ESP32
607 			.default_vref = data->meas_ref_internal
608 #endif
609 		};
610 
611 		LOG_DBG("Line fitting calib [unit_id: %u, chan: %u, atten: %u, bitwidth: %u]",
612 			conf->unit, cfg->channel_id, data->attenuation[cfg->channel_id],
613 			data->resolution[cfg->channel_id]);
614 
615 		if (data->cal_handle[cfg->channel_id] != NULL) {
616 			/* delete pre-existing calib scheme */
617 			adc_cali_delete_scheme_line_fitting(data->cal_handle[cfg->channel_id]);
618 		}
619 
620 		adc_cali_create_scheme_line_fitting(&cal_config,
621 						    &data->cal_handle[cfg->channel_id]);
622 #endif /* ADC_CALI_SCHEME_LINE_FITTING_SUPPORTED */
623 	}
624 
625 #if defined(CONFIG_ADC_ESP32_DMA)
626 	if (!SOC_ADC_DIG_SUPPORTED_UNIT(conf->unit)) {
627 		LOG_ERR("ADC2 dma mode is no longer supported, please use ADC1!");
628 		return -EINVAL;
629 	}
630 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
631 
632 	/* GPIO config for ADC mode */
633 
634 	int io_num = adc_channel_io_map[conf->unit][cfg->channel_id];
635 
636 	if (io_num < 0) {
637 		LOG_ERR("Channel %u not supported!", cfg->channel_id);
638 		return -ENOTSUP;
639 	}
640 
641 	struct gpio_dt_spec gpio = {
642 		.port = conf->gpio_port,
643 		.dt_flags = 0,
644 		.pin = io_num,
645 	};
646 
647 	int err = gpio_pin_configure_dt(&gpio, GPIO_DISCONNECTED);
648 
649 	if (err) {
650 		LOG_ERR("Error disconnecting io (%d)", io_num);
651 		return err;
652 	}
653 
654 	return 0;
655 }
656 
adc_esp32_init(const struct device * dev)657 static int adc_esp32_init(const struct device *dev)
658 {
659 	struct adc_esp32_data *data = (struct adc_esp32_data *)dev->data;
660 	const struct adc_esp32_conf *conf = (struct adc_esp32_conf *)dev->config;
661 	uint32_t clock_src_hz;
662 
663 #if SOC_ADC_DIG_CTRL_SUPPORTED && !SOC_ADC_RTC_CTRL_SUPPORTED
664 	if (!device_is_ready(conf->clock_dev)) {
665 		return -ENODEV;
666 	}
667 
668 	clock_control_on(conf->clock_dev, conf->clock_subsys);
669 #endif
670 
671 	esp_clk_tree_src_get_freq_hz(ADC_DIGI_CLK_SRC_DEFAULT,
672 				     ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED, &clock_src_hz);
673 
674 	adc_oneshot_hal_cfg_t config = {
675 		.unit = conf->unit,
676 		.work_mode = ADC_HAL_SINGLE_READ_MODE,
677 		.clk_src = ADC_DIGI_CLK_SRC_DEFAULT,
678 		.clk_src_freq_hz = clock_src_hz,
679 	};
680 
681 	adc_oneshot_hal_init(&data->hal, &config);
682 
683 	sar_periph_ctrl_adc_oneshot_power_acquire();
684 
685 	if (!device_is_ready(conf->gpio_port)) {
686 		LOG_ERR("gpio0 port not ready");
687 		return -ENODEV;
688 	}
689 
690 #if defined(CONFIG_ADC_ESP32_DMA)
691 
692 	if (k_sem_init(&data->dma_conv_wait_lock, 0, 1)) {
693 		LOG_ERR("dma_conv_wait_lock initialization failed!");
694 		return -EINVAL;
695 	}
696 
697 	data->adc_hal_dma_ctx.rx_desc = k_aligned_alloc(sizeof(uint32_t), sizeof(dma_descriptor_t));
698 	if (!data->adc_hal_dma_ctx.rx_desc) {
699 		LOG_ERR("rx_desc allocation failed!");
700 		return -ENOMEM;
701 	}
702 	LOG_DBG("rx_desc = 0x%08X", (unsigned int)data->adc_hal_dma_ctx.rx_desc);
703 
704 	data->dma_buffer = k_aligned_alloc(sizeof(uint32_t), ADC_DMA_BUFFER_SIZE);
705 	if (!data->dma_buffer) {
706 		LOG_ERR("dma buffer allocation failed!");
707 		k_free(data->adc_hal_dma_ctx.rx_desc);
708 		return -ENOMEM;
709 	}
710 	LOG_DBG("data->dma_buffer = 0x%08X", (unsigned int)data->dma_buffer);
711 
712 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
713 
714 	for (uint8_t i = 0; i < SOC_ADC_MAX_CHANNEL_NUM; i++) {
715 		data->resolution[i] = ADC_RESOLUTION_MAX;
716 		data->attenuation[i] = ADC_ATTEN_DB_0;
717 		data->cal_handle[i] = NULL;
718 	}
719 
720 	/* Default reference voltage. This could be calibrated externaly */
721 	data->meas_ref_internal = ADC_ESP32_DEFAULT_VREF_INTERNAL;
722 
723 	adc_hw_calibration(conf->unit);
724 
725 	return 0;
726 }
727 
728 static DEVICE_API(adc, api_esp32_driver_api) = {
729 	.channel_setup = adc_esp32_channel_setup,
730 	.read = adc_esp32_read,
731 #ifdef CONFIG_ADC_ASYNC
732 	.read_async = adc_esp32_read_async,
733 #endif /* CONFIG_ADC_ASYNC */
734 	.ref_internal = ADC_ESP32_DEFAULT_VREF_INTERNAL,
735 };
736 
737 #define ADC_ESP32_CONF_GPIO_PORT_INIT .gpio_port = DEVICE_DT_GET(DT_NODELABEL(gpio0)),
738 
739 #if defined(CONFIG_ADC_ESP32_DMA)
740 
741 #define ADC_ESP32_CONF_DMA_INIT(n)                                                                 \
742 	.dma_dev = COND_CODE_1(DT_INST_NODE_HAS_PROP(n, dmas),     \
743 					(DEVICE_DT_GET(DT_INST_DMAS_CTLR_BY_IDX(n, 0))),           \
744 					(NULL)),                          \
745 		 .dma_channel = COND_CODE_1(DT_INST_NODE_HAS_PROP(n, dmas), \
746 					(DT_INST_DMAS_CELL_BY_IDX(n, 0, channel)),                 \
747 					(0xff)),
748 #else
749 
750 #define ADC_ESP32_CONF_DMA_INIT(inst)
751 
752 #endif /* defined(CONFIG_ADC_ESP32_DMA) */
753 
754 #define ESP32_ADC_INIT(inst)                                                                       \
755                                                                                                    \
756 	static const struct adc_esp32_conf adc_esp32_conf_##inst = {                               \
757 		.clock_dev = DEVICE_DT_GET(DT_INST_CLOCKS_CTLR(inst)),                             \
758 		.clock_subsys = (clock_control_subsys_t)DT_INST_CLOCKS_CELL(inst, offset),         \
759 		.unit = DT_PROP(DT_DRV_INST(inst), unit) - 1,                                      \
760 		.channel_count = DT_PROP(DT_DRV_INST(inst), channel_count),                        \
761 		ADC_ESP32_CONF_GPIO_PORT_INIT ADC_ESP32_CONF_DMA_INIT(inst)};                      \
762                                                                                                    \
763 	static struct adc_esp32_data adc_esp32_data_##inst = {                                     \
764 		.hal =                                                                             \
765 			{                                                                          \
766 				.dev = (adc_oneshot_soc_handle_t)DT_INST_REG_ADDR(inst),           \
767 			},                                                                         \
768 	};                                                                                         \
769                                                                                                    \
770 	DEVICE_DT_INST_DEFINE(inst, &adc_esp32_init, NULL, &adc_esp32_data_##inst,                 \
771 			      &adc_esp32_conf_##inst, POST_KERNEL, CONFIG_ADC_INIT_PRIORITY,       \
772 			      &api_esp32_driver_api);
773 
774 DT_INST_FOREACH_STATUS_OKAY(ESP32_ADC_INIT)
775