1 /*
2 * SPDX-FileCopyrightText: 2019-2024 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <esp_types.h>
8 #include "sdkconfig.h"
9 #include "esp_log.h"
10 #include "esp_check.h"
11 #include "freertos/FreeRTOS.h"
12 #include "esp_private/periph_ctrl.h"
13 #include "esp_private/adc_private.h"
14 #include "esp_private/adc_share_hw_ctrl.h"
15 #include "driver/gpio.h"
16 #include "hal/adc_hal.h"
17 #include "hal/adc_hal_common.h"
18 #include "soc/adc_periph.h"
19
20
21 static const char *TAG = "adc_common";
22
23 /*---------------------------------------------------------------
24 ADC IOs
25 ---------------------------------------------------------------*/
adc_io_to_channel(int io_num,adc_unit_t * unit_id,adc_channel_t * channel)26 esp_err_t adc_io_to_channel(int io_num, adc_unit_t *unit_id, adc_channel_t *channel)
27 {
28 ESP_RETURN_ON_FALSE(GPIO_IS_VALID_GPIO(io_num), ESP_ERR_INVALID_ARG, TAG, "invalid gpio number");
29 ESP_RETURN_ON_FALSE(unit_id && channel, ESP_ERR_INVALID_ARG, TAG, "invalid argument: null pointer");
30
31 bool found = false;
32 for (int i = 0; i < SOC_ADC_PERIPH_NUM; i++) {
33 for (int j = 0; j < SOC_ADC_MAX_CHANNEL_NUM; j++) {
34 if (adc_channel_io_map[i][j] == io_num) {
35 *channel = j;
36 *unit_id = i;
37 found = true;
38 }
39 }
40 }
41 return (found) ? ESP_OK : ESP_ERR_NOT_FOUND;
42 }
43
adc_channel_to_io(adc_unit_t unit_id,adc_channel_t channel,int * io_num)44 esp_err_t adc_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *io_num)
45 {
46 ESP_RETURN_ON_FALSE(unit_id < SOC_ADC_PERIPH_NUM, ESP_ERR_INVALID_ARG, TAG, "invalid unit");
47 ESP_RETURN_ON_FALSE(channel < SOC_ADC_CHANNEL_NUM(unit_id), ESP_ERR_INVALID_ARG, TAG, "invalid channel");
48 ESP_RETURN_ON_FALSE(io_num, ESP_ERR_INVALID_ARG, TAG, "invalid argument: null pointer");
49
50 *io_num = adc_channel_io_map[unit_id][channel];
51 return ESP_OK;
52 }
53
54 #if SOC_ADC_CALIBRATION_V1_SUPPORTED
55 /*---------------------------------------------------------------
56 ADC Hardware Calibration
57 ---------------------------------------------------------------*/
adc_hw_calibration(void)58 static void adc_hw_calibration(void)
59 {
60 //Calculate all ICode
61 for (int i = 0; i < SOC_ADC_PERIPH_NUM; i++) {
62 adc_hal_calibration_init(i);
63 for (int j = 0; j < SOC_ADC_ATTEN_NUM; j++) {
64 /**
65 * This may get wrong when attenuations are NOT consecutive on some chips,
66 * update this when bringing up the calibration on that chip
67 */
68 adc_calc_hw_calibration_code(i, j);
69 #if SOC_ADC_CALIB_CHAN_COMPENS_SUPPORTED
70 /* Load the channel compensation from efuse */
71 for (int k = 0; k < SOC_ADC_CHANNEL_NUM(i); k++) {
72 adc_load_hw_calibration_chan_compens(i, k, j);
73 }
74 #endif
75 }
76 }
77 }
78 #endif //#if SOC_ADC_CALIBRATION_V1_SUPPORTED
79