data
stringlengths 512
2.99k
|
---|
[in] Length of the data frame
-
- Returns
ESP_OK on success, an error passed from the I/O driver otherwise
-
esp_err_t esp_netif_transmit_wrap(esp_netif_t *esp_netif, void *data, size_t len, void *netstack_buf)
Outputs packets from the TCP/IP stack to the media to be transmitted.
This function gets called from network stack to output packets to IO driver.
- Parameters
esp_netif -- [in] Handle to esp-netif instance
data -- [in] Data to be transmitted
len -- [in] Length of the data frame
netstack_buf -- [in] net stack buffer
-
- Returns
ESP_OK on success, an error passed from the I/O driver otherwise
-
void |
Analog to Digital Converter (ADC) Oneshot Mode Driver
Introduction
The Analog to Digital Converter is integrated on the chip and is capable of measuring analog signals from specific analog IO pins.
ESP32 has two ADC unit(s), which can be used in scenario(s) like:
Generate one-shot ADC conversion result
Generate continuous ADC conversion results
This guide introduces ADC oneshot mode conversion.
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 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_idselects the ADC. Please refer to the datasheet to know dedicated analog IOs for this ADC.
adc_oneshot_unit_init_cfg_t::clk_srcselects 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_tto know the details.
adc_oneshot_unit_init_cfg_t::ulp_modesets if the ADC will be working under ULP mode.
|
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::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 >
|
Dmax
|
Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where bitwidth is the :cpp:member::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.
|
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.
ADC2 is also used by Wi-Fi.
adc_oneshot_read()has provided protection between the Wi-Fi driver and ADC oneshot mode driver.
ESP32-DevKitC: GPIO0 cannot be used in oneshot mode, because the DevKit has used it for auto-flash.
ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes.
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
Above functions are guaranteed to be thread-safe. Therefore, you can call them from different RTOS tasks without protection by extra locks.
adc_oneshot_del_unit()is not thread-safe. Besides, concurrently calling this function may result in failures of the above thread-safe APIs.
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.
|
For ESP32-S2: If (channel < ADC_CHANNEL_MAX), The data is valid. If (channel > ADC_CHANNEL_MAX), The data is invalid.
-
struct adc_digi_output_data_t::[anonymous]::[anonymous] type1
ADC type1
-
uint16_t unit
ADC unit index info. 0: ADC1; 1: ADC2.
-
struct adc_digi_output_data_t::[anonymous]::[anonymous] type2
When the configured output format is 11bit.
-
uint16_t val
Raw data value
- uint16_t data
Type Definitions
-
typedef soc_periph_adc_digi_clk_src_t adc_oneshot_clk_src_t
Clock source type of oneshot mode which uses digital controller.
-
typedef soc_periph_adc_digi_clk_src_t adc_continuous_clk_src_t
Clock source type of continuous mode which uses digital controller.
Enumerations
-
enum adc_unit_t
ADC unit.
Values:
-
enumerator ADC_UNIT_1
SAR ADC 1.
-
enumerator ADC_UNIT_2
SAR ADC 2.
- enumerator ADC_UNIT_1
-
enum adc_channel_t
ADC channels.
Values:
-
enumerator ADC_CHANNEL_0
ADC channel.
-
enumerator ADC_CHANNEL_1
ADC channel.
-
enumerator ADC_CHANNEL_2
ADC channel.
-
enumerator ADC_CHANNEL_3
ADC channel.
-
enumerator ADC_CHANNEL_4
ADC channel.
-
enumerator ADC_CHANNEL_5
ADC channel.
-
enumerator ADC_CHANNEL_6
ADC channel.
-
enumerator ADC_CHANNEL_7
ADC channel.
-
enumerator ADC_CHANNEL_8
ADC channel.
-
enumerator ADC_CHANNEL_9
ADC channel.
- enumerator ADC_CHANNEL_0
-
enum adc_atten_t
ADC attenuation parameter. |
Different parameters determine the range of the ADC.
Values:
-
enumerator ADC_ATTEN_DB_0
No input attenuation, ADC can measure up to approx.
-
enumerator ADC_ATTEN_DB_2_5
The input voltage of ADC will be attenuated extending the range of measurement by about 2.5 dB.
-
enumerator ADC_ATTEN_DB_6
The input voltage of ADC will be attenuated extending the range of measurement by about 6 dB.
-
enumerator ADC_ATTEN_DB_12
The input voltage of ADC will be attenuated extending the range of measurement by about 12 dB.
-
enumerator ADC_ATTEN_DB_11
This is deprecated, it behaves the same as
ADC_ATTEN_DB_12
- enumerator ADC_ATTEN_DB_0
-
enum adc_bitwidth_t
Values:
-
enumerator ADC_BITWIDTH_DEFAULT
Default ADC output bits, max supported width will be selected.
-
enumerator ADC_BITWIDTH_9
ADC output width is 9Bit.
-
enumerator ADC_BITWIDTH_10
ADC output width is 10Bit.
-
enumerator ADC_BITWIDTH_11
ADC output width is 11Bit.
-
enumerator ADC_BITWIDTH_12
ADC output width is 12Bit.
-
enumerator ADC_BITWIDTH_13
ADC output width is 13Bit.
- enumerator ADC_BITWIDTH_DEFAULT
-
enum adc_ulp_mode_t
Values:
-
enumerator ADC_ULP_MODE_DISABLE
ADC ULP mode is disabled.
-
enumerator ADC_ULP_MODE_FSM
ADC is controlled by ULP FSM.
-
enumerator ADC_ULP_MODE_RISCV
ADC is controlled by ULP RISCV.
- enumerator ADC_ULP_MODE_DISABLE
-
enum adc_digi_convert_mode_t
ADC digital controller (DMA mode) work mode.
Values:
-
enumerator ADC_CONV_SINGLE_UNIT_1
Only use ADC1 for conversion.
-
enumerator ADC_CONV_SINGLE_UNIT_2
Only use ADC2 for conversion.
-
enumerator ADC_CONV_BOTH_UNIT
Use Both ADC1 and ADC2 for conversion simultaneously.
-
enumerator ADC_CONV_ALTER_UNIT
Use both ADC1 and ADC2 for conversion by turn. e.g. ADC1 -> ADC2 -> ADC1 -> ADC2 .....
- enumerator ADC_CONV_SINGLE_UNIT_1
-
enum adc_digi_output_format_t
ADC digital controller (DMA mode) output data format option.
Values:
-
enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1
-
enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE2
- enumerator ADC_DIGI_OUTPUT_FORMAT_TYPE1
-
enum adc_digi_iir_filter_t
ADC IIR Filter ID.
Values:
-
enumerator ADC_DIGI_IIR_FILTER_0
Filter 0.
-
enumerator ADC_DIGI_IIR_FILTER_1
Filter 1.
- enumerator ADC_DIGI_IIR_FILTER_0
-
enum adc_digi_iir_filter_coeff_t
IIR Filter Coefficient.
Values:
-
enumerator ADC_DIGI_IIR_FILTER_COEFF_2
|
The filter coefficient is 2.
-
enumerator ADC_DIGI_IIR_FILTER_COEFF_4
The filter coefficient is 4.
-
enumerator ADC_DIGI_IIR_FILTER_COEFF_8
The filter coefficient is 8.
-
enumerator ADC_DIGI_IIR_FILTER_COEFF_16
The filter coefficient is 16.
-
enumerator ADC_DIGI_IIR_FILTER_COEFF_64
The filter coefficient is 64 .
- enumerator ADC_DIGI_IIR_FILTER_COEFF_2
-
enum adc_monitor_id_t
ADC monitor (continuous mode) ID.
Values:
-
enumerator ADC_MONITOR_0
The monitor index 0.
-
enumerator ADC_MONITOR_1
The monitor index 1.
- enumerator ADC_MONITOR_0
Header File
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_adccomponent. 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 -- |
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 -- |
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
- adc_unit_t unit_id
-
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.
- adc_atten_t atten
Type Definitions
-
typedef struct adc_oneshot_unit_ctx_t *adc_oneshot_unit_handle_t
Type of ADC unit handle for oneshot mode. |
100,
};
ESP_ERROR_CHECK(adc_continuous_new_handle(&adc_config));
Recycle the ADC Unit
ESP_ERROR_CHECK(adc_continuous_deinit());
ADC Configurations
After the ADC continuous mode driver is initialized, set up the
adc_continuous_config_t to configure ADC IOs to measure analog signal:
adc_continuous_config_t::pattern_num: number of ADC channels that will be used.
adc_continuous_config_t::adc_pattern: list of configs for each ADC channel that will be used, see the description below.
adc_continuous_config_t::sample_freq_hz: expected ADC sampling frequency in Hz.
adc_continuous_config_t::conv_mode: continuous conversion mode.
adc_continuous_config_t::format: conversion output format.
Set
adc_digi_pattern_config_t with the following process:
adc_digi_pattern_config_t::atten: |
the IO corresponding ADC channel number. See the note below.
adc_digi_pattern_config_t::unit: the ADC that the IO is subordinate to.
adc_digi_pattern_config_t::bit_width: the bitwidth of the raw conversion result.
Note
For the IO corresponding ADC channel number, check TRM to acquire the ADC IOs. Besides,
adc_continuous_io_to_channel() and
adc_continuous_channel_to_io() can be used to acquire the ADC channels and ADC IOs.
To make these settings take effect, call
adc_continuous_config() with the configuration structure above. This API may fail due to reasons like
ESP_ERR_INVALID_ARG. When it returns
ESP_ERR_INVALID_STATE, this means the ADC continuous mode driver is started, you should not call this API at this moment.
|
See ADC continuous mode example peripherals/adc/continuous_read to see configuration codes.
ADC Control
Start and Stop
Calling
adc_continuous_start() makes the ADC start to measure analog signals from the configured ADC channels, and generate the conversion results.
On the contrary, calling
adc_continuous_stop() stops the ADC conversion.
ESP_ERROR_CHECK(adc_continuous_stop());
Register Event Callbacks
By calling
adc_continuous_register_event_callbacks(), you can hook your own function to the driver ISR. |
|
Vmax
|
Maximum measurable input analog voltage, this is related to the ADC attenuation, please refer to the On-Chip Sensor and Analog Signal Processing chapter in TRM.
|
Dmax
|
Maximum of the output ADC raw digital reading result, which is 2^bitwidth, where the bitwidth is the
To do further calibration to convert the ADC raw result to voltage in mV, please refer to Analog to Digital Converter (ADC) Calibration Driver.
Hardware Limitations
A specific ADC unit can only work under one operating mode at any one time, either continuous mode or one-shot mode.
adc_continuous_start()has provided the protection.
|
When ADC continuous mode driver works, the random number generated from RNG will be less random.
ADC2 is also used by Wi-Fi.
adc_continuous_start()has provided the protection between Wi-Fi driver and ADC continuous mode driver.
ADC continuous mode driver uses I2S0 peripheral as hardware DMA FIFO. Therefore, if I2S0 is in use already, the
adc_continuous_new_handle()will return
ESP_ERR_NOT_FOUND.
ESP32 DevKitC: GPIO 0 cannot be used due to external auto program circuits.
ESP-WROVER-KIT: GPIO 0, 2, 4, and 15 cannot be used due to external connections for different purposes.
Power Management
When power management is enabled, i.e., CONFIG_PM_ENABLE is on, the APB clock frequency may be adjusted when the system is in an idle state, thus potentially changing the behavior of ADC continuous conversion.
However, the continuous mode driver can prevent this change by acquiring a power management lock of type
ESP_PM_APB_FREQ_MAX. The lock is acquired after the continuous conversion is started by
adc_continuous_start(). Similarly, the lock will be released after
adc_continuous_stop(). Therefore,
adc_continuous_start() and
adc_continuous_stop() should appear in pairs, otherwise, the power management will be out of action.
IRAM Safe
All the ADC continuous mode driver APIs are not IRAM-safe. They are not supposed to be run when the Cache is disabled. By enabling the Kconfig option CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE, the driver's internal ISR handler is IRAM-safe, which means even when the Cache is disabled, the driver will still save the conversion results into its internal pool.
Thread Safety
ADC continuous mode driver APIs are not guaranteed to be thread-safe. However, the share hardware mutual exclusion is provided by the driver. See Hardware Limitations for more details.
|
Application Examples
ADC continuous mode example: peripherals/adc/continuous_read.
API Reference
Header File
This header file can be included with:
#include "esp_adc/adc_continuous.h"
This header file is a part of the API provided by the
esp_adccomponent. 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_continuous_new_handle(const adc_continuous_handle_cfg_t *hdl_config, adc_continuous_handle_t *ret_handle)
Initialize ADC continuous driver and get a handle to it.
- Parameters
hdl_config -- |
[out] ADC continuous mode driver handle
-
- Returns
ESP_ERR_INVALID_ARG If the combination of arguments is invalid.
ESP_ERR_NOT_FOUND No free interrupt found with the specified flags
ESP_ERR_NO_MEM If out of memory
ESP_OK On success
-
-
esp_err_t adc_continuous_config(adc_continuous_handle_t handle, const adc_continuous_config_t *config)
Set ADC continuous mode required configurations.
- Parameters
handle -- [in] ADC continuous mode driver handle
config -- [in] Refer to
adc_digi_config_t.
-
- Returns
ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment
ESP_ERR_INVALID_ARG: If the combination of arguments is invalid.
ESP_OK: On success
-
-
esp_err_t adc_continuous_register_event_callbacks(adc_continuous_handle_t handle, const adc_continuous_evt_cbs_t *cbs, void *user_data)
Register callbacks.
Note
User can deregister a previously registered callback by calling this function and setting the to-be-deregistered callback member in the
cbsstructure to NULL.
Note
When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables (including
user_data) should be in internal RAM as well.
Note
You should only call this API when the ADC continuous mode driver isn't started. Check return value to know this.
- Parameters
handle -- [in] ADC continuous mode driver handle
cbs -- [in] Group of callback functions
user_data -- [in] User data, which will be delivered to the callback functions directly
-
- Returns
ESP_OK: On success
ESP_ERR_INVALID_ARG: Invalid arguments
ESP_ERR_INVALID_STATE: Driver state is invalid, you shouldn't call this API at this moment
-
-
esp_err_t adc_continuous_start(adc_continuous_handle_t handle)
Start the ADC under continuous mode. After this, the hardware starts working.
- Parameters
handle -- [in] ADC continuous mode driver handle
- Returns
ESP_ERR_INVALID_STATE Driver state is invalid.
ESP_OK On success
-
-
esp_err_t adc_continuous_read(adc_continuous_handle_t handle, uint8_t *buf, uint32_t length_max, uint32_t *out_length, uint32_t timeout_ms)
Read bytes from ADC under continuous mode.
- Parameters
handle -- [in] ADC continuous mode driver handle
buf -- [out] Conversion result buffer to read from ADC. Suggest convert to
adc_digi_output_data_tfor
ADC Conversion Results. See the subsection
Driver Backgroundsin this header file to learn about this concept.
length_max -- [in] Expected length of the Conversion Results read from the ADC, in bytes.
|
[in] Time to wait for data via this API, in millisecond.
-
- Returns
ESP_ERR_INVALID_STATE Driver state is invalid. Usually it means the ADC sampling rate is faster than the task processing rate.
ESP_ERR_TIMEOUT Operation timed out
ESP_OK On success
-
-
esp_err_t adc_continuous_stop(adc_continuous_handle_t handle)
Stop the ADC. After this, the hardware stops working.
- Parameters
handle -- [in] ADC continuous mode driver handle
- Returns
ESP_ERR_INVALID_STATE Driver state is invalid.
ESP_OK On success
-
-
esp_err_t adc_continuous_deinit(adc_continuous_handle_t handle)
Deinitialize the ADC continuous driver.
- Parameters
handle -- [in] ADC continuous mode driver handle
- Returns
ESP_ERR_INVALID_STATE Driver state is invalid.
ESP_OK On success
-
-
esp_err_t adc_continuous_flush_pool(adc_continuous_handle_t handle)
|
[in] ADC unit
channel -- [in] ADC channel
io_num -- [out] GPIO number
- -- ESP_OK: On success
ESP_ERR_INVALID_ARG: Invalid argument
-
-
Structures
-
struct adc_continuous_handle_cfg_t
ADC continuous mode driver initial configurations.
Public Members
-
uint32_t max_store_buf_size
Max length of the conversion results that driver can store, in bytes.
-
uint32_t conv_frame_size
Conversion frame size, in bytes. This should be in multiples of
SOC_ADC_DIGI_DATA_BYTES_PER_CONV.
-
uint32_t flush_pool
Flush the internal pool when the pool is full.
-
struct adc_continuous_handle_cfg_t::[anonymous] flags
Driver flags.
- uint32_t max_store_buf_size
-
struct adc_continuous_config_t
ADC continuous mode driver configurations.
Public Members
-
uint32_t pattern_num
Number of ADC channels that will be used.
-
adc_digi_pattern_config_t *adc_pattern
List of configs for each ADC channel that will be used.
-
uint32_t sample_freq_hz
The expected ADC sampling frequency in Hz. |
Please refer to
soc/soc_caps.hto know available sampling frequency range
-
adc_digi_convert_mode_t conv_mode
ADC DMA conversion mode, see
adc_digi_convert_mode_t.
-
adc_digi_output_format_t format
ADC DMA conversion output format, see
adc_digi_output_format_t.
- uint32_t pattern_num
-
struct adc_continuous_evt_data_t
Event data structure.
Note
The
conv_frame_bufferis maintained by the driver itself, so never free this piece of memory.
-
struct adc_continuous_evt_cbs_t
Group of ADC continuous mode callbacks.
Note
These callbacks are all running in an ISR environment.
Note
When CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. Involved variables should be in internal RAM as well.
Public Members
-
adc_continuous_callback_t on_conv_done
Event callback, invoked when one conversion frame is done. See the subsection
Driver Backgroundsin this header file to learn about the
conversion frameconcept.
-
adc_continuous_callback_t on_pool_ovf
Event callback, invoked when the internal pool is full.
- adc_continuous_callback_t on_conv_done
Macros
-
ADC_MAX_DELAY
ADC read max timeout value, it may make the
adc_continuous_readblock forever if the OS supports.
|
Type Definitions
-
typedef struct adc_continuous_ctx_t *adc_continuous_handle_t
Type of adc continuous mode driver handle.
-
typedef bool (*adc_continuous_callback_t)(adc_continuous_handle_t handle, const adc_continuous_evt_data_t *edata, void *user_data)
Prototype of ADC continuous mode event callback.
- Param handle
[in] ADC continuous mode driver handle
- Param edata
[in] Pointer to ADC continuous mode event data
- Param user_data
[in] User registered context, registered when in
adc_continuous_register_event_callbacks()
- Return
Whether a high priority task is woken up by this function |
Analog to Digital Converter (ADC) Calibration Driver
Introduction
In ESP32, the digital-to-analog converter (ADC) compares the input analog voltage to the reference, and determines each bit of the output digital result. By design, the ADC reference voltage for ESP32 is 1100 mV. However, the true reference voltage can range from 1000 mV to 1200 mV among different chips. This guide introduces the ADC calibration driver to minimize the effect of different reference voltages, and get more accurate output results.
Functional Overview
The following sections of this document cover the typical steps to install and use the ADC calibration driver:
Calibration Scheme Creation - covers how to create a calibration scheme handle and delete the calibration scheme handle.
Result Conversion - covers how to convert ADC raw result to calibrated result.
Thread Safety - lists which APIs are guaranteed to be thread-safe by the driver.
Minimize Noise - describes a general way to minimize the noise.
Kconfig Options - lists the supported Kconfig options that can be used to make a different effect on driver behavior.
|
Calibration Scheme Creation
The ADC calibration driver provides ADC calibration scheme(s). From the calibration driver's point of view, an ADC calibration scheme is created for an ADC calibration handle
adc_cali_handle_t.
adc_cali_check_scheme() can be used to know which calibration scheme is supported on the chip. If you already know the supported schemes, this step can be skipped. Just call the corresponding function to create the scheme handle.
If you use your custom ADC calibration schemes, you could either modify this function
adc_cali_check_scheme(), or just skip this step and call your custom creation function.
|
Normally this can be simply set to 0. Line Fitting scheme does not rely on this value. However, if the Line Fitting scheme required eFuse bits are not burned on your board, the driver will rely on this value to do the calibration.
You can use
adc_cali_scheme_line_fitting_check_efuse() to check the eFuse bits. Normally the Line Fitting scheme eFuse value is
ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP or
ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF. This means the Line Fitting scheme uses calibration parameters burned in the eFuse to do the calibration.
When the Line Fitting scheme eFuse value is
ADC_CALI_LINE_FITTING_EFUSE_VAL_DEFAULT_VREF, you need to set the
esp_adc_cali_line_fitting_init::default_vref. Default vref is an estimate of the ADC reference voltage provided as a parameter during calibration.
After setting up the configuration structure, call
adc_cali_create_scheme_line_fitting() to create a Line Fitting calibration scheme handle.
ESP_LOGI(TAG, "calibration scheme version is %s", "Line Fitting");
adc_cali_line_fitting_config_t cali_config = {
.unit_id = unit,
.atten = atten,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
ESP_ERROR_CHECK(adc_cali_create_scheme_line_fitting(&cali_config, &handle));
When the ADC calibration is no longer used, please delete the calibration scheme handle by calling
adc_cali_delete_scheme_line_fitting().
Delete Line Fitting Scheme
ESP_LOGI(TAG, "delete %s calibration scheme", "Line Fitting");
ESP_ERROR_CHECK(adc_cali_delete_scheme_line_fitting(handle));
Note
If you want to use your custom calibration schemes, you could provide a creation function to create your calibration scheme handle. Check the function table
adc_cali_scheme_t in
components/esp_adc/interface/adc_cali_interface.h to know the ESP ADC calibration interface.
Result Conversion
After setting up the calibration characteristics, you can call
adc_cali_raw_to_voltage() to convert the ADC raw result into calibrated result. The calibrated result is in the unit of mV. This function may fail due to an invalid argument. Especially, if this function returns
ESP_ERR_INVALID_STATE, this means the calibration scheme is not created. You need to create a calibration scheme handle, use
adc_cali_check_scheme() to know the supported calibration scheme. On the other hand, you could also provide a custom calibration scheme and create the handle.
|
Therefore, you can call them from different RTOS tasks without protection by extra locks.
Other functions that take the
adc_cali_handle_t as the first positional parameter are not thread-safe, you should avoid calling them from multiple tasks.
Kconfig Options
CONFIG_ADC_CAL_EFUSE_TP_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to
ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_TP.
CONFIG_ADC_CAL_EFUSE_VREF_ENABLE - disable this to decrease the code size, if the calibration eFuse value is not set to
ADC_CALI_LINE_FITTING_EFUSE_VAL_EFUSE_VREF.
CONFIG_ADC_CAL_LUT_ENABLE - disable this to decrease the code size, if you do not calibrate the ADC raw results under
ADC_ATTEN_DB_12.
Minimize Noise
The ESP32 ADC is sensitive to noise, leading to large discrepancies in ADC readings. Depending on the usage scenario, you may need to 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.
API Reference
Header File
This header file can be included with:
#include "esp_adc/adc_cali.h"
This header file is a part of the API provided by the
esp_adccomponent. 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_cali_check_scheme(adc_cali_scheme_ver_t *scheme_mask)
Check the supported ADC calibration scheme.
- Parameters
scheme_mask -- |
No supported calibration scheme
-
-
esp_err_t adc_cali_raw_to_voltage(adc_cali_handle_t handle, int raw, int *voltage)
Convert ADC raw data to calibrated voltage.
- Parameters
handle -- [in] ADC calibration handle
raw -- [in] ADC raw data
voltage -- [out] Calibrated ADC voltage (in mV)
-
- Returns
ESP_OK: On success
ESP_ERR_INVALID_ARG: Invalid argument
ESP_ERR_INVALID_STATE: Invalid state, scheme didn't registered
-
Type Definitions
-
typedef struct adc_cali_scheme_t *adc_cali_handle_t
ADC calibration handle.
Enumerations
Header File
This header file can be included with:
#include "esp_adc/adc_cali_scheme.h"
This header file is a part of the API provided by the
esp_adccomponent. To declare that your component depends on
esp_adc, add the following to your CMakeLists.txt:
REQUIRES esp_adc
or
PRIV_REQUIRES esp_adc |
Clock Tree
The clock subsystem of ESP32 is used to source and distribute system/module clocks from a range of root clocks. The clock tree driver maintains the basic functionality of the system clock and the intricate relationship among module clocks.
This document starts with the introduction to root and module clocks. Then it covers the clock tree APIs that can be called to monitor the status of the module clocks at runtime.
Introduction
This section lists definitions of ESP32's supported root clocks and module clocks. These definitions are commonly used in the driver configuration, to help select a proper source clock for the peripheral.
Root Clocks
Root clocks generate reliable clock signals. These clock signals then pass through various gates, muxes, dividers, or multipliers to become the clock sources for every functional module: the CPU core(s), Wi-Fi, Bluetooth, the RTC, and the peripherals.
ESP32's root clocks are listed in
soc_root_clk_t:
-
Internal 8 MHz RC Oscillator (RC_FAST)
This RC oscillator generates a about 8.5 MHz clock signal output as the
RC_FAST_CLK.
The about 8.5 MHz signal output is also passed into a configurable divider, which by default divides the input clock frequency by 256, to generate a
RC_FAST_D256_CLK.
The exact frequency of
RC_FAST_CLKcan be computed in runtime through calibration on the
RC_FAST_D256_CLK.
-
External 2 ~ 40 MHz Crystal (XTAL)
-
Internal 150 kHz RC Oscillator (RC_SLOW)
This RC oscillator generates a about 150kHz clock signal output as the
RC_SLOW_CLK. The exact frequency of this clock can be computed in runtime through calibration.
-
External 32 kHz Crystal - optional (XTAL32K)
The clock source for this
XTAL32K_CLKcan be either a 32 kHz crystal connecting to the
32K_XPand
32K_XNpins or a 32 kHz clock signal generated by an external circuit. The external signal must be connected to the
32K_XNpin. Additionally, a 1 nF capacitor must be placed between the
32K_XPpin and ground. In this case, the
32K_XPpin cannot be used as a GPIO pin.
XTAL32K_CLKcan also be calibrated to get its exact frequency.
Typically, the frequency of the signal generated from an RC oscillator circuit is less accurate and more sensitive to the environment compared to the signal generated from a crystal. ESP32 provides several clock source options for the
RTC_SLOW_CLK, and it is possible to make the choice based on the requirements for system time accuracy and power consumption. For more details, please refer to RTC Timer Clock Sources.
Module Clocks
ESP32's available module clocks are listed in
soc_module_clk_t. |
[out] Frequency of the clock source, in Hz
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
ESP_FAIL Calibration failed
-
Enumerations
-
enum esp_clk_tree_src_freq_precision_t
Degree of precision of frequency value to be returned by esp_clk_tree_src_get_freq_hz()
Values:
-
enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED
-
enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_APPROX
-
enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_EXACT
-
enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_INVALID
- enumerator ESP_CLK_TREE_SRC_FREQ_PRECISION_CACHED |
Digital To Analog Converter (DAC)
Overview
ESP32 has two 8-bit DAC (digital to analog converter) channels respectively connected to GPIO25 (Channel 1) and GPIO26 (Channel 2). Each DAC channel can convert the digital value 0~255 to the analog voltage 0~Vref (The reference voltage 'Vref' here is input from the pin VDD3P3_RTC, which ideally equals to the power supply VDD). The output voltage can be calculated as the following:
out_voltage = Vref * digi_val / 255
The DAC peripheral supports outputting analog signal in the following ways:
Outputting a voltage directly. The DAC channel keeps outputting a specified voltage.
Outputting continuous analog signal by DMA. The DAC converts the data in a buffer at a specified frequency.
Outputting a cosine wave by the cosine wave generator. The DAC channel can output a cosine wave with specified frequency and amplitude.
For other analog output options, see Sigma-Delta Modulation and LED Control. Both modules produce high-frequency PWM/PDM output, which can be hardware low-pass filtered in order to generate a lower frequency analog output.
DAC File Structure
Public headers that need to be included in the DAC application are listed as follows:
dac.h: The top header file of the legacy DAC driver, which should be only included in the apps which use the legacy driver API.
|
The top header file of the new DAC driver, which should be included in the apps which use the new driver API with cosine mode.
dac_continuous.h: The top header file of the new DAC driver, which should be included in the apps which use the new driver API with continuous mode.
Note
The legacy driver cannot coexist with the new driver. Include
dac.h to use the legacy driver or
dac_oneshot.h,
dac_cosine.h, and
dac_continuous.h to use the new driver. The legacy driver might be removed in the future.
Functional Overview
Resources Management
The DAC on ESP32 has two channels. The channels have separate software resources and can be managed by
dac_oneshot_handle_t,
dac_cosine_handle_t, or
dac_continuous_handle_t according to the usage. Registering different modes on a same DAC channel is not allowed.
|
Direct Voltage Output (One-shot/Direct Mode)
The DAC channels in the group can convert an 8-bit digital value into the analog when
dac_oneshot_output_voltage() is called (it can be called in ISR). The analog voltage is kept on the DAC channel until the next conversion starts. To start the voltage conversion, the DAC channels need to be enabled first through registering by
dac_oneshot_new_channel().
Continuous Wave Output (Continuous/DMA Mode)
DAC channels can convert digital data continuously via the DMA. There are three ways to write the DAC data:
-
Normal writing (synchronous): Data can be transmitted at one time and kept blocked until all the data has been loaded into the DMA buffer, and the voltage is kept as the last conversion value while no more data is inputted. It is usually used to transport a long signal like an audio. To convert data continuously, the continuous channel handle need to be allocated by calling
dac_continuous_new_channels()and the DMA conversion should be enabled by calling
dac_continuous_enable(). Then data can be written by
dac_continuous_write()synchronously. Refer to peripherals/dac/dac_continuous/dac_audio for examples.
-
Cyclical writing: A piece of data can be converted cyclically without blocking, and no more operation is needed after the data are loaded into the DMA buffer. But note that the inputted buffer size is limited by the number of descriptors and the DMA buffer size. It is usually used to transport short signals that need to be repeated, e.g., a sine wave. To achieve cyclical writing, call
dac_continuous_write_cyclically()after the DAC continuous mode is enabled. |
-
Asynchronous writing: Data can be transmitted asynchronously based on the event callback.
dac_event_callbacks_t::on_convert_donemust be registered to use asynchronous mode. Users can get the
dac_event_data_tin the callback which contains the DMA buffer address and length, allowing them to load the data into the buffer directly. To use the asynchronous writing, call
dac_continuous_register_event_callback()to register the
dac_event_callbacks_t::on_convert_donebefore enabling, and then
dac_continuous_start_async_writing()to start the asynchronous writing. Note that once the asynchronous writing is started, the callback function will be triggered continuously. Call
dac_continuous_write_asynchronously()to load the data either in a separate task or in the callback directly. |
On ESP32, the DAC digital controller can be connected internally to the I2S0 and use its DMA for continuous conversion. Although the DAC only needs 8-bit data for conversion, it has to be the left-shifted 8 bits (i.e., the high 8 bits in a 16-bit slot) to satisfy the I2S communication format. By default, the driver helps to expand the data to 16-bit wide automatically. To expand manually, please disable CONFIG_DAC_DMA_AUTO_16BIT_ALIGN in the menuconfig.
The clock of the DAC digital controller comes from I2S0 as well, so there are two clock sources for selection:
dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_PLL_D2supports frequency between 19.6 KHz to several MHz. It is the default clock which can also be selected by
dac_continuous_digi_clk_src_t::DAC_DIGI_CLK_SRC_DEFAULT.
|
The DAC channel has been registered already
ESP_ERR_NO_MEM No memory for the DAC oneshot channel resources
ESP_OK Allocate the new DAC oneshot channel success
-
-
esp_err_t dac_oneshot_del_channel(dac_oneshot_handle_t handle)
Delete the DAC oneshot channel.
Note
The channel will be disabled as well when the channel deleted
- Parameters
handle -- [in] The DAC oneshot channel handle
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channel has already been de-registered
ESP_OK Delete the oneshot channel success
-
-
esp_err_t dac_oneshot_output_voltage(dac_oneshot_handle_t handle, uint8_t digi_value)
|
[in] The DAC oneshot channel handle
digi_value -- [in] The digital value that need to be converted
-
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_OK Convert the digital value success
-
Structures
-
struct dac_oneshot_config_t
DAC oneshot channel configuration.
Public Members
-
dac_channel_t chan_id
DAC channel id
- dac_channel_t chan_id
Type Definitions
-
typedef struct dac_oneshot_s *dac_oneshot_handle_t
DAC oneshot channel handle
Header File
This header file can be included with:
#include "driver/dac_cosine.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t dac_cosine_new_channel(const dac_cosine_config_t *cos_cfg, dac_cosine_handle_t *ret_handle)
Allocate a new DAC cosine wave channel.
Note
Since there is only one cosine wave generator, only the first channel can set the frequency of the cosine wave. Normally, the latter one is not allowed to set a different frequency, but the it can be forced to set by setting the bit
force_set_freqin the configuration, notice that another channel will be affected as well when the frequency is updated.
- Parameters
cos_cfg -- |
The DAC channel has been registered already
ESP_ERR_NO_MEM No memory for the DAC cosine wave channel resources
ESP_OK Allocate the new DAC cosine wave channel success
-
-
esp_err_t dac_cosine_del_channel(dac_cosine_handle_t handle)
Delete the DAC cosine wave channel.
- Parameters
handle -- [in] The DAC cosine wave channel handle
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channel has already been deregistered
ESP_OK Delete the cosine wave channel success
-
-
esp_err_t dac_cosine_start(dac_cosine_handle_t handle)
Start outputting the cosine wave on the channel.
- |
[in] The DAC cosine wave channel handle
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channel has been started already
ESP_OK Start the cosine wave success
-
-
esp_err_t dac_cosine_stop(dac_cosine_handle_t handle)
Stop outputting the cosine wave on the channel.
- Parameters
handle -- [in] The DAC cosine wave channel handle
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channel has been stopped already
ESP_OK Stop the cosine wave success
-
Structures
-
struct dac_cosine_config_t
DAC cosine channel configurations.
Public Members
-
dac_channel_t chan_id
The cosine wave channel id
-
uint32_t freq_hz
The frequency of cosine wave, unit: Hz. The cosine wave generator is driven by RTC_FAST clock which is divide from RC_FAST, With the default RTC clock, the minimum frequency of cosine wave is about 130 Hz, Although it can support up to several MHz frequency theoretically, the waveform will distort at high frequency due to the hardware limitation. Typically not suggest to set the frequency higher than 200 KHz
-
dac_cosine_clk_src_t clk_src
The clock source of the cosine wave generator, currently only support
DAC_COSINE_CLK_SRC_DEFAULT
-
dac_cosine_atten_t atten
The attenuation of cosine wave amplitude
-
dac_cosine_phase_t phase
The phase of cosine wave, can only support DAC_COSINE_PHASE_0 or DAC_COSINE_PHASE_180, default as 0 while setting an unsupported phase
-
int8_t offset
The DC offset of cosine wave
-
bool force_set_freq
Force to set the cosine wave frequency
-
struct dac_cosine_config_t::[anonymous] flags
Flags of cosine mode
- dac_channel_t chan_id
Type Definitions
-
typedef struct dac_cosine_s *dac_cosine_handle_t
DAC cosine wave channel handle
Header File
This header file can be included with:
#include "driver/dac_continuous.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t |
No memory for the DAC continuous mode resources
ESP_OK Allocate the new DAC continuous mode success
-
-
esp_err_t dac_continuous_del_channels(dac_continuous_handle_t handle)
Delete the DAC continuous handle.
- Parameters
handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channels have already been deregistered or not disabled
ESP_OK Delete the continuous channels success
-
-
esp_err_t dac_continuous_enable(dac_continuous_handle_t handle)
Enabled the DAC continuous mode.
Note
Must enable the channels before
- Parameters
handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channels have been enabled already
ESP_OK Enable the continuous output success
-
-
esp_err_t dac_continuous_disable(dac_continuous_handle_t handle)
Disable the DAC continuous mode.
- Parameters
handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The channels have been enabled already
ESP_OK Disable the continuous output success
-
-
esp_err_t dac_continuous_write(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t * |
Write DAC data continuously.
Note
The data in buffer will only be converted one time, This function will be blocked until all data loaded or timeout then the DAC output will keep outputting the voltage of the last data in the buffer
Note
Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing
CONFIG_DAC_DMA_AUTO_16BIT_ALIGNin menuconfig.
- Parameters
handle -- |
[in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
buf -- [in] The digital data buffer to convert
buf_size -- [in] The buffer size of digital data buffer
bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it
timeout_ms -- [in] The timeout time in millisecond, set a minus value means will block forever
-
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet
ESP_ERR_TIMEOUT Waiting for semaphore or message queue timeout
ESP_OK Success to output the acyclic DAC data
-
-
esp_err_t dac_continuous_write_cyclically(dac_continuous_handle_t handle, uint8_t *buf, size_t buf_size, size_t *bytes_loaded)
Write DAC continuous data cyclically.
Note
The data in buffer will be converted cyclically using DMA once this function is called, This function will return once the data loaded into DMA buffers.
Note
The buffer size of cyclically output is limited by the descriptor number and dma buffer size while initializing the continuous mode. Concretely, in order to load all the data into descriptors, the cyclic buffer size is not supposed to be greater than
desc_num * buf_size
Note
Specially, on ESP32, the data bit width of DAC continuous data is fixed to 16 bits while only the high 8 bits are available, The driver will help to expand the inputted buffer automatically by default, you can also align the data to 16 bits manually by clearing
CONFIG_DAC_DMA_AUTO_16BIT_ALIGNin menuconfig.
- Parameters
handle -- |
[in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
buf -- [in] The digital data buffer to convert
buf_size -- [in] The buffer size of digital data buffer
bytes_loaded -- [out] The bytes that has been loaded into DMA buffer, can be NULL if don't need it
-
- Returns
ESP_ERR_INVALID_ARG The input parameter is invalid
ESP_ERR_INVALID_STATE The DAC continuous mode has not been enabled yet
ESP_OK Success to output the acyclic DAC data
-
-
esp_err_t dac_continuous_register_event_callback(dac_continuous_handle_t handle, const dac_event_callbacks_t *callbacks, void *user_data)
Set event callbacks for DAC continuous mode.
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
callbacksstructure to NULL.
Note
When CONFIG_DAC_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in this function, including the
user_data, should be in the internal RAM as well.
- Parameters
handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
callbacks -- [in] Group of callback functions, input NULL to clear the former callbacks
user_data -- [in] User data, which will be passed to callback functions directly
-
- Returns
ESP_OK Set event callbacks successfully
ESP_ERR_INVALID_ARG Set event callbacks failed because of invalid argument
-
-
esp_err_t dac_continuous_start_async_writing(dac_continuous_handle_t handle)
Start the async writing.
Note
When the asynchronous writing start, the DAC will keep outputting '0' until the data are loaded into the DMA buffer. To loaded the data into DMA buffer, 'on_convert_done' callback is required, which can be registered by 'dac_continuous_register_event_callback' before enabling
- Parameters
handle -- [in] The DAC continuous channel handle that obtained from 'dac_continuous_new_channels'
- Returns
ESP_OK Start asynchronous writing successfully
ESP_ERR_INVALID_ARG |
Note
Assume the data in buffer is 'A B C D E F' DAC_CHANNEL_MODE_SIMUL:
channel 0: A B C D E F
channel 1: A B C D E F DAC_CHANNEL_MODE_ALTER:
channel 0: A C E
channel 1: B D F
Values:
-
enumerator DAC_CHANNEL_MODE_SIMUL
The data in the DMA buffer is simultaneously output to the enable channel of the DAC.
-
enumerator DAC_CHANNEL_MODE_ALTER
The data in the DMA buffer is alternately output to the enable channel of the DAC.
-
Header File
This header file can be included with:
#include "hal/dac_types.h"
Enumerations
-
enum dac_channel_t
Values:
-
enumerator DAC_CHAN_0
DAC channel 0 is GPIO25(ESP32) / GPIO17(ESP32S2)
-
enumerator DAC_CHAN_1
DAC channel 1 is GPIO26(ESP32) / GPIO18(ESP32S2)
-
enumerator DAC_CHANNEL_1
Alias of 'DAC_CHAN_0', now the channel index start from '0'
-
enumerator DAC_CHANNEL_2
Alias of 'DAC_CHAN_1', now the channel index start from '0'
- enumerator DAC_CHAN_0
-
enum dac_cosine_atten_t
The attenuation of the amplitude of the cosine wave generator. |
GPIO & RTC GPIO
GPIO Summary
The ESP32 chip features 34 physical GPIO pins (GPIO0 ~ GPIO19, GPIO21 ~ GPIO23, GPIO25 ~ GPIO27, and GPIO32 ~ GPIO39). Each pin can be used as a general-purpose I/O, or be connected to an internal peripheral signal. Through IO MUX, RTC IO MUX and the GPIO matrix, peripheral input signals can be from any IO pins, and peripheral output signals can be routed to any IO pins. Together these modules provide highly configurable I/O. For more details, see ESP32 Technical Reference Manual > IO MUX and GPIO Matrix (GPIO, IO_MUX) |
|
GPIO
|
Analog Function
|
RTC GPIO
|
Comments
|
GPIO0
|
ADC2_CH1
|
RTC_GPIO11
|
Strapping pin
|
GPIO1
|
TXD
|
GPIO2
|
ADC2_CH2
|
RTC_GPIO12
|
Strapping pin
|
GPIO3
|
RXD
|
GPIO4
|
ADC2_CH0
|
RTC_GPIO10
|
GPIO5
|
Strapping pin
|
GPIO6
|
SPI0/1
|
GPIO7
|
SPI0/1
|
GPIO8
|
SPI0/1
|
GPIO9
|
SPI0/1
|
GPIO10
|
SPI0/1
|
GPIO11
|
SPI0/1
|
GPIO12
|
ADC2_CH5
|
RTC_GPIO15
|
Strapping pin; JTAG
|
GPIO13
|
ADC2_CH4
|
RTC_GPIO14
|
JTAG
|
GPIO14
|
ADC2_CH6
|
RTC_GPIO16
|
JTAG
|
GPIO15
|
ADC2_CH3
|
RTC_GPIO13
|
Strapping pin; JTAG
|
GPIO16
|
SPI0/1
|
GPIO17
|
SPI0/1
|
GPIO18
|
GPIO19
|
GPIO21
|
GPIO22
|
GPIO23
|
GPIO25
|
ADC2_CH8
|
RTC_GPIO6
|
GPIO26
|
ADC2_CH9
|
RTC_GPIO7
|
GPIO27
|
ADC2_CH7
|
RTC_GPIO17
|
GPIO32
|
ADC1_CH4
|
RTC_GPIO9
|
GPIO33
|
ADC1_CH5
|
RTC_GPIO8
|
GPIO34
|
ADC1_CH6
|
RTC_GPIO4
|
GPI
|
GPIO35
|
ADC1_CH7
|
RTC_GPIO5
|
GPI
|
GPIO36
|
ADC1_CH0
|
RTC_GPIO0
|
GPI
|
GPIO37
|
ADC1_CH1
|
RTC_GPIO1
|
GPI
|
GPIO38
|
ADC1_CH2
|
RTC_GPIO2
|
GPI
|
GPIO39
|
ADC1_CH3
|
RTC_GPIO3
|
GPI
Note
Strapping pin: GPIO0, GPIO2, GPIO5, GPIO12 |
For more infomation, please refer to ESP32 datasheet.
SPI0/1: GPIO6-11 and GPIO16-17 are usually connected to the SPI flash and PSRAM integrated on the module and therefore should not be used for other purposes.
JTAG: GPIO12-15 are usually used for inline debug.
GPI: GPIO34-39 can only be set as input mode and do not have software-enabled pullup or pulldown functions.
TXD & RXD are usually used for flashing and debugging.
ADC2: ADC2 pins cannot be used when Wi-Fi is used. So, if you are having trouble getting the value from an ADC2 GPIO while using Wi-Fi, you may consider using an ADC1 GPIO instead, which should solve your problem. For more details, please refer to Hardware Limitations of ADC Continuous Mode and Hardware Limitations of ADC Oneshot Mode.
Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to ESP32 ECO and Workarounds for Bugs > Section 3.11 for the detailed description of the issue.
GPIO driver offers a dump function
gpio_dump_io_configuration() to show the configurations of the IOs at the moment, such as pull-up / pull-down, input / output enable, pin mapping etc. |
Below is an example dump:
================IO DUMP Start================
IO[4] -
Pullup: 1, Pulldown: 0, DriveCap: 2
InputEn: 1, OutputEn: 0, OpenDrain: 0
FuncSel: 1 (GPIO)
GPIO Matrix SigIn ID: (simple GPIO input)
SleepSelEn: 1
IO[18] -
Pullup: 0, Pulldown: 0, DriveCap: 2
InputEn: 0, OutputEn: 1, OpenDrain: 0
FuncSel: 1 (GPIO)
GPIO Matrix SigOut ID: 256 (simple GPIO output)
SleepSelEn: 1
IO[26] **RESERVED** -
Pullup: 1, Pulldown: 0, DriveCap: 2
InputEn: 1, OutputEn: 0, OpenDrain: 0
FuncSel: 0 (IOMUX)
SleepSelEn: 1
=================IO DUMP |
It is strongly not recommended to reconfigure them for other application purposes.
There is also separate "RTC GPIO" support, which functions when GPIOs are routed to the "RTC" low-power and analog subsystem. These pin functions can be used when:
In Deep-sleep mode
The Ultra Low Power co-processor is running
Analog functions such as ADC/DAC/etc are in use
Application Example
GPIO output and input interrupt example: peripherals/gpio/generic_gpio.
API Reference - Normal GPIO
Header File
This header file can be included with:
#include "driver/gpio.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t gpio_config(const gpio_config_t *pGPIOConfig)
GPIO common configuration.
Configure GPIO's Mode,pull-up,PullDown,IntrType
- Parameters
pGPIOConfig -- Pointer to GPIO configure struct
- Returns
ESP_OK success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_reset_pin(gpio_num_t gpio_num)
Reset an gpio to default state (select gpio function, enable pullup and disable input and output).
Note
This function also configures the IOMUX for this pin to the GPIO function, and disconnects any other peripheral output configured via GPIO Matrix.
- Parameters
gpio_num -- GPIO number.
- Returns
Always return ESP_OK.
-
esp_err_t gpio_set_intr_type(gpio_num_t gpio_num, gpio_int_type_t intr_type)
GPIO set interrupt trigger type.
- Parameters
gpio_num -- GPIO number. If you want to set the trigger type of e.g. of GPIO16, gpio_num should be GPIO_NUM_16 (16);
intr_type -- Interrupt type, select from gpio_int_type_t
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_intr_enable(gpio_num_t gpio_num)
Enable GPIO module interrupt signal.
Note
ESP32: Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled. Please refer to the comments of
adc1_get_raw. Please refer to Section 3.11 of ESP32 ECO and Workarounds for Bugs for the description of this issue.
- Parameters
gpio_num -- GPIO number. |
If you want to enable an interrupt on e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_intr_disable(gpio_num_t gpio_num)
Disable GPIO module interrupt signal.
Note
This function is allowed to be executed when Cache is disabled within ISR context, by enabling
CONFIG_GPIO_CTRL_FUNC_IN_IRAM
- Parameters
gpio_num -- GPIO number. If you want to disable the interrupt of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
- Returns
ESP_OK success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_set_level(gpio_num_t gpio_num, uint32_t level)
GPIO set output level.
Note
This function is allowed to be executed when Cache is disabled within ISR context, by enabling
CONFIG_GPIO_CTRL_FUNC_IN_IRAM
- Parameters
gpio_num -- GPIO number. If you want to set the output level of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
level -- Output level. |
0: low ; 1: high
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG GPIO number error
-
-
int gpio_get_level(gpio_num_t gpio_num)
GPIO get input level.
Warning
If the pad is not configured for input (or input and output) the returned value is always 0.
- Parameters
gpio_num -- GPIO number. If you want to get the logic level of e.g. pin GPIO16, gpio_num should be GPIO_NUM_16 (16);
- Returns
0 the GPIO input level is 0
1 the GPIO input level is 1
-
-
esp_err_t gpio_set_direction(gpio_num_t gpio_num, gpio_mode_t mode)
|
GPIO set direction.
Configure GPIO direction,such as output_only,input_only,output_and_input
- Parameters
gpio_num -- Configure GPIO pins number, it should be GPIO number. If you want to set direction of e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
mode -- GPIO direction
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG GPIO error
-
-
esp_err_t gpio_set_pull_mode(gpio_num_t gpio_num, gpio_pull_mode_t pull)
Configure GPIO pull-up/pull-down resistors.
Note
ESP32: Only pins that support both input & output have integrated pull-up and pull-down resistors. Input-only GPIOs 34-39 do not.
- Parameters
gpio_num -- GPIO number. If you want to set pull up or down mode for e.g. GPIO16, gpio_num should be GPIO_NUM_16 (16);
pull -- GPIO pull up/down mode.
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG : Parameter error
-
-
esp_err_t gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type)
Enable GPIO wake-up function.
- Parameters
gpio_num -- GPIO number.
intr_type -- GPIO wake-up type. Only GPIO_INTR_LOW_LEVEL or GPIO_INTR_HIGH_LEVEL can be used.
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_wakeup_disable(gpio_num_t gpio_num)
Disable GPIO wake-up function.
- Parameters
gpio_num -- GPIO number
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_isr_register(void |
See esp_intr_alloc.h for more info.
handle -- Pointer to return handle. If non-NULL, a handle for the interrupt will be returned here.
-
- Returns
ESP_OK Success ;
ESP_ERR_INVALID_ARG GPIO error
ESP_ERR_NOT_FOUND No free interrupt found with the specified flags
-
-
esp_err_t gpio_pullup_en(gpio_num_t gpio_num)
Enable pull-up on GPIO.
- Parameters
gpio_num -- GPIO number
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_pullup_dis(gpio_num_t gpio_num)
Disable pull-up on GPIO.
- Parameters
gpio_num -- GPIO number
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_pulldown_en(gpio_num_t gpio_num)
Enable pull-down on GPIO.
- Parameters
gpio_num -- GPIO number
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_pulldown_dis(gpio_num_t gpio_num)
Disable pull-down on GPIO.
- Parameters
gpio_num -- GPIO number
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_install_isr_service(int intr_alloc_flags)
Install the GPIO driver's ETS_GPIO_INTR_SOURCE ISR handler service, which allows per-pin GPIO interrupt handlers.
This function is incompatible with gpio_isr_register() - if that function is used, a single global ISR is registered for all GPIO interrupts. If this function is used, the ISR service provides a global GPIO ISR and individual pin handlers are registered via the gpio_isr_handler_add() function.
- Parameters
intr_alloc_flags -- Flags used to allocate the interrupt. One or multiple (ORred) ESP_INTR_FLAG_* values. See esp_intr_alloc.h for more info.
- Returns
ESP_OK Success
ESP_ERR_NO_MEM No memory to install this service
ESP_ERR_INVALID_STATE ISR service already installed.
ESP_ERR_NOT_FOUND No free interrupt found with the specified flags
ESP_ERR_INVALID_ARG GPIO error
-
-
void gpio_uninstall_isr_service(void)
Uninstall the driver's GPIO ISR service, freeing related resources.
-
esp_err_t gpio_isr_handler_add(gpio_num_t gpio_num, gpio_isr_t isr_handler, void *args)
Add ISR handler for the corresponding GPIO pin.
Call this function after using gpio_install_isr_service() to install the driver's GPIO ISR handler service.
The pin ISR handlers no longer need to be declared with IRAM_ATTR, unless you pass the ESP_INTR_FLAG_IRAM flag when allocating the ISR in gpio_install_isr_service().
This ISR handler will be called from an ISR. So there is a stack size limit (configurable as "ISR stack size" in menuconfig). This limit is smaller compared to a global GPIO interrupt handler due to the additional level of indirection.
- Parameters
gpio_num -- GPIO number
isr_handler -- ISR handler function for the corresponding GPIO number.
args -- parameter for ISR handler.
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_STATE Wrong state, the ISR service has not been initialized.
ESP_ERR_INVALID_ARG Parameter error
-
-
esp_err_t gpio_isr_handler_remove(gpio_num_t |
: The gpio is not rtcio.
-
esp_err_t rtc_gpio_init(gpio_num_t gpio_num)
Init a GPIO as RTC GPIO.
This function must be called when initializing a pad for an analog function.
- Parameters
gpio_num -- GPIO number (e.g. GPIO_NUM_12)
- Returns
ESP_OK success
ESP_ERR_INVALID_ARG GPIO is not an RTC IO
-
-
esp_err_t rtc_gpio_deinit(gpio_num_t gpio_num)
Init a GPIO as digital GPIO.
- Parameters
gpio_num -- GPIO number (e.g. GPIO_NUM_12)
- Returns
ESP_OK success
ESP_ERR_INVALID_ARG GPIO is not an RTC IO
-
-
uint32_t rtc_gpio_get_level(gpio_num_t gpio_num)
Get the RTC IO input level.
- Parameters
gpio_num -- GPIO number (e.g. GPIO_NUM_12)
- Returns
1 High level
0 Low level
ESP_ERR_INVALID_ARG GPIO is not an RTC IO
-
-
esp_err_t rtc_gpio_set_level(gpio_num_t gpio_num, uint32_t level)
Set the RTC IO output level.
- Parameters
gpio_num -- GPIO number (e.g. GPIO_NUM_12)
level -- output level
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG GPIO is not an RTC IO
-
-
esp_err_t rtc_gpio_set_direction(gpio_num_t gpio_num, rtc_gpio_mode_t mode)
RTC GPIO set direction.
Configure RTC GPIO direction, such as output only, input only, output and input.
- Parameters
gpio_num -- GPIO number (e.g. GPIO_NUM_12)
mode -- GPIO direction
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG GPIO is not an RTC IO
-
-
esp_err_t rtc_gpio_set_direction_in_sleep(gpio_num_t gpio_num, rtc_gpio_mode_t mode)
RTC GPIO set direction in deep sleep mode or disable sleep status (default). In some application scenarios, IO needs to have another states during deep sleep.
|
Each RTC pad has a "force hold" input signal from the RTC controller. If this signal is set, pad latches current values of input enable, function, output enable, and other signals which come from the RTC mux. Force hold signal is enabled before going into deep sleep for pins which are used for EXT1 wakeup.
-
esp_err_t rtc_gpio_wakeup_enable(gpio_num_t gpio_num, gpio_int_type_t intr_type)
Enable wakeup from sleep mode using specific GPIO.
- Parameters
gpio_num -- GPIO number
intr_type -- Wakeup on high level (GPIO_INTR_HIGH_LEVEL) or low level (GPIO_INTR_LOW_LEVEL)
-
- Returns
ESP_OK on success
ESP_ERR_INVALID_ARG if gpio_num is not an RTC IO, or intr_type is not one of GPIO_INTR_HIGH_LEVEL, GPIO_INTR_LOW_LEVEL.
-
Macros
-
RTC_GPIO_IS_VALID_GPIO(gpio_num)
Header File
This header file can be included with:
#include "driver/lp_io.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Header File
This header file can be included with:
#include "hal/rtc_io_types.h"
Enumerations
-
enum rtc_gpio_mode_t
RTCIO output/input mode type.
|
The hardware timer features high resolution and flexible alarm action. The behavior when the internal counter of a timer reaches a specific target value is called a timer alarm. When a timer alarms, a user registered per-timer callback would be called.
Typically, a general purpose timer can be used in scenarios like:
Free running as a wall clock, fetching a high-resolution timestamp at any time and any places
Generate period alarms, trigger events periodically
Generate one-shot alarm, respond in target time
Functional Overview
The following sections of this document cover the typical steps to install and operate a timer:
Resource Allocation - covers which parameters should be set up to get a timer handle and how to recycle the resources when GPTimer finishes working.
Set and Get Count Value - covers how to force the timer counting from a start point and how to get the count value at anytime.
Set up Alarm Action - covers the parameters that should be set up to enable the alarm event.
Register Event Callbacks - covers how to hook user specific code to the alarm event callback function.
Enable and Disable Timer - covers how to enable and disable the timer.
Start and Stop Timer - shows some typical use cases that start the timer with different alarm behavior.
Power Management - describes how different source clock selections can affect power consumption.
IRAM Safe - describes tips on how to make the timer interrupt and IO control functions work better along with a disabled cache.
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
Different ESP chips might have different numbers of independent timer groups, and within each group, there could also be several independent timers. |
The driver behind manages all available hardware resources in a pool, so that you do not need to care about which timer and which group it belongs to.
To install a timer instance, there is a configuration structure that needs to be given in advance:
gptimer_config_t:
gptimer_config_t::clk_srcselects the source clock for the timer. The available clocks are listed in
gptimer_clock_source_t, you can only pick one of them. For the effect on power consumption of different clock source, please refer to Section Power Management.
gptimer_config_t::directionsets the counting direction of the timer, supported directions are listed in
gptimer_count_direction_t, you can only pick one of them.
gptimer_config_t::resolution_hzsets the resolution of the internal counter. |
gptimer_config::intr_prioritysets the priority of the timer interrupt. If it is set to
0, the driver will allocate an interrupt with a default priority. Otherwise, the driver will use the given priority.
Optional
gptimer_config_t::intr_sharedsets whether or not mark the timer interrupt source as a shared one. For the pros/cons of a shared interrupt, you can refer to Interrupt Handling.
With all the above configurations set in the structure, the structure can be passed to
gptimer_new_timer() which will instantiate the timer instance and return a handle of the timer.
The function can fail due to various errors such as insufficient memory, invalid arguments, etc. Specifically, when there are no more free timers (i.e., all hardware resources have been used up), then
ESP_ERR_NOT_FOUND will be returned. The total number of available timers is represented by the
SOC_TIMER_GROUP_TOTAL_TIMERS and its value depends on the ESP chip.
If a previously created GPTimer instance is no longer required, you should recycle the timer by calling
gptimer_del_timer(). This allows the underlying HW timer to be used for other purposes. Before deleting a GPTimer handle, please disable it by
gptimer_disable() in advance or make sure it has not enabled yet by
gptimer_enable().
Creating a GPTimer Handle with Resolution of 1 MHz
gptimer_handle_t gptimer = NULL;
gptimer_config_t timer_config = {
.clk_src = GPTIMER_CLK_SRC_DEFAULT,
.direction = GPTIMER_COUNT_UP,
.resolution_hz = 1 * 1000 * 1000, // 1MHz, 1 tick = 1us
};
ESP_ERROR_CHECK(gptimer_new_timer(&timer_config, &gptimer));
Set and Get Count Value
When the GPTimer is created, the internal counter will be reset to zero by default. The counter value can be updated asynchronously by
gptimer_set_raw_count(). The maximum count value is dependent on the bit width of the hardware timer, which is also reflected by the SOC macro
SOC_TIMER_GROUP_COUNTER_BIT_WIDTH. When updating the raw count of an active timer, the timer will immediately start counting from the new value.
Count value can be retrieved by
gptimer_get_raw_count(), at any time.
|
Start Timer as a Wall Clock
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
// Retrieve the timestamp at any time
uint64_t count;
ESP_ERROR_CHECK(gptimer_get_raw_count(gptimer, &count));
Trigger Period Events
typedef struct {
uint64_t event_count;
} example_queue_element_t;
static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_ctx;
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// |
Optional: send the event data to other task by OS queue
// Do not introduce complex logics in callbacks
// Suggest dealing with event data in the main loop, instead of in this callback
xQueueSendFromISR(queue, &ele, &high_task_awoken);
// return whether we need to yield at the end of ISR
return high_task_awoken == pdTRUE;
}
gptimer_alarm_config_t alarm_config = {
.reload_count = 0, // counter will reload with 0 on alarm event
.alarm_count = 1000000, // period = 1s @resolution 1MHz
.flags.auto_reload_on_alarm = true, // enable auto-reload
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
Trigger One-Shot Event
typedef struct {
uint64_t event_count;
} example_queue_element_t;
static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_ctx;
// Stop timer the sooner the better
gptimer_stop(timer);
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// Optional: send the event data to other task by OS queue
xQueueSendFromISR(queue, &ele, &high_task_awoken);
// return whether we need to yield at the end of ISR
return high_task_awoken == pdTRUE;
}
gptimer_alarm_config_t alarm_config |
= 1 * 1000 * 1000, // alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer));
Dynamic Alarm Update
Alarm value can be updated dynamically inside the ISR handler callback, by changing
gptimer_alarm_event_data_t::alarm_value. |
typedef struct {
uint64_t event_count;
} example_queue_element_t;
static bool example_timer_on_alarm_cb(gptimer_handle_t timer, const gptimer_alarm_event_data_t *edata, void *user_ctx)
{
BaseType_t high_task_awoken = pdFALSE;
QueueHandle_t queue = (QueueHandle_t)user_data;
// Retrieve the count value from event data
example_queue_element_t ele = {
.event_count = edata->count_value
};
// Optional: send the event data to other task by OS queue
xQueueSendFromISR(queue, &ele, &high_task_awoken);
// reconfigure alarm value
gptimer_alarm_config_t alarm_config = {
.alarm_count = edata->alarm_value + 1000000, // alarm in next 1s
};
gptimer_set_alarm_action(timer, &alarm_config);
// return whether we need to yield at the end of ISR
return high_task_awoken == pdTRUE;
}
gptimer_alarm_config_t alarm_config = {
.alarm_count = 1000000, // initial alarm target = 1s @resolution 1MHz
};
ESP_ERROR_CHECK(gptimer_set_alarm_action(gptimer, &alarm_config));
gptimer_event_callbacks_t cbs = {
.on_alarm = example_timer_on_alarm_cb, // register user callback
};
ESP_ERROR_CHECK(gptimer_register_event_callbacks(gptimer, &cbs, queue));
ESP_ERROR_CHECK(gptimer_enable(gptimer));
ESP_ERROR_CHECK(gptimer_start(gptimer, &alarm_config));
Power Management
There are some power management strategies, which might turn off or change the frequency of GPTimer's source clock to save power consumption. |
For example, during DFS, APB clock will be scaled down. If light-sleep is also enabled, PLL and XTAL clocks will be powered off. Both of them can result in an inaccurate time keeping.
The driver can prevent the above situation from happening by creating different power management lock according to different clock source. The driver increases the reference count of that power management lock in the
gptimer_enable() and decrease it in the
gptimer_disable(). So we can ensure the clock source is stable between
gptimer_enable() and
gptimer_disable().
|
IRAM Safe
By default, the GPTimer interrupt will be deferred when the cache is disabled because of writing or erasing the flash. Thus the alarm interrupt will not get executed in time, which is not expected in a real-time application.
There is a Kconfig option CONFIG_GPTIMER_ISR_IRAM_SAFE that:
Enables the interrupt being serviced even when the cache is disabled
Places all functions that used by the ISR into IRAM 2
Places driver object into DRAM (in case it is mapped to PSRAM by accident)
This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption.
There is another Kconfig option CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM that can put commonly used IO control functions into IRAM as well. So, these functions can also be executable when the cache is disabled. These IO control functions are as follows:
Thread Safety
All the APIs provided by the driver are guaranteed to be thread safe, which means you can call them from different RTOS tasks without protection by extra locks. The following functions are allowed to run under ISR context.
Kconfig Options
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM controls where to place the GPTimer control functions (IRAM or flash).
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM controls where to place the GPTimer ISR handler (IRAM or flash).
CONFIG_GPTIMER_ISR_IRAM_SAFE controls whether the default ISR handler should be masked when the cache is disabled, see Section IRAM Safe for more information.
CONFIG_GPTIMER_ENABLE_DEBUG_LOG is used to enabled the debug log output. Enable this option will increase the firmware binary size.
Application Examples
Typical use cases of GPTimer are listed in the example peripherals/timer_group/gptimer.
API Reference
Header File
This header file can be included with:
#include "driver/gptimer.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t gptimer_new_timer(const gptimer_config_t *config, gptimer_handle_t *ret_timer)
Create a new General Purpose Timer, and return the handle.
Note
The newly created timer is put in the "init" state.
- Parameters
config -- |
[in] Timer handle created by
gptimer_new_timer
value -- [in] Count value to be set
-
- Returns
ESP_OK: Set GPTimer raw count value successfully
ESP_ERR_INVALID_ARG: Set GPTimer raw count value failed because of invalid argument
ESP_FAIL: Set GPTimer raw count value failed because of other error
-
-
esp_err_t gptimer_get_raw_count(gptimer_handle_t timer, uint64_t *value)
Get GPTimer raw count value.
Note
This function will trigger a software capture event and then return the captured count value.
Note
With the raw count value and the resolution returned from
gptimer_get_resolution, you can convert the count value into seconds.
Note
This function is allowed to run within ISR context
Note
If
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled.
- Parameters
timer -- [in] Timer handle created by
gptimer_new_timer
value -- [out] Returned GPTimer count value
-
- Returns
ESP_OK: Get GPTimer raw count value successfully
ESP_ERR_INVALID_ARG: Get GPTimer raw count value failed because of invalid argument
ESP_FAIL: Get GPTimer raw count value failed because of other error
-
-
esp_err_t gptimer_get_resolution(gptimer_handle_t timer, uint32_t *out_resolution)
Return the real resolution of the timer.
Note
usually the timer resolution is same as what you configured in the
gptimer_config_t::resolution_hz, but some unstable clock source (e.g. RC_FAST) will do a calibration, the real resolution can be different from the configured one.
- Parameters
timer -- |
Note
The capture action can be issued either by ETM event or by software (see also
gptimer_get_raw_count).
Note
This function is allowed to run within ISR context
Note
If
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled.
- Parameters
timer -- [in] Timer handle created by
gptimer_new_timer
value -- [out] Returned captured count value
-
- Returns
ESP_OK: Get GPTimer captured count value successfully
ESP_ERR_INVALID_ARG: Get GPTimer captured count value failed because of invalid argument
ESP_FAIL: Get GPTimer captured count value failed because of other error
-
-
esp_err_t gptimer_register_event_callbacks(gptimer_handle_t timer, const gptimer_event_callbacks_t *cbs, void *user_data)
Set callbacks for GPTimer.
Note
User registered callbacks are expected to be runnable within ISR context
Note
The first call to this function needs to be before the call to
gptimer_enable
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
cbsstructure to NULL.
- Parameters
timer -- |
[in] Timer handle created by
gptimer_new_timer
cbs -- [in] Group of callback functions
user_data -- [in] User data, which will be passed to callback functions directly
-
- Returns
ESP_OK: Set event callbacks successfully
ESP_ERR_INVALID_ARG: Set event callbacks failed because of invalid argument
ESP_ERR_INVALID_STATE: Set event callbacks failed because the timer is not in init state
ESP_FAIL: Set event callbacks failed because of other error
-
-
esp_err_t gptimer_set_alarm_action(gptimer_handle_t timer, const gptimer_alarm_config_t *config)
Set alarm event actions for GPTimer.
Note
This function is allowed to run within ISR context, so that user can set new alarm action immediately in the ISR callback.
Note
If
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled.
- Parameters
timer -- [in] Timer handle created by
gptimer_new_timer
config -- [in] Alarm configuration, especially, set config to NULL means disabling the alarm function
-
- Returns
ESP_OK: Set alarm action for GPTimer successfully
ESP_ERR_INVALID_ARG: Set alarm action for GPTimer failed because of invalid argument
ESP_FAIL: Set alarm action for GPTimer failed because of other error
-
-
esp_err_t gptimer_enable(gptimer_handle_t timer)
Enable GPTimer.
Note
This function will transit the timer state from "init" to "enable".
Note
This function will enable the interrupt service, if it's lazy installed in
gptimer_register_event_callbacks.
Note
This function will acquire a PM lock, if a specific source clock (e.g. APB) is selected in the
gptimer_config_t, while
CONFIG_PM_ENABLEis enabled.
Note
Enable a timer doesn't mean to start it. See also
gptimer_startfor how to make the timer start counting.
- Parameters
timer -- |
[in] Timer handle created by
gptimer_new_timer
- Returns
ESP_OK: Enable GPTimer successfully
ESP_ERR_INVALID_ARG: Enable GPTimer failed because of invalid argument
ESP_ERR_INVALID_STATE: Enable GPTimer failed because the timer is already enabled
ESP_FAIL: Enable GPTimer failed because of other error
-
-
esp_err_t gptimer_disable(gptimer_handle_t timer)
Disable GPTimer.
Note
This function will transit the timer state from "enable" to "init".
Note
This function will disable the interrupt service if it's installed.
Note
This function will release the PM lock if it's acquired in the
gptimer_enable.
Note
Disable a timer doesn't mean to stop it. See also
gptimer_stopfor how to make the timer stop counting.
- Parameters
timer -- |
[in] Timer handle created by
gptimer_new_timer
- Returns
ESP_OK: Disable GPTimer successfully
ESP_ERR_INVALID_ARG: Disable GPTimer failed because of invalid argument
ESP_ERR_INVALID_STATE: Disable GPTimer failed because the timer is not enabled yet
ESP_FAIL: Disable GPTimer failed because of other error
-
-
esp_err_t gptimer_start(gptimer_handle_t timer)
Start GPTimer (internal counter starts counting)
Note
This function will transit the timer state from "enable" to "run".
Note
This function is allowed to run within ISR context
Note
If
CONFIG_GPTIMER_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Flash Cache is disabled.
- Parameters
timer -- |
Stop GPTimer failed because the timer is not in running.
ESP_FAIL: Stop GPTimer failed because of other error
-
Structures
-
struct gptimer_config_t
General Purpose Timer configuration.
Public Members
-
gptimer_clock_source_t clk_src
GPTimer clock source
-
gptimer_count_direction_t direction
Count direction
-
uint32_t resolution_hz
Counter resolution (working frequency) in Hz, hence, the step size of each count tick equals to (1 / resolution_hz) seconds
-
int intr_priority
GPTimer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3)
Set true, the timer interrupt number can be shared with other peripherals
-
struct gptimer_config_t::[anonymous] flags
GPTimer config flags
- gptimer_clock_source_t clk_src
-
struct gptimer_event_callbacks_t
Group of supported GPTimer callbacks.
Note
The callbacks are all running under ISR environment
Note
When CONFIG_GPTIMER_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM.
|
Public Members
-
gptimer_alarm_cb_t on_alarm
Timer alarm callback
- gptimer_alarm_cb_t on_alarm
-
struct gptimer_alarm_config_t
General Purpose Timer alarm configuration.
Public Members
-
uint64_t alarm_count
Alarm target count value
-
uint64_t reload_count
Alarm reload count value, effect only when
auto_reload_on_alarmis set to true
-
uint32_t auto_reload_on_alarm
Reload the count value by hardware, immediately at the alarm event
-
struct gptimer_alarm_config_t::[anonymous] flags
Alarm config flags
- uint64_t alarm_count
Header File
This header file can be included with:
#include "driver/gptimer_etm.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t gptimer_new_etm_event(gptimer_handle_t timer, const gptimer_etm_event_config_t *config, esp_etm_event_handle_t *out_event)
Get the ETM event for GPTimer.
Note
The created ETM event object can be deleted later by calling
esp_etm_del_event
- Parameters
timer -- |
[in] Timer handle created by
gptimer_new_timer
config -- [in] GPTimer ETM event configuration
out_event -- [out] Returned ETM event handle
-
- Returns
ESP_OK: Get ETM event successfully
ESP_ERR_INVALID_ARG: Get ETM event failed because of invalid argument
ESP_FAIL: Get ETM event failed because of other error
-
-
esp_err_t gptimer_new_etm_task(gptimer_handle_t timer, const gptimer_etm_task_config_t *config, esp_etm_task_handle_t *out_task)
Get the ETM task for GPTimer.
Note
The created ETM task object can be deleted later by calling
esp_etm_del_task
- Parameters
timer -- |
[out] Returned ETM task handle
-
- Returns
ESP_OK: Get ETM task successfully
ESP_ERR_INVALID_ARG: Get ETM task failed because of invalid argument
ESP_FAIL: Get ETM task failed because of other error
-
Structures
-
struct gptimer_etm_event_config_t
GPTimer ETM event configuration.
Public Members
-
gptimer_etm_event_type_t event_type
GPTimer ETM event type
- gptimer_etm_event_type_t event_type
-
struct gptimer_etm_task_config_t
GPTimer ETM task configuration.
Public Members
-
gptimer_etm_task_type_t task_type
GPTimer ETM task type
- gptimer_etm_task_type_t task_type
Header File
This header file can be included with:
#include "driver/gptimer_types.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Structures
-
struct gptimer_alarm_event_data_t
GPTimer alarm event data.
|
[in] Timer handle created by
gptimer_new_timer
- Param edata
[in] Alarm event data, fed by driver
- Param user_ctx
[in] User data, passed from
gptimer_register_event_callbacks
- Return
Whether a high priority task has been waken up by this function
Header File
This header file can be included with:
#include "hal/timer_types.h"
Type Definitions
-
typedef soc_periph_gptimer_clk_src_t gptimer_clock_source_t
GPTimer clock source.
Note
User should select the clock source based on the power and resolution requirement
Enumerations
-
enum gptimer_count_direction_t
GPTimer count direction.
Values:
-
enumerator GPTIMER_COUNT_DOWN
Decrease count value
-
enumerator GPTIMER_COUNT_UP
Increase count value
- enumerator GPTIMER_COUNT_DOWN
-
enum gptimer_etm_task_type_t
GPTimer specific tasks that supported by the ETM module.
Values:
-
enumerator GPTIMER_ETM_TASK_START_COUNT
Start the counter
-
enumerator GPTIMER_ETM_TASK_STOP_COUNT
Stop the counter
-
enumerator GPTIMER_ETM_TASK_EN_ALARM
Enable the alarm
-
enumerator GPTIMER_ETM_TASK_RELOAD
Reload preset value into counter
-
enumerator GPTIMER_ETM_TASK_CAPTURE
Capture current count value into specific register
-
enumerator GPTIMER_ETM_TASK_MAX
Maximum number of tasks
- enumerator GPTIMER_ETM_TASK_START_COUNT
-
enum gptimer_etm_event_type_t
GPTimer specific events that supported by the ETM module.
Values:
-
enumerator GPTIMER_ETM_EVENT_ALARM_MATCH
Count value matches the alarm target value
-
enumerator GPTIMER_ETM_EVENT_MAX
Maximum number of events
- enumerator GPTIMER_ETM_EVENT_ALARM_MATCH
- 1
Different ESP chip series might have different numbers of GPTimer instances. For more details, please refer to ESP32 Technical Reference Manual > Chapter Timer Group (TIMG) |
Inter-Integrated Circuit (I2C)
Introduction
I2C is a serial, synchronous, multi-device, half-duplex communication protocol that allows co-existence of multiple masters and slaves on the same bus. I2C uses two bidirectional open-drain lines: serial data line (SDA) and serial clock line (SCL), pulled up by resistors.
ESP32 has 2 I2C controller (also called port), responsible for handling communication on the I2C bus. A single I2C controller can be a master or a slave.
Typically, an I2C slave device has a 7-bit address or 10-bit address. ESP32 supports both I2C Standard-mode (Sm) and Fast-mode (Fm) which can go up to 100KHz and 400KHz respectively.
Warning
The clock frequency of SCL in master mode should not be larger than 400 KHz
Note
The frequency of SCL is influenced by both the pull-up resistor and the wire capacitance. Therefore, users are strongly recommended to choose appropriate pull-up resistors to make the frequency accurate. The recommended value for pull-up resistors usually ranges from 1K Ohms to 10K Ohms.
Keep in mind that the higher the frequency, the smaller the pull-up resistor should be (but not less than 1 KOhms). Indeed, large resistors will decline the current, which will increase the clock switching time and reduce the frequency. We usually recommend a range of 2 KOhms to 5 KOhms, but users may also need to make some adjustments depending on their current draw requirements.
I2C Clock Configuration
i2c_clock_source_t::I2C_CLK_SRC_DEFAULT: Default I2C source clock.
i2c_clock_source_t::I2C_CLK_SRC_APB: APB clock as I2C clock source.
I2C File Structure
Public headers that need to be included in the I2C application
i2c.h: The header file of legacy I2C APIs (for apps using legacy driver).
|
The header file that provides standard communication mode specific APIs (for apps using new driver with master mode).
i2c_slave.h: The header file that provides standard communication mode specific APIs (for apps using new driver with slave mode).
Note
The legacy driver can't coexist with the new driver. Include
i2c.h to use the legacy driver or the other two headers to use the new driver. Please keep in mind that the legacy driver is now deprecated and will be removed in future.
Public headers that have been included in the headers above
i2c_types_legacy.h: The legacy public types that only used in the legacy driver.
|
i2c_device_config_t::device_addressI2C device raw address. Please parse the device address to this member directly. For example, the device address is 0x28, then parse 0x28 to
i2c_device_config_t::device_address, don't carry a write/read bit.
i2c_device_config_t::scl_speed_hzset the scl line frequency of this device.
Once the
i2c_device_config_t structure is populated with mandatory parameters, users can call
i2c_master_bus_add_device() to allocate an I2C device instance and mounted to the master bus then. This function will return an I2C device handle if it runs correctly. Specifically, when the I2C bus is not initialized properly, calling this function will result in a
ESP_ERR_INVALID_ARG error.
|
= 7,
.flags.enable_internal_pullup = true,
};
i2c_master_bus_handle_t bus_handle;
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
i2c_device_config_t dev_cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = 0x58,
.scl_speed_hz = 100000,
};
i2c_master_dev_handle_t dev_handle;
ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
Uninstall I2C master bus and device
If a previously installed I2C bus or device is no longer needed, it's recommended to recycle the resource by calling
i2c_master_bus_rm_device() or
i2c_del_master_bus(), so that to release the underlying hardware.
Install I2C slave device
I2C slave requires the configuration that specified by
i2c_slave_config_t:
i2c_slave_config_t::i2c_portsets the I2C port used by the controller.
i2c_slave_config_t::sda_io_numsets the GPIO number for serial data bus (SDA).
i2c_slave_config_t::scl_io_numsets the GPIO number for serial clock bus (SCL).
i2c_slave_config_t::clk_sourceselects the source clock for I2C bus. The available clocks are listed in
i2c_clock_source_t. For the effect on power consumption of different clock source, please refer to Power Management section.
i2c_slave_config_t::send_buf_depthsets the sending buffer length.
i2c_slave_config_t::slave_addrsets the slave address
i2c_master_bus_config_t::intr_prioritySet the priority of the interrupt. If set to
0, then the driver will use a interrupt with low or medium priority (priority level may be one of 1,2 or 3), otherwise use the priority indicated by
i2c_master_bus_config_t::intr_priorityPlease use the number form (1,2,3) , not the bitmask form ((1<<1),(1<<2),(1<<3)). Please pay attention that once the interrupt priority is set, it cannot be changed until
i2c_del_master_bus()is called.
i2c_slave_config_t::addr_bit_lensets true if you need the slave to have a 10-bit address.
Once the
i2c_slave_config_t structure is populated with mandatory parameters, users can call
i2c_new_slave_device() to allocate and initialize an I2C master bus. This function will return an I2C bus handle if it runs correctly. Specifically, when there are no more I2C port available, this function will return
ESP_ERR_NOT_FOUND error.
|
Uninstall I2C slave device
If a previously installed I2C bus is no longer needed, it's recommended to recycle the resource by calling
i2c_del_slave_device(), so that to release the underlying hardware.
I2C Master Controller
After installing the i2c master driver by
i2c_new_master_bus(), ESP32 is ready to communicate with other I2C devices. I2C APIs allow the standard transactions. Like the wave as follows:
I2C Master Write
After installing I2C master bus successfully, you can simply call
i2c_master_transmit() to write data to the slave device. The principle of this function can be explained by following chart.
In order to organize the process, the driver uses a command link, that should be populated with a sequence of commands and then passed to I2C controller for execution.
Simple example for writing data to slave:
#define DATA_LENGTH 100
i2c_master_bus_config_t i2c_mst_config = {
.clk_source = |
I2C_MASTER_SDA_IO,
.glitch_ignore_cnt = 7,
};
i2c_master_bus_handle_t bus_handle;
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
i2c_device_config_t dev_cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = 0x58,
.scl_speed_hz = 100000,
};
i2c_master_dev_handle_t dev_handle;
ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
ESP_ERROR_CHECK(i2c_master_transmit(dev_handle, data_wr, DATA_LENGTH, -1));
I2C Master Read
After installing I2C master bus successfully, you can simply call
i2c_master_receive() to read data from the slave device. The principle of this function can be explained by following chart.
Simple example for reading data from slave:
#define DATA_LENGTH 100
i2c_master_bus_config_t i2c_mst_config = {
.clk_source = |
I2C_MASTER_SDA_IO,
.glitch_ignore_cnt = 7,
};
i2c_master_bus_handle_t bus_handle;
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));
i2c_device_config_t dev_cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = 0x58,
.scl_speed_hz = 100000,
};
i2c_master_dev_handle_t dev_handle;
ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
i2c_master_receive(dev_handle, data_rd, DATA_LENGTH, -1);
I2C Master Write and Read
Some I2C device needs write configurations before reading data from it, therefore, an interface called
i2c_master_transmit_receive() can help. The principle of this function can be explained by following chart.
Simple example for writing and reading from slave:
|
i2c_device_config_t dev_cfg = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = 0x58,
.scl_speed_hz = 100000,
};
i2c_master_dev_handle_t dev_handle;
ESP_ERROR_CHECK(i2c_master_bus_add_device(I2C_PORT_NUM_0, &dev_cfg, &dev_handle));
uint8_t buf[20] = {0x20};
uint8_t buffer[2];
ESP_ERROR_CHECK(i2c_master_transmit_receive(i2c_bus_handle, buf, sizeof(buf), buffer, 2, -1));
I2C Master Probe
I2C driver can use
i2c_master_probe() to detect whether the specific device has been connected on I2C bus. If this function return
ESP_OK, that means the device has been detected.
|
= 7,
.flags.enable_internal_pullup = true,
};
i2c_master_bus_handle_t bus_handle;
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config_1, &bus_handle));
ESP_ERROR_CHECK(i2c_master_probe(bus_handle, 0x22, -1));
ESP_ERROR_CHECK(i2c_del_master_bus(bus_handle));
I2C Slave Controller
After installing the i2c slave driver by
i2c_new_slave_device(), ESP32 is ready to communicate with other I2C master as a slave.
I2C Slave Write
The send buffer of the I2C slave is used as a FIFO to store the data to be sent. The data will queue up until the master requests them. You can call
i2c_slave_transmit() to transfer data.
Simple example for writing data to FIFO:
uint8_t *data_wr = (uint8_t *) malloc(DATA_LENGTH);
i2c_slave_config_t i2c_slv_config = {
.addr_bit_len = I2C_ADDR_BIT_LEN_7, // 7-bit address
.clk_source = I2C_CLK_SRC_DEFAULT, // set the clock source
.i2c_port = 0, // set I2C port number
.send_buf_depth = 256, // set tx buffer length
.scl_io_num = 2, // SCL gpio number
.sda_io_num = 1, // SDA gpio number
.slave_addr = 0x58, // slave address
};
i2c_bus_handle_t i2c_bus_handle;
ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &i2c_bus_handle));
for (int i = 0; i < DATA_LENGTH; i++) {
data_wr[i] = i;
}
ESP_ERROR_CHECK(i2c_slave_transmit(i2c_bus_handle, data_wr, DATA_LENGTH, 10000));
I2C Slave Read
Whenever the master writes data to the slave, the slave will automatically store data in the receive buffer. This allows the slave application to call the function
i2c_slave_receive() as its own discretion. As
i2c_slave_receive() is designed as a non-blocking interface. So the user needs to register callback
i2c_slave_register_event_callbacks() to know when the receive has finished.
static IRAM_ATTR |
bool i2c_slave_rx_done_callback(i2c_slave_dev_handle_t channel, const i2c_slave_rx_done_event_data_t *edata, void *user_data)
{
BaseType_t high_task_wakeup = pdFALSE;
QueueHandle_t receive_queue = (QueueHandle_t)user_data;
xQueueSendFromISR(receive_queue, edata, &high_task_wakeup);
return high_task_wakeup == pdTRUE;
}
uint8_t *data_rd = (uint8_t *) malloc(DATA_LENGTH);
uint32_t size_rd = 0;
i2c_slave_config_t i2c_slv_config = {
.addr_bit_len = I2C_ADDR_BIT_LEN_7,
.clk_source = I2C_CLK_SRC_DEFAULT,
.i2c_port = TEST_I2C_PORT,
.send_buf_depth = 256,
.scl_io_num = I2C_SLAVE_SCL_IO,
.sda_io_num = I2C_SLAVE_SDA_IO,
.slave_addr = 0x58,
};
i2c_slave_dev_handle_t slave_handle;
ESP_ERROR_CHECK(i2c_new_slave_device(&i2c_slv_config, &slave_handle));
s_receive_queue = xQueueCreate(1, sizeof(i2c_slave_rx_done_event_data_t));
i2c_slave_event_callbacks_t cbs = {
.on_recv_done = i2c_slave_rx_done_callback,
};
ESP_ERROR_CHECK(i2c_slave_register_event_callbacks(slave_handle, &cbs, s_receive_queue));
i2c_slave_rx_done_event_data_t rx_data;
ESP_ERROR_CHECK(i2c_slave_receive(slave_handle, data_rd, DATA_LENGTH));
xQueueReceive(s_receive_queue, &rx_data, pdMS_TO_TICKS(10000));
// |
Register Event Callbacks
I2C master callbacks
When an I2C master bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some functions that need to be called when those events occurred, you can hook your functions to the ISR (Interrupt Service Routine) by calling
i2c_master_register_event_callbacks(). Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with
ISR suffix are called from within the function). The callback functions are required to return a boolean value, to tell the ISR whether a high priority task is woke up by it.
I2C master event callbacks are listed in the
i2c_master_event_callbacks_t.
Although I2C is a synchronous communication protocol, we also support asynchronous behavior by registering above callback. In this way, I2C APIs will be non-blocking interface. But note that on the same bus, only one device can adopt asynchronous operation.
Important
I2C master asynchronous transaction is still an experimental feature. (The issue is when asynchronous transaction is very large, it will cause memory problem.)
i2c_master_event_callbacks_t::on_recv_donesets a callback function for master "transaction-done" event. The function prototype is declared in
i2c_master_callback_t.
I2C slave callbacks
When an I2C slave bus triggers an interrupt, a specific event will be generated and notify the CPU. If you have some function that needs to be called when those events occurred, you can hook your function to the ISR (Interrupt Service Routine) by calling
i2c_slave_register_event_callbacks(). Since the registered callback functions are called in the interrupt context, user should ensure the callback function doesn't attempt to block (e.g. by making sure that only FreeRTOS APIs with
ISR suffix are called from within the function). The callback function has a boolean return value, to tell the caller whether a high priority task is woke up by it.
I2C slave event callbacks are listed in the
i2c_slave_event_callbacks_t.
|
i2c_slave_event_callbacks_t::on_recv_donesets a callback function for "receive-done" event. The function prototype is declared in
i2c_slave_received_callback_t.
Power Management
When the power management is enabled (i.e. CONFIG_PM_ENABLE is on), the system will adjust or stop the source clock of I2C fifo before going into light sleep, thus potentially changing the I2C signals and leading to transmitting or receiving invalid data.
However, the driver can prevent the system from changing APB frequency by acquiring a power management lock of type
ESP_PM_APB_FREQ_MAX. Whenever user creates an I2C bus that has selected
I2C_CLK_SRC_APB as the clock source, the driver will guarantee that the power management lock is acquired when I2C operations begin and release the lock automatically when I2C operations finish.
IRAM Safe
By default, the I2C interrupt will be deferred when the Cache is disabled for reasons like writing/erasing Flash. Thus the event callback functions will not get executed in time, which is not expected in a real-time application.
There's a Kconfig option CONFIG_I2C_ISR_IRAM_SAFE that will:
Enable the interrupt being serviced even when cache is disabled
Place all functions that used by the ISR into IRAM
Place driver object into DRAM (in case it's mapped to PSRAM by accident)
This will allow the interrupt to run while the cache is disabled but will come at the cost of increased IRAM consumption.
Thread Safety
The factory function
i2c_new_master_bus() and
i2c_new_slave_device() are guaranteed to be thread safe by the driver, which means, user can call them from different RTOS tasks without protection by extra locks. Other public I2C APIs are not thread safe. which means the user should avoid calling them from multiple tasks, if user strongly needs to call them in multiple tasks, please add extra lock.
Kconfig Options
CONFIG_I2C_ISR_IRAM_SAFE controls whether the default ISR handler can work when cache is disabled, see also IRAM Safe for more information.
CONFIG_I2C_ENABLE_DEBUG_LOG is used to enable the debug log at the cost of increased firmware binary size.
API Reference
Header File
This header file can be included with:
#include "driver/i2c_master.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t i2c_new_master_bus(const i2c_master_bus_config_t *bus_config, i2c_master_bus_handle_t *ret_bus_handle)
Allocate an I2C master bus.
- Parameters
bus_config -- |
Create I2C bus failed because of out of memory.
-
-
esp_err_t i2c_del_master_bus(i2c_master_bus_handle_t bus_handle)
Deinitialize the I2C master bus and delete the handle.
- Parameters
bus_handle -- [in] I2C bus handle.
- Returns
ESP_OK: Delete I2C bus success, otherwise, failed.
Otherwise: Some module delete failed.
-
-
esp_err_t i2c_master_bus_rm_device(i2c_master_dev_handle_t handle)
I2C master bus delete device.
- Parameters
handle -- i2c device handle
- Returns
ESP_OK: If device is successfully deleted.
-
-
esp_err_t i2c_master_transmit(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, int xfer_timeout_ms)
Perform a write transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided.
Note
If a callback was registered with
i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt.
- Parameters
i2c_dev -- [in] I2C master device handle that created by
i2c_master_bus_add_device.
write_buffer -- [in] Data bytes to send on the I2C bus.
write_size -- [in] Size, in bytes, of the write buffer.
xfer_timeout_ms -- [in] Wait timeout, in ms. Note: -1 means wait forever.
-
- Returns
ESP_OK: I2C master transmit success
ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid.
ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash.
-
-
esp_err_t i2c_master_transmit_receive(i2c_master_dev_handle_t i2c_dev, const uint8_t *write_buffer, size_t write_size, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms)
Perform a write-read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided.
Note
If a callback was registered with
i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt.
- Parameters
i2c_dev -- [in] I2C master device handle that created by
i2c_master_bus_add_device.
write_buffer -- [in] Data bytes to send on the I2C bus.
write_size -- [in] Size, in bytes, of the write buffer.
read_buffer -- [out] Data bytes received from i2c bus.
read_size -- [in] Size, in bytes, of the read buffer.
|
[in] Wait timeout, in ms. Note: -1 means wait forever.
-
- Returns
ESP_OK: I2C master transmit-receive success
ESP_ERR_INVALID_ARG: I2C master transmit parameter invalid.
ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash.
-
-
esp_err_t i2c_master_receive(i2c_master_dev_handle_t i2c_dev, uint8_t *read_buffer, size_t read_size, int xfer_timeout_ms)
Perform a read transaction on the I2C bus. The transaction will be undergoing until it finishes or it reaches the timeout provided.
Note
If a callback was registered with
i2c_master_register_event_callbacks, the transaction will be asynchronous, and thus, this function will return directly, without blocking. You will get finish information from callback. Besides, data buffer should always be completely prepared when callback is registered, otherwise, the data will get corrupt.
- Parameters
i2c_dev -- [in] I2C master device handle that created by
i2c_master_bus_add_device.
read_buffer -- [out] Data bytes received from i2c bus.
|
[in] Wait timeout, in ms. Note: -1 means wait forever.
-
- Returns
ESP_OK: I2C master receive success
ESP_ERR_INVALID_ARG: I2C master receive parameter invalid.
ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash.
-
-
esp_err_t i2c_master_probe(i2c_master_bus_handle_t bus_handle, uint16_t address, int xfer_timeout_ms)
Probe I2C address, if address is correct and ACK is received, this function will return ESP_OK.
- Parameters
bus_handle -- [in] I2C master device handle that created by
i2c_master_bus_add_device.
address -- [in] I2C device address that you want to probe.
|
[in] Wait timeout, in ms. Note: -1 means wait forever (Not recommended in this function).
-
- Returns
ESP_OK: I2C device probe successfully
ESP_ERR_NOT_FOUND: I2C probe failed, doesn't find the device with specific address you gave.
ESP_ERR_TIMEOUT: Operation timeout(larger than xfer_timeout_ms) because the bus is busy or hardware crash.
-
-
esp_err_t i2c_master_register_event_callbacks(i2c_master_dev_handle_t i2c_dev, const i2c_master_event_callbacks_t *cbs, void *user_data)
Register I2C transaction callbacks for a master device.
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
cbsstructure to NULL.
Note
When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The
user_datashould also reside in SRAM.
Note
If the callback is used for helping asynchronous transaction. On the same bus, only one device can be used for performing asynchronous operation.
|
- Parameters
i2c_dev -- [in] I2C master device handle that created by
i2c_master_bus_add_device.
cbs -- [in] Group of callback functions
user_data -- [in] User data, which will be passed to callback functions directly
-
- Returns
ESP_OK: Set I2C transaction callbacks successfully
ESP_ERR_INVALID_ARG: Set I2C transaction callbacks failed because of invalid argument
ESP_FAIL: Set I2C transaction callbacks failed because of other error
-
-
esp_err_t i2c_master_bus_reset(i2c_master_bus_handle_t bus_handle)
Reset the I2C master bus.
- Parameters
bus_handle -- I2C bus handle.
- Returns
ESP_OK: Reset succeed.
|
Otherwise: Reset failed.
-
-
esp_err_t i2c_master_bus_wait_all_done(i2c_master_bus_handle_t bus_handle, int timeout_ms)
Wait for all pending I2C transactions done.
- Parameters
bus_handle -- [in] I2C bus handle
timeout_ms -- [in] Wait timeout, in ms. Specially, -1 means to wait forever.
-
- Returns
ESP_OK: Flush transactions successfully
ESP_ERR_INVALID_ARG: Flush transactions failed because of invalid argument
ESP_ERR_TIMEOUT: Flush transactions failed because of timeout
ESP_FAIL: Flush transactions failed because of other error
-
Structures
-
struct i2c_master_bus_config_t
I2C master bus specific configurations.
Public Members
-
i2c_port_num_t i2c_port
I2C port number,
-1for auto selecting
-
gpio_num_t sda_io_num
GPIO number of I2C SDA signal, pulled-up internally
-
gpio_num_t scl_io_num
GPIO number of I2C SCL signal, pulled-up internally
-
i2c_clock_source_t clk_source
Clock source of I2C master bus, channels in the same group must use the same clock source
-
uint8_t glitch_ignore_cnt
If the glitch period on the line is less than this value, it can be filtered out, typically value is 7 (unit: I2C module clock cycle)
-
int intr_priority
I2C interrupt priority, if set to 0, driver will select the default priority (1,2,3).
-
size_t trans_queue_depth
Depth of internal transfer queue, increase this value can support more transfers pending in the background, only valid in asynchronous transaction. (Typically max_device_num * per_transaction)
-
uint32_t enable_internal_pullup
Enable internal pullups. Note: This is not strong enough to pullup buses under high-speed frequency. Recommend proper external pull-up if possible
-
struct i2c_master_bus_config_t::[anonymous] flags
I2C master config flags
- i2c_port_num_t i2c_port
-
struct i2c_device_config_t
I2C device configuration.
Public Members
-
i2c_addr_bit_len_t dev_addr_length
Select the address length of the slave device.
-
uint16_t device_address
I2C device raw address. (The 7/10 bit address without read/write bit)
-
uint32_t scl_speed_hz
I2C SCL line frequency.
- i2c_addr_bit_len_t dev_addr_length
-
struct i2c_master_event_callbacks_t
Group of I2C master callbacks, can be used to get status during transaction or doing other small things. But take care potential concurrency issues.
Note
The callbacks are all running under ISR context
Note
When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well.
|
Public Members
-
i2c_master_callback_t on_trans_done
I2C master transaction finish callback
- i2c_master_callback_t on_trans_done
Header File
This header file can be included with:
#include "driver/i2c_slave.h"
This header file is a part of the API provided by the
drivercomponent. To declare that your component depends on
driver, add the following to your CMakeLists.txt:
REQUIRES driver
or
PRIV_REQUIRES driver
Functions
-
esp_err_t i2c_new_slave_device(const i2c_slave_config_t *slave_config, i2c_slave_dev_handle_t *ret_handle)
Initialize an I2C slave device.
|
I2C device initialization failed because of invalid argument.
-
-
esp_err_t i2c_slave_receive(i2c_slave_dev_handle_t i2c_slave, uint8_t *data, size_t buffer_size)
Read bytes from I2C internal buffer. Start a job to receive I2C data.
Note
This function is non-blocking, it initiates a new receive job and then returns. User should check the received data from the
on_recv_donecallback that registered by
i2c_slave_register_event_callbacks().
- Parameters
i2c_slave -- [in] I2C slave device handle that created by
i2c_new_slave_device.
data -- [out] Buffer to store data from I2C fifo. Should be valid until
on_recv_doneis triggered.
|
ESP_ERR_INVALID_ARG: I2C slave receive parameter invalid.
ESP_ERR_NOT_SUPPORTED: This function should be work in fifo mode, but I2C_SLAVE_NONFIFO mode is configured
-
-
esp_err_t i2c_slave_transmit(i2c_slave_dev_handle_t i2c_slave, const uint8_t *data, int size, int xfer_timeout_ms)
Write bytes to internal ringbuffer of the I2C slave data. When the TX fifo empty, the ISR will fill the hardware FIFO with the internal ringbuffer's data.
Note
If you connect this slave device to some master device, the data transaction direction is from slave device to master device.
- Parameters
i2c_slave -- [in] I2C slave device handle that created by
i2c_new_slave_device.
|
-
-
esp_err_t i2c_slave_register_event_callbacks(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_event_callbacks_t *cbs, void *user_data)
Set I2C slave event callbacks for I2C slave channel.
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
cbsstructure to NULL.
Note
When CONFIG_I2C_ISR_IRAM_SAFE is enabled, the callback itself and functions called by it should be placed in IRAM. The variables used in the function should be in the SRAM as well. The
user_datashould also reside in SRAM.
- Parameters
i2c_slave -- [in] I2C slave device handle that created by
i2c_new_slave_device.
|
Inter-IC Sound (I2S)
Introduction
I2S (Inter-IC Sound) is a synchronous serial communication protocol usually used for transmitting audio data between two digital audio devices.
ESP32 contains two I2S peripheral(s). These peripherals can be configured to input and output sample data via the I2S driver.
An I2S bus that communicates in standard or TDM mode consists of the following lines:
MCLK: Master clock line. It is an optional signal depending on the slave side, mainly used for offering a reference clock to the I2S slave device.
|
DIN/DOUT: Serial data input/output line.
Each I2S controller has the following features that can be configured by the I2S driver:
Operation as system master or slave
Capable of acting as transmitter or receiver
DMA controller that allows stream sampling of data without requiring the CPU to copy each data sample
Each controller supports single RX or TX simplex communication. As RX and TX channels share a clock, they can only be combined with the same configuration to establish a full-duplex communication.
I2S File Structure
Public headers that need to be included in the I2S application are as follows:
i2s.h: The header file that provides legacy I2S APIs (for apps using legacy driver).
i2s_std.h: The header file that provides standard communication mode specific APIs (for apps using new driver with standard mode).
i2s_pdm.h: The header file that provides PDM communication mode specific APIs (for apps using new driver with PDM mode).
i2s_tdm.h: The header file that provides TDM communication mode specific APIs (for apps using new driver with TDM mode).
Note
The legacy driver cannot coexist with the new driver. Include
i2s.h to use the legacy driver, or include the other three headers to use the new driver. The legacy driver might be removed in future.
Public headers that have been included in the headers above are as follows:
i2s_types_legacy.h: The header file that provides legacy public types that are only used in the legacy driver.
i2s_types.h: The header file that provides public types.
i2s_common.h: The header file that provides common APIs for all communication modes.
I2S Clock
Clock Source
i2s_clock_src_t::I2S_CLK_SRC_DEFAULT: Default PLL clock.
i2s_clock_src_t::I2S_CLK_SRC_PLL_160M: 160 MHz PLL clock.
|
LRCK / WS: Left/right clock or word select clock. For non-PDM mode, its frequency is equal to the sample rate.
Note
Normally, MCLK should be the multiple of
sample rate and BCLK at the same time. The field
i2s_std_clk_config_t::mclk_multiple indicates the multiple of MCLK to the
sample rate. In most cases,
I2S_MCLK_MULTIPLE_256 should be enough. However, if
slot_bit_width is set to
I2S_SLOT_BIT_WIDTH_24BIT, to keep MCLK a multiple to the BCLK,
i2s_std_clk_config_t::mclk_multiple should be set to multiples that are divisible by 3 such as
I2S_MCLK_MULTIPLE_384. |
Otherwise, WS will be inaccurate.
I2S Communication Mode
Overview of All Modes
|
Target
|
Standard
|
PDM TX
|
PDM RX
|
TDM
|
ADC/DAC
|
LCD/Camera
|
ESP32
|
I2S 0/1
|
I2S 0
|
I2S 0
|
none
|
I2S 0
|
I2S 0
|
ESP32-S2
|
I2S 0
|
none
|
none
|
none
|
none
|
I2S 0
|
ESP32-C3
|
I2S 0
|
I2S 0
|
none
|
I2S 0
|
none
|
none
|
ESP32-C6
|
I2S 0
|
I2S 0
|
none
|
I2S 0
|
none
|
none
|
ESP32-S3
|
I2S 0/1
|
I2S 0
|
I2S 0
|
I2S 0/1
|
none
|
none
|
ESP32-H2
|
I2S 0
|
I2S 0
|
none
|
I2S 0
|
none
|
none
|
ESP32-P4
|
I2S 0~2
|
I2S 0
|
I2S 0
|
I2S 0~2
|
none
|
none
Standard Mode
In standard mode, there are always two sound channels, i.e., the left and right channels, which are called "slots". |
These slots support 8/16/24/32-bit width sample data. The communication format for the slots mainly includes the followings:
Philips Format: Data signal has one-bit shift comparing to the WS signal, and the duty of WS signal is 50%.
MSB Format: Basically the same as Philips format, but without data shift.
PCM Short Format: Data has one-bit shift and meanwhile the WS signal becomes a pulse lasting for one BCLK cycle.
PDM Mode (TX)
PDM (Pulse-density Modulation) mode for the TX channel can convert PCM data into PDM format which always has left and right slots. PDM TX is only supported on I2S0 and it only supports 16-bit width sample data. It needs at least a CLK pin for clock signal and a DOUT pin for data signal (i.e., the WS and SD signal in the following figure; the BCK signal is an internal bit sampling clock, which is not needed between PDM devices). This mode allows users to configure the up-sampling parameters
i2s_pdm_tx_clk_config_t::up_sample_fp and
i2s_pdm_tx_clk_config_t::up_sample_fs. The up-sampling rate can be calculated by
up_sample_rate = i2s_pdm_tx_clk_config_t::up_sample_fp / i2s_pdm_tx_clk_config_t::up_sample_fs. |