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