# Analog to Digital Converter (ADC) Oneshot Mode Driver

[中文]

## Introduction

This document describes the ADC oneshot mode driver on ESP32-H2.

Oneshot mode allows you to perform single, on-demand ADC conversions on selected analog input channels. It is suitable for applications that require infrequent or triggered sampling, as opposed to continuous data acquisition.

To perform continuous data acquisition, ESP32-H2 provides ADC Continuous Mode Driver.

## Functional Overview

The following sections of this document cover the typical steps to install and operate an ADC:

- Resource Allocation - covers which parameters should be set up to get an ADC handle and how to recycle the resources when ADC finishes working.

- Unit Configuration - covers the parameters that should be set up to configure the ADC unit, so as to get ADC conversion raw result.

- Read Conversion Result - covers how to get ADC conversion raw result.

- Hardware Limitations - describes the ADC-related hardware limitations.

- Power Management - covers power management-related information.

- IRAM Safe - describes tips on how to read ADC conversion raw results when the cache is disabled.

- Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver.

- Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior.

### Resource Allocation

The ADC oneshot mode driver is implemented based on ESP32-H2 SAR ADC module. Different ESP chips might have different numbers of independent ADCs. From the oneshot mode driver's point of view, an ADC instance is represented by `adc_oneshot_unit_handle_t`.

To install an ADC instance, set up the required initial configuration structure `adc_oneshot_unit_init_cfg_t`:

- `adc_oneshot_unit_init_cfg_t::unit_id` selects the ADC. Please refer to the datasheet to know dedicated analog IOs for this ADC.

- `adc_oneshot_unit_init_cfg_t::clk_src` selects the source clock of the ADC. If set to 0, the driver will fall back to using a default clock source, see `adc_oneshot_clk_src_t` to know the details.

- `adc_oneshot_unit_init_cfg_t::ulp_mode` sets if the ADC will be working under ULP mode.

After setting up the initial configurations for the ADC, call `adc_oneshot_new_unit()` with the prepared `adc_oneshot_unit_init_cfg_t`. This function will return an ADC unit handle if the allocation is successful.

This function may fail due to various errors such as invalid arguments, insufficient memory, etc. Specifically, when the to-be-allocated ADC instance is registered already, this function will return `ESP_ERR_NOT_FOUND` error. Number of available ADC(s) is recorded by `SOC_ADC_PERIPH_NUM`.

If a previously created ADC instance is no longer required, you should recycle the ADC instance by calling `adc_oneshot_del_unit()`, related hardware and software resources will be recycled as well.

#### Create an ADC Unit Handle Under Normal Oneshot Mode

    adc_oneshot_unit_handle_t adc1_handle;
    adc_oneshot_unit_init_cfg_t init_config1 = {
        .unit_id = ADC_UNIT_1,
        .ulp_mode = ADC_ULP_MODE_DISABLE,
    };
    ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config1, &adc1_handle));

#### Recycle the ADC Unit

    ESP_ERROR_CHECK(adc_oneshot_del_unit(adc1_handle));

### Unit Configuration

After an ADC instance is created, set up the `adc_oneshot_chan_cfg_t` to configure ADC IOs to measure analog signal:

- `adc_oneshot_chan_cfg_t::atten`, ADC attenuation. Refer to Datasheet > `ADC Characteristics`.

- `adc_oneshot_chan_cfg_t::bitwidth`, the bitwidth of the raw conversion result.

Note

For the IO corresponding ADC channel number, check datasheet to know the ADC IOs.

Additionally, `adc_continuous_io_to_channel()` and `adc_continuous_channel_to_io()` can be used to know the ADC channels and ADC IOs.

To make these settings take effect, call `adc_oneshot_config_channel()` with the above configuration structure. You should specify an ADC channel to be configured as well. Function `adc_oneshot_config_channel()` can be called multiple times to configure different ADC channels. The Driver will save each of these channel configurations internally.

#### Configure Two ADC Channels

    adc_oneshot_chan_cfg_t config = {
        .bitwidth = ADC_BITWIDTH_DEFAULT,
        .atten = ADC_ATTEN_DB_12,
    };
    ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN0, &config));
    ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, EXAMPLE_ADC1_CHAN1, &config));

### Read Conversion Result

After above configurations, the ADC is ready to measure the analog signal(s) from the configured ADC channel(s). Call `adc_oneshot_read()` to get the conversion raw result of an ADC channel.

