1Analog to Digital Converter (ADC)
2=================================
3
4{IDF_TARGET_ADC1_CH0: default="GPIO 0", esp32="GPIO 36"}
5{IDF_TARGET_ADC2_CH7: default="GPIO 0", esp32="GPIO 27"}
6
7
8ADC Channels
9------------
10
11{IDF_TARGET_ADC_TOTAL_CHAN:default="20", esp32="18", esp32s2="20", esp32c3="6"}
12{IDF_TARGET_ADC_UNIT_NUM:default="2"}
13
14The {IDF_TARGET_NAME} integrates {IDF_TARGET_ADC_UNIT_NUM} SAR (`Successive Approximation Register <https://en.wikipedia.org/wiki/Successive_approximation_ADC>`_) ADCs, supporting a total of {IDF_TARGET_ADC_TOTAL_CHAN} measurement channels (analog enabled pins).
15
16These channels are supported:
17
18.. only:: esp32
19
20    ADC1:
21        - 8 channels: GPIO32 - GPIO39
22    ADC2:
23        - 10 channels: GPIO0, GPIO2, GPIO4, GPIO12 - GPIO15, GOIO25 - GPIO27
24
25.. only:: esp32s2 or esp32s3
26
27    ADC1:
28        - 10 channels: GPIO1 - GPIO10
29    ADC2:
30        - 10 channels: GPIO11 - GPIO20
31
32.. only:: esp32c3
33
34    ADC1:
35        - 5 channels: GPIO0 - GPIO4
36    ADC2:
37        - 1 channels: GPIO5
38
39
40.. _adc_attenuation:
41
42ADC Attenuation
43---------------
44{IDF_TARGET_ADC_V_MIN_ATTEN0:default="0", esp32="100"}
45{IDF_TARGET_ADC_V_MAX_ATTEN0:default="950", esp32s2="750", esp32c3="750", esp32s3="950"}
46
47{IDF_TARGET_ADC_V_MIN_ATTEN1:default="0", esp32="100"}
48{IDF_TARGET_ADC_V_MAX_ATTEN1:default="1250", esp32s2="1050", esp32c3="1050", esp32s3="1250"}
49
50{IDF_TARGET_ADC_V_MIN_ATTEN2:default="0", esp32="150"}
51{IDF_TARGET_ADC_V_MAX_ATTEN2:default="1750", esp32s2="1300", esp32c3="1300", esp32s3="1750"}
52
53{IDF_TARGET_ADC_V_MIN_ATTEN3:default="0", esp32="150"}
54{IDF_TARGET_ADC_V_MAX_ATTEN3:default="2450", esp32s2="2500", esp32c3="2500", esp32s3="3100"}
55
56
57Vref is the reference voltage used internally by {IDF_TARGET_NAME} ADCs for measuring the input voltage. The {IDF_TARGET_NAME} ADCs can measure analog voltages from 0 V to Vref. Among different chips, the Vref varies, the median is 1.1 V. In order to convert voltages larger than Vref, input voltages can be attenuated before being input to the ADCs. There are 4 available attenuation options, the higher the attenuation is, the higher the measurable input voltage could be.
58
59=====================  =========================================================================================================
60Attenuation            Measurable input voltage range
61=====================  =========================================================================================================
62``ADC_ATTEN_DB_0``     {IDF_TARGET_ADC_V_MIN_ATTEN0} mV ~ {IDF_TARGET_ADC_V_MAX_ATTEN0} mV
63``ADC_ATTEN_DB_2_5``   {IDF_TARGET_ADC_V_MIN_ATTEN1} mV ~ {IDF_TARGET_ADC_V_MAX_ATTEN1} mV
64``ADC_ATTEN_DB_6``     {IDF_TARGET_ADC_V_MIN_ATTEN2} mV ~ {IDF_TARGET_ADC_V_MAX_ATTEN2} mV
65``ADC_ATTEN_DB_11``    {IDF_TARGET_ADC_V_MIN_ATTEN3} mV ~ {IDF_TARGET_ADC_V_MAX_ATTEN3} mV
66=====================  =========================================================================================================
67
68
69.. _adc_conversion:
70
71ADC Conversion
72--------------
73
74{IDF_TARGET_ADC_SINGLE_MAX_WIDTH:default="12", esp32s2="13}
75{IDF_TARGET_ADC_SINGLE_RAW_MAX:default="4095", esp32s2="8191"}
76{IDF_TARGET_ADC_CONTINUOUS_MAX_WIDTH:default="12", esp32s3="13}
77{IDF_TARGET_ADC_CONTINUOUS_RAW_MAX:default="4095", esp32s3="8191"}
78
79
80An ADC conversion is to convert the input analog voltage to a digital value. The ADC conversion results provided by the ADC driver APIs are raw data. Resolution of {IDF_TARGET_NAME} ADC raw results under Single Read mode is {IDF_TARGET_ADC_SINGLE_MAX_WIDTH}-bit.
81
82- :cpp:func:`adc1_get_raw`
83- :cpp:func:`adc2_get_raw`
84
85.. only:: esp32c3
86
87    - :cpp:func:`adc_digi_read_bytes`
88
89To calculate the voltage based on the ADC raw results, this formula can be used:
90
91.. parsed-literal::
92
93    Vout = Dout * Vmax / Dmax       (1)
94
95where:
96
97======  =============================================================
98Vout    Digital output result, standing for the voltage.
99Dout    ADC raw digital reading result.
100Vmax    Maximum measurable input analog voltage, see :ref:`adc_attenuation`.
101Dmax    Maximum of the output ADC raw digital reading result, which is {IDF_TARGET_ADC_SINGLE_RAW_MAX} under Single Read mode, {IDF_TARGET_ADC_CONTINUOUS_RAW_MAX} under Continuous Read mode.
102======  =============================================================
103
104For boards with eFuse ADC calibration bits, :cpp:func:`esp_adc_cal_raw_to_voltage` can be used to get the calibrated conversion results. These results stand for the actual voltage (in mV). No need to transform these data via the formula (1).
105If ADC calibration APIs are used on boards without eFuse ADC calibration bits, warnings will be generated. See :ref:`adc_calibration`.
106
107
108.. _adc_limitations:
109
110ADC Limitations
111---------------
112
113.. note::
114
115    .. only:: esp32
116
117        - Some of the ADC2 pins are used as strapping pins (GPIO 0, 2, 15) thus cannot be used freely. Such is the case in the following official Development Kits:
118        - ESP32 DevKitC: GPIO 0 cannot be used due to external auto program circuits.
119        - ESP-WROVER-KIT: GPIO 0, 2, 4 and 15 cannot be used due to external connections for different purposes.
120        - Since the ADC2 module is also used by the Wi-Fi, only one of them could get the preemption when using together, which means the :cpp:func:`adc2_get_raw` may get blocked until Wi-Fi stops, and vice versa.
121
122    .. only:: not esp32
123
124        - Since the ADC2 module is also used by the Wi-Fi, reading operation of :cpp:func:`adc2_get_raw` may fail between :cpp:func:`esp_wifi_start()` and :cpp:func:`esp_wifi_stop()`. Use the return code to see whether the reading is successful.
125
126    .. only:: esp32c3
127
128        - A specific ADC module can only work under one operating mode at any one time, either Continuous Read Mode or Single Read Mode.
129        - ADC1 and ADC2 can not work under Singel Read Mode simultaneously. One of them will get blocked until another one finishes.
130        - For continuous (DMA) read mode, the ADC sampling frequency (the ``sample_freq_hz`` member of :cpp:type:`adc_digi_config_t`) should be within ``SOC_ADC_SAMPLE_FREQ_THRES_LOW`` and ``SOC_ADC_SAMPLE_FREQ_THRES_HIGH``.
131
132Driver Usage
133------------
134
135.. only:: esp32c3
136
137    Each ADC unit supports two work modes, ADC single read mode and ADC continuous (DMA) mode. ADC single read mode is suitable for low-frequency sampling operations. ADC continuous (DMA) read mode is suitable for high-frequency continuous sampling actions.
138
139.. only:: not esp32c3
140
141    Both of the ADC units support single read mode, which is suitable for low-frequency sampling operations.
142
143.. note::
144
145    ADC readings from a pin not connected to any signal are random.
146
147.. only:: esp32c3
148
149    ADC Continuous (DMA) Read mode
150    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
151
152    To use the ADC continuous read mode driver, execute the following steps:
153
154        1. Initialize the ADC driver by calling the function :cpp:func:`adc_digi_initialize`.
155        2. Initialize the ADC controller by calling the function :cpp:func:`adc_digi_controller_config`.
156        3. Start the ADC continuous reading by calling the function :cpp:func:`adc_digi_start`.
157        4. After starting the ADC, you can get the ADC reading result by calling the function :cpp:func:`adc_digi_read_bytes`. Before stopping the ADC (by calling :cpp:func:`adc_digi_stop`), the driver will keep converting the analog data to digital data.
158        5. Stop the ADC reading by calling the function :cpp:func:`adc_digi_stop`.
159        6. Deinitialize the ADC driver by calling the function :cpp:func:`adc_digi_deinitialize`.
160
161
162    .. only:: esp32c3
163
164    The code example for using ADC continuous (DMA) read mode can be found in the :example:`peripherals/adc/dma_read` directory of ESP-IDF examples.
165
166    .. note:: See :ref:`adc_limitations` for the limitation of using ADC continuous (DMA) read mode.
167
168ADC Single Read mode
169^^^^^^^^^^^^^^^^^^^^
170
171The ADC should be configured before reading is taken.
172
173 - For ADC1, configure desired precision and attenuation by calling functions :cpp:func:`adc1_config_width` and :cpp:func:`adc1_config_channel_atten`.
174 - For ADC2, configure the attenuation by :cpp:func:`adc2_config_channel_atten`. The reading width of ADC2 is configured every time you take the reading.
175
176Attenuation configuration is done per channel, see :cpp:type:`adc1_channel_t` and :cpp:type:`adc2_channel_t`, set as a parameter of above functions.
177
178Then it is possible to read ADC conversion result with :cpp:func:`adc1_get_raw` and :cpp:func:`adc2_get_raw`. Reading width of ADC2 should be set as a parameter of :cpp:func:`adc2_get_raw` instead of in the configuration functions.
179
180Single Read mode ADC example can be found in :example:`peripherals/adc/single_read` directory of ESP-IDF examples.
181
182.. only:: esp32
183
184    It is also possible to read the internal hall effect sensor via ADC1 by calling dedicated function :cpp:func:`hall_sensor_read`. Note that even the hall sensor is internal to ESP32, reading from it uses channels 0 and 3 of ADC1 (GPIO 36 and 39). Do not connect anything else to these pins and do not change their configuration. Otherwise it may affect the measurement of low value signal from the sensor.
185
186.. only:: SOC_ULP_SUPPORTED
187
188    This API provides convenient way to configure ADC1 for reading from :doc:`ULP <../../api-guides/ulp>`. To do so, call function :cpp:func:`adc1_ulp_enable` and then set precision and attenuation as discussed above.
189
190.. only:: esp32 or esp32s2
191
192    There is another specific function :cpp:func:`adc_vref_to_gpio` used to route internal reference voltage to a GPIO pin. It comes handy to calibrate ADC reading and this is discussed in section :ref:`adc_calibration`.
193
194
195.. note:: See :ref:`adc_limitations` for the limitation of using ADC single read mode.
196
197
198Minimizing Noise
199----------------
200
201The {IDF_TARGET_NAME} ADC can be sensitive to noise leading to large discrepancies in ADC readings. Depending on the usage scenario, users may connect a bypass capacitor (e.g. a 100 nF ceramic capacitor) to the ADC input pad in use, to minimize noise. Besides, multisampling may also be used to further mitigate the effects of noise.
202
203.. only:: esp32
204
205    .. figure:: ../../../_static/diagrams/adc/adc-noise-graph.jpg
206        :align: center
207        :alt: ADC noise mitigation
208
209        Graph illustrating noise mitigation using capacitor and multisampling of 64 samples.
210
211
212.. _adc_calibration:
213
214ADC Calibration
215---------------
216
217.. only:: esp32 or esp32s2
218
219    The :component_file:`esp_adc_cal/include/esp_adc_cal.h` API provides functions to correct for differences in measured voltages caused by variation of ADC reference voltages (Vref) between chips. Per design the ADC reference voltage is 1100 mV, however the true reference voltage can range from 1000 mV to 1200 mV amongst different {IDF_TARGET_NAME}s.
220
221    .. figure:: ../../../_static/diagrams/adc/adc-vref-graph.jpg
222        :align: center
223        :alt: ADC reference voltage comparison
224
225        Graph illustrating effect of differing reference voltages on the ADC voltage curve.
226
227    Correcting ADC readings using this API involves characterizing one of the ADCs at a given attenuation to obtain a characteristics curve (ADC-Voltage curve) that takes into account the difference in ADC reference voltage. The characteristics curve is in the form of ``y = coeff_a * x + coeff_b`` and is used to convert ADC readings to voltages in mV. Calculation of the characteristics curve is based on calibration values which can be stored in eFuse or provided by the user.
228
229    Calibration Values
230    ^^^^^^^^^^^^^^^^^^
231
232    {IDF_TARGET_ADC_CALI_SOURCE: default="3", esp32="3", esp32s2="1"}
233
234    Calibration values are used to generate characteristic curves that account for the variation of ADC reference voltage of a particular {IDF_TARGET_NAME} chip. There are currently {IDF_TARGET_ADC_CALI_SOURCE} source(s) of calibration values on {IDF_TARGET_NAME}. The availability of these calibration values will depend on the type and production date of the {IDF_TARGET_NAME} chip/module.
235
236    .. only:: esp32
237
238        * **Two Point** values represent each of the ADCs’ readings at 150 mV and 850 mV. To obtain more accurate calibration results these values should be measured by user and burned into eFuse ``BLOCK3``.
239
240        * **eFuse Vref** represents the true ADC reference voltage. This value is measured and burned into eFuse ``BLOCK0`` during factory calibration.
241
242        * **Default Vref** is an estimate of the ADC reference voltage provided by the user as a parameter during characterization. If Two Point or eFuse Vref values are unavailable, **Default Vref** will be used.
243
244            Individual measurement and burning of the **eFuse Vref** has been applied to ESP32-D0WD and ESP32-D0WDQ6 chips produced on/after the 1st week of 2018. Such chips may be recognized by date codes on/later than 012018 (see Line 4 on figure below).
245
246            .. figure:: ../../../_static/chip_surface_marking.png
247                :align: center
248                :alt: ESP32 Chip Surface Marking
249
250                ESP32 Chip Surface Marking
251
252            If you would like to purchase chips or modules with calibration, double check with distributor or Espressif (sales@espressif.com) directly.
253
254            .. highlight:: none
255
256            If you are unable to check the date code (i.e. the chip may be enclosed inside a canned module, etc.), you can still verify if **eFuse Vref** is present by running the `espefuse.py <https://github.com/espressif/esptool/wiki/espefuse>`_  tool with ``adc_info`` parameter ::
257
258                $IDF_PATH/components/esptool_py/esptool/espefuse.py --port /dev/ttyUSB0 adc_info
259
260            Replace ``/dev/ttyUSB0`` with {IDF_TARGET_NAME} board's port name.
261
262            A chip that has specific **eFuse Vref** value programmed (in this case 1093 mV) will be reported as follows::
263
264                ADC VRef calibration: 1093 mV
265
266            In another example below the **eFuse Vref** is not programmed::
267
268                ADC VRef calibration: None (1100 mV nominal)
269
270            For a chip with two point calibration the message will look similar to::
271
272                ADC VRef calibration: 1149 mV
273                ADC readings stored in efuse BLK3:
274                    ADC1 Low reading  (150 mV): 306
275                    ADC1 High reading (850 mV): 3153
276                    ADC2 Low reading  (150 mV): 389
277                    ADC2 High reading (850 mV): 3206
278
279    .. only:: esp32s2
280
281        * **eFuse Two Point** values calibrates the ADC output at two different voltages. This value is measured and burned into eFuse ``BLOCK0`` during factory calibration on newly manufactured ESP32-S2 chips and modules. If you would like to purchase chips or modules with calibration, double check with distributor or Espressif (sales@espressif.com) directly.
282
283        .. highlight:: none
284
285        You can verify if **eFuse Two Point** is present by running the `espefuse.py <https://github.com/espressif/esptool/wiki/espefuse>`_  tool with ``adc_info`` parameter ::
286
287            $IDF_PATH/components/esptool_py/esptool/espefuse.py --port /dev/ttyUSB0 adc_info
288
289        Replace ``/dev/ttyUSB0`` with {IDF_TARGET_NAME} board's port name.
290
291
292
293.. only:: esp32c3 or esp32s3
294
295    {IDF_TARGET_NAME} ADC Calibration contains 2 steps: Hardware Calibration and Software Calibration.
296
297
298    Hardware Calibration
299    ^^^^^^^^^^^^^^^^^^^^
300
301    Based on series of comparisons with the reference voltage, {IDF_TARGET_NAME} ADC determines each bit of the output digital result. Per design the {IDF_TARGET_NAME} ADC reference voltage is 1100 mV, however the true reference voltage can range from 1000 mV to 1200 mV among different chips. To minimize this difference, hardware calibration is introduced.
302
303    Hardware calibration contains 2 steps:
304
305        1. Set an auto-calibration parameter of bandgap voltage reference. In this way, the difference mentioned above can be minimized.
306        2. Correct the offset of the ADC Vin-Dout characteristics. ADC characteristics is generally a function: f(x) = A * x + B, where B is the offset.
307
308        .. only:: esp32c3
309
310            An uncalibrated ADC characteristics is as follows:
311
312            .. figure:: ../../../_static/diagrams/adc/adc-uncali-raw-c3.png
313                :align: center
314                :alt: ADC uncalibrated conversion result
315
316        .. only:: esp32s3
317
318            An uncalibrated ADC characteristics is as follows:
319
320            .. figure:: ../../../_static/diagrams/adc/adc-uncali-raw-s3.png
321                :align: center
322                :alt: ADC uncalibrated conversion result
323
324
325    The offset in the uncalibrated characteristics is significant. Step 2 is to correct the offset to 0.
326
327        .. only:: esp32c3
328
329            After hardware calibration, the ADC characteristics would be like:
330
331            .. figure:: ../../../_static/diagrams/adc/adc-hw-cali-c3.png
332                :align: center
333                :alt: ADC conversion results after hardware calibration
334
335        .. only:: esp32s3
336
337            After hardware calibration, the ADC characteristics would be like:
338
339            .. figure:: ../../../_static/diagrams/adc/adc-hw-cali-s3.png
340                :align: center
341                :alt: ADC conversion results after hardware calibration
342
343    Hardware calibration is done internally by the ADC driver. The consequent results are raw data. A transformation is needed to get the final result, see :ref:`adc_conversion`.
344
345
346    Software Calibration
347    ^^^^^^^^^^^^^^^^^^^^
348
349    To convert ADC raw data to calibrated digital data, following steps should be followed:
350
351        1. Check the eFuse to know if the software calibration is supported via :cpp:func:`esp_adc_cal_check_efuse`.
352        2. Calculate the ADC calibration characteristics via :cpp:func:`esp_adc_cal_characterize`. The ADC software calibration characteristics are per ADC module and per attenuation. For example, characteristics of ADC1 channel 0 under 11 dB attenuation are the same as characteristics of ADC1 channel 2 under 11 dB attenuation. But characteristics of ADC1 channel 0 under 11 dB attenuation are different with characteristics of ADC2 channel 0 under 11 dB attenuation. Also characteristics of ADC1 channel 0 under 11 dB attenuation are different with characteristics of ADC1 channel 0 under 6 dB attenuation.
353        3. Get the actual voltage value via :cpp:func:`esp_adc_cal_raw_to_voltage`.
354
355    .. only:: esp32c3
356
357        After software calibration, the ADC characteristics would be like:
358
359            .. figure:: ../../../_static/diagrams/adc/adc-all-cali-c3.png
360                :align: center
361                :alt: ADC conversion results after hardware calibration
362
363    .. only:: esp32s3
364
365        After software calibration, the ADC characteristics would be like:
366
367            .. figure:: ../../../_static/diagrams/adc/adc-all-cali-s3.png
368                :align: center
369                :alt: ADC conversion results after hardware calibration
370
371
372    The results provided by the ADC calibration APIs indicate the actual voltage values. ADC software calibration example can be found in :example:`peripherals/adc/single_read` directory of ESP-IDF examples.
373
374
375.. only:: esp32 or esp32s2
376
377    Application Extensions
378    ----------------------
379
380    For a full example see esp-idf: :example:`peripherals/adc/single_read`
381
382    Characterizing an ADC at a particular attenuation::
383
384        #include "driver/adc.h"
385        #include "esp_adc_cal.h"
386
387        ...
388
389            //Characterize ADC at particular atten
390            esp_adc_cal_characteristics_t *adc_chars = calloc(1, sizeof(esp_adc_cal_characteristics_t));
391            esp_adc_cal_value_t val_type = esp_adc_cal_characterize(unit, atten, ADC_WIDTH_BIT_12, DEFAULT_VREF, adc_chars);
392            //Check type of calibration value used to characterize ADC
393            if (val_type == ESP_ADC_CAL_VAL_EFUSE_VREF) {
394                printf("eFuse Vref");
395            } else if (val_type == ESP_ADC_CAL_VAL_EFUSE_TP) {
396                printf("Two Point");
397            } else {
398                printf("Default");
399            }
400
401    Reading an ADC then converting the reading to a voltage::
402
403        #include "driver/adc.h"
404        #include "esp_adc_cal.h"
405
406        ...
407            uint32_t reading =  adc1_get_raw(ADC1_CHANNEL_5);
408            uint32_t voltage = esp_adc_cal_raw_to_voltage(reading, adc_chars);
409
410    Routing ADC reference voltage to GPIO, so it can be manually measured (for **Default Vref**)::
411
412        #include "driver/adc.h"
413
414        ...
415
416            esp_err_t status = adc_vref_to_gpio(ADC_UNIT_1, GPIO_NUM_25);
417            if (status == ESP_OK) {
418                printf("v_ref routed to GPIO\n");
419            } else {
420                printf("failed to route v_ref\n");
421            }
422
423GPIO Lookup Macros
424------------------
425
426There are macros available to specify the GPIO number of a ADC channel, or vice versa.
427e.g.
428
4291. ``ADC1_CHANNEL_0_GPIO_NUM`` is the GPIO number of ADC1 channel 0.
4302. ``ADC1_GPIOn_CHANNEL`` is the ADC1 channel number of GPIO n.
431
432API Reference
433-------------
434
435This reference covers three components:
436
437* :ref:`adc-api-reference-adc-driver`
438* :ref:`adc-api-reference-adc-calibration`
439* :ref:`adc-api-reference-gpio-lookup-macros`
440
441
442.. _adc-api-reference-adc-driver:
443
444ADC driver
445^^^^^^^^^^
446
447.. include-build-file:: inc/adc.inc
448
449.. include-build-file:: inc/adc_types.inc
450
451.. _adc-api-reference-adc-calibration:
452
453ADC Calibration
454^^^^^^^^^^^^^^^
455
456.. include-build-file:: inc/esp_adc_cal.inc
457
458.. _adc-api-reference-gpio-lookup-macros:
459
460GPIO Lookup Macros
461^^^^^^^^^^^^^^^^^^
462
463.. include-build-file:: inc/adc_channel.inc
464