- `adc_oneshot_read()` is safe to use. ADC(s) are shared by some other drivers/peripherals, see Hardware Limitations. This function uses mutexes to avoid concurrent hardware usage. Therefore, this function should not be used in an ISR context. This function may fail when the ADC is in use by other drivers/peripherals, and return `ESP_ERR_TIMEOUT`. Under this condition, the ADC raw result is invalid.

This function will fail due to invalid arguments.

The ADC conversion results read from this function are raw data. To calculate the voltage based on the ADC raw results, this formula can be used:

    Vout = Dout * Vmax / Dmax       (1)

where:

Vout | Digital output result, standing for the voltage.
--- | ---
Dout | ADC raw digital reading result.
Vmax | Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to TRM > `On-Chip Sensor and Analog Signal Processing`.
Dmax | Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where bitwidth is the `adc_oneshot_chan_cfg_t::bitwidth` configured before.

To do further calibration to convert the ADC raw result to voltage in mV, please refer to calibration doc Analog to Digital Converter (ADC) Calibration Driver.

#### Read Raw Result

    ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN0, &adc_raw[0][0]));
    ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN0, adc_raw[0][0]);

    ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, EXAMPLE_ADC1_CHAN1, &adc_raw[0][1]));
    ESP_LOGI(TAG, "ADC%d Channel[%d] Raw Data: %d", ADC_UNIT_1 + 1, EXAMPLE_ADC1_CHAN1, adc_raw[0][1]);

### Hardware Limitations

- Random Number Generator (RNG) uses ADC as an input source. When ADC `adc_oneshot_read()` works, the random number generated from RNG will be less random.

- A specific ADC unit can only work under one operating mode at any one time, either continuous mode or oneshot mode. `adc_oneshot_read()` has provided the protection.

### Power Management

When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the system clock frequency may be adjusted when the system is in an idle state. However, the ADC oneshot mode driver works in a polling routine, the `adc_oneshot_read()` will poll the CPU until the function returns. During this period of time, the task in which ADC oneshot mode driver resides will not be blocked. Therefore the clock frequency is stable when reading.

### IRAM Safe

By default, all the ADC oneshot mode driver APIs are not supposed to be run when the Cache is disabled. Cache may be disabled due to many reasons, such as Flash writing/erasing, OTA, etc. If these APIs execute when the Cache is disabled, you will probably see errors like `Illegal Instruction` or `Load/Store Prohibited`.

### Thread Safety

- `adc_oneshot_new_unit()`

- `adc_oneshot_config_channel()`

- `adc_oneshot_read()`

- `adc_oneshot_del_unit()`

Above functions are guaranteed to be thread-safe. Therefore, you can call them from different RTOS tasks without protection by extra locks.

### Kconfig Options

- CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM controls where to place the ADC fast read function (IRAM or Flash), see IRAM Safe for more details.

## Application Examples

- peripherals/adc/oneshot_read demonstrates how to obtain a one-shot ADC reading from a GPIO pin using the ADC one-shot mode driver and how to use the ADC Calibration functions to obtain a calibrated result in mV on ESP32-H2.

## API Reference

### Header File

- components/esp_adc/include/esp_adc/adc_oneshot.h

- This header file can be included with:

  >     #include "esp_adc/adc_oneshot.h"

- This header file is a part of the API provided by the `esp_adc` component. To declare that your component depends on `esp_adc`, add the following to your CMakeLists.txt:

  >     REQUIRES esp_adc

  > or

  >     PRIV_REQUIRES esp_adc

### Functions

esp_err_t adc_oneshot_new_unit(const adc_oneshot_unit_init_cfg_t *init_config, adc_oneshot_unit_handle_t *ret_unit)

  Create a handle to a specific ADC unit.

  Note

  This API is thread-safe. For more details, see ADC programming guide

  Parameters:

    - init_config -- [in] Driver initial configurations

    - ret_unit -- [out] ADC unit handle

  Returns:

    - ESP_OK: On success

    - ESP_ERR_INVALID_ARG: Invalid arguments

    - ESP_ERR_NO_MEM: No memory

    - ESP_ERR_NOT_FOUND: The ADC peripheral to be claimed is already in use

    - ESP_FAIL: Clock source isn't initialised correctly

esp_err_t adc_oneshot_config_channel(adc_oneshot_unit_handle_t handle, adc_channel_t channel, const adc_oneshot_chan_cfg_t *config)

  Set ADC oneshot mode required configurations.

  Note

  This API is thread-safe. For more details, see ADC programming guide

  Parameters:

    - handle -- [in] ADC handle

    - channel -- [in] ADC channel to be configured

    - config -- [in] ADC configurations

  Returns:

    - ESP_OK: On success

    - ESP_ERR_INVALID_ARG: Invalid arguments

esp_err_t adc_oneshot_read(adc_oneshot_unit_handle_t handle, adc_channel_t chan, int *out_raw)

  Get one ADC conversion raw result.

  Note

  This API is thread-safe. For more details, see ADC programming guide

  Note

  This API should NOT be called in an ISR context

  Parameters:

    - handle -- [in] ADC handle

    - chan -- [in] ADC channel

    - out_raw -- [out] ADC conversion raw result

  Returns:

    - ESP_OK: On success

    - ESP_ERR_INVALID_ARG: Invalid arguments

    - ESP_ERR_TIMEOUT: Timeout, the ADC result is invalid

esp_err_t adc_oneshot_del_unit(adc_oneshot_unit_handle_t handle)

  Delete the ADC unit handle.

  Note

  This API is thread-safe. For more details, see ADC programming guide

  Parameters:

    handle -- [in] ADC handle

  Returns:

    - ESP_OK: On success

    - ESP_ERR_INVALID_ARG: Invalid arguments

    - ESP_ERR_NOT_FOUND: The ADC peripheral to be disclaimed isn't in use

esp_err_t adc_oneshot_io_to_channel(int io_num, adc_unit_t *const unit_id, adc_channel_t *const channel)

  Get ADC channel from the given GPIO number.

  Parameters:

    - io_num -- [in] GPIO number

    - unit_id -- [out] ADC unit

    - channel -- [out] ADC channel

  Returns:

    - ESP_OK: On success

    - ESP_ERR_INVALID_ARG: Invalid argument

    - ESP_ERR_NOT_FOUND: The IO is not a valid ADC pad

esp_err_t adc_oneshot_channel_to_io(adc_unit_t unit_id, adc_channel_t channel, int *const io_num)

  Get GPIO number from the given ADC channel.

  Parameters:

    - unit_id -- [in] ADC unit

    - channel -- [in] ADC channel

    - io_num -- [out] GPIO number

    - - -- ESP_OK: On success

      - ESP_ERR_INVALID_ARG: Invalid argument

esp_err_t adc_oneshot_get_calibrated_result(adc_oneshot_unit_handle_t handle, adc_cali_handle_t cali_handle, adc_channel_t chan, int *cali_result)

  Convenience function to get ADC calibrated result.

  This is an all-in-one function which does:

  - oneshot read ADC raw result

  - calibrate the raw result and convert it into calibrated result (in mV)

  Parameters:

    - handle -- [in] ADC oneshot handle, you should call adc_oneshot_new_unit() to get this handle

    - cali_handle -- [in] ADC calibration handle, you should call adc_cali_create_scheme_x() in adc_cali_scheme.h to create a handle

    - chan -- [in] ADC channel

    - cali_result -- [out] Calibrated ADC result (in mV)

  Returns:

    - ESP_OK Other return errors from adc_oneshot_read() and adc_cali_raw_to_voltage()

### Structures

struct adc_oneshot_unit_init_cfg_t

  ADC oneshot driver initial configurations.

  Public Members

  adc_unit_t unit_id

    ADC unit.

  adc_oneshot_clk_src_t clk_src

    Clock source.

  adc_ulp_mode_t ulp_mode

    ADC controlled by ULP, see `adc_ulp_mode_t`

struct adc_oneshot_chan_cfg_t

  ADC channel configurations.

  Public Members

  adc_atten_t atten

    ADC attenuation.

  adc_bitwidth_t bitwidth

    ADC conversion result bits.

### Type Definitions

typedef struct adc_oneshot_unit_ctx_t *adc_oneshot_unit_handle_t

  Type of ADC unit handle for oneshot mode.

Was this page helpful?

- Thank you! We received your feedback.
- If you have any comments, fill in Espressif Documentation Feedback Form.

- We value your feedback.
- Let us know how we can improve this page by filling in Espressif Documentation Feedback Form.