data
stringlengths 512
2.99k
|
---|
Setting
fp = 960and
fs = sample_rate / 100, then the clock frequency (Fpdm) on CLK pin will be fixed to
128 * 48 KHz = 6.144 MHz. Note that this frequency is not equal to the sample rate (Fpcm).
Fixed Up-sampling Rate: In this mode, the up-sampling rate is fixed to 2. Setting
fp = 960and
fs = 480, then the clock frequency (Fpdm) on CLK pin will be
128 * sample_rate.
PDM Mode (RX)
PDM (Pulse-density Modulation) mode for RX channel can receive PDM-format data and convert the data into PCM format. PDM RX is only supported on I2S0, and it only supports 16-bit width sample data. PDM RX needs at least a CLK pin for clock signal and a DIN pin for data signal. This mode allows users to configure the down-sampling parameter
i2s_pdm_rx_clk_config_t::dn_sample_mode. |
LCD Mode [PDF].
ADC/DAC Mode
ADC and DAC modes only exist on ESP32 and are only supported on I2S0. Actually, they are two sub-modes of LCD/Camera mode. I2S0 can be routed directly to the internal analog-to-digital converter (ADC) and digital-to-analog converter (DAC). In other words, ADC and DAC peripherals can read or write continuously via I2S0 DMA. As they are not actual communication modes, the I2S driver does not implement them.
Functional Overview
The I2S driver offers the following services:
Resource Management
There are three levels of resources in the I2S driver:
platform level: Resources of all I2S controllers in the current target.
controller level: Resources in one I2S controller.
channel level: Resources of TX or RX channel in one I2S controller.
The public APIs are all channel-level APIs. The channel handle
i2s_chan_handle_t can help users to manage the resources under a specific channel without considering the other two levels. The other two upper levels' resources are private and are managed by the driver automatically. |
Users can call
i2s_new_channel() to allocate a channel handle and call
i2s_del_channel() to delete it.
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 I2S before entering Light-sleep, thus potentially changing the I2S signals and leading to transmitting or receiving invalid data.
The I2S driver can prevent the system from changing or stopping the source clock by acquiring a power management lock. When the source clock is generated from APB, the lock type will be set to
esp_pm_lock_type_t::ESP_PM_APB_FREQ_MAX and when the source clock is APLL (if supported), it will be set to
esp_pm_lock_type_t::ESP_PM_NO_LIGHT_SLEEP. Whenever the user is reading or writing via I2S (i.e., calling
i2s_channel_read() or
i2s_channel_write()), the driver guarantees that the power management lock is acquired. Likewise, the driver releases the lock after the reading or writing finishes.
|
Finite State Machine
There are three states for an I2S channel, namely,
registered,
ready, and
running. Their relationship is shown in the following diagram:
The
<mode> in the diagram can be replaced by corresponding I2S communication modes, e.g.,
std for standard two-slot mode. For more information about communication modes, please refer to the I2S Communication Mode section.
Data Transport
The data transport of the I2S peripheral, including sending and receiving, is realized by DMA. Before transporting data, please call
i2s_channel_enable() to enable the specific channel. When the sent or received data reaches the size of one DMA buffer, the
I2S_OUT_EOF or
I2S_IN_SUC_EOF interrupt will be triggered. Note that the DMA buffer size is not equal to
i2s_chan_config_t::dma_frame_num. One frame here refers to all the sampled data in one WS circle. Therefore,
dma_buffer_size = |
They keeps waiting until the whole source buffer is sent or the whole destination buffer is loaded, unless they exceed the max blocking time, where the error code
ESP_ERR_TIMEOUT returns. To send or receive data asynchronously, callbacks can be registered by
i2s_channel_register_event_callback(). Users are able to access the DMA buffer directly in the callback function instead of transmitting or receiving by the two blocking functions. However, please be aware that it is an interrupt callback, so do not add complex logic, run floating operation, or call non-reentrant functions in the callback.
|
Configuration
Users can initialize a channel by calling corresponding functions (i.e.,
i2s_channel_init_std_mode(),
i2s_channel_init_pdm_rx_mode(),
i2s_channel_init_pdm_tx_mode(), or
i2s_channel_init_tdm_mode()) to a specific mode. If the configurations need to be updated after initialization, users have to first call
i2s_channel_disable() to ensure that the channel has stopped, and then call corresponding
reconfig functions, like
i2s_channel_reconfig_std_slot(),
i2s_channel_reconfig_std_clock(), and
i2s_channel_reconfig_std_gpio().
IRAM Safe
By default, the I2S interrupt will be deferred when the cache is disabled for reasons like writing/erasing flash. Thus the EOF interrupt will not get executed in time.
To avoid such case in real-time applications, you can enable the Kconfig option CONFIG_I2S_ISR_IRAM_SAFE that:
Keeps the interrupt being serviced even when the cache is disabled.
Places driver object into DRAM (in case it is linked to PSRAM by accident).
This allows the interrupt to run while the cache is disabled, but comes at the cost of increased IRAM consumption.
Thread Safety
All the public I2S APIs are guaranteed to be thread safe by the driver, which means users can call them from different RTOS tasks without protection by extra locks. Notice that the I2S driver uses mutex lock to ensure the thread safety, thus these APIs are not allowed to be used in ISR.
Kconfig Options
CONFIG_I2S_ISR_IRAM_SAFE controls whether the default ISR handler can work when the cache is disabled. See IRAM Safe for more information.
CONFIG_I2S_SUPPRESS_DEPRECATE_WARN controls whether to suppress the compiling warning message while using the legacy I2S driver.
CONFIG_I2S_ENABLE_DEBUG_LOG is used to enable the debug log output. Enable this option increases the firmware binary size.
Application Example
The examples of the I2S driver can be found in the directory peripherals/i2s. Here are some simple usages of each mode:
Standard TX/RX Usage
Different slot communication formats can be generated by the following helper macros for standard mode. As described above, there are three formats in standard mode, and their helper macros are:
The clock config helper macro is:
Please refer to Standard Mode for information about STD API. |
When the data in a
uint16_t writing buffer are:
|
data 0
|
data 1
|
data 2
|
data 3
|
data 4
|
data 5
|
data 6
|
data 7
|
...
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
|
...
Here is the table of the real data on the line with different
i2s_std_slot_config_t::slot_mode and
i2s_std_slot_config_t::slot_mask.
|
data bit width
|
slot mode
|
slot mask
|
WS low
|
WS high
|
WS low
|
WS high
|
WS low
|
WS high
|
WS low
|
WS high
|
16 bit
|
mono
|
left
|
0x0002
|
0x0000
|
0x0001
|
0x0000
|
0x0004
|
0x0000
|
0x0003
|
0x0000
|
right
|
0x0000
|
0x0002
|
0x0000
|
0x0001
|
0x0000
|
0x0004
|
0x0000
|
0x0003
|
both
|
0x0002
|
0x0002
|
0x0001
|
0x0001
|
0x0004
|
0x0004
|
0x0003
|
0x0003
|
stereo
|
left
|
0x0001
|
0x0001
|
0x0003
|
0x0003
|
0x0005
|
0x0005
|
0x0007
|
0x0007
|
right
|
0x0002
|
0x0002
|
0x0004
|
0x0004
|
0x0006
|
0x0006
|
0x0008
|
0x0008
|
both
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
Note
|
It is similar when the data is 32-bit width, but take care when using 8-bit and 24-bit data width. For 8-bit width, the written buffer should still use
uint16_t (i.e., align with 2 bytes), and only the high 8 bits are valid while the low 8 bits are dropped. For 24-bit width, the buffer is supposed to use
uint32_t (i.e., align with 4 bytes), and only the high 24 bits are valid while the low 8 bits are dropped.
Besides, for 8-bit and 16-bit mono modes, the real data on the line is swapped. To get the correct data sequence, the writing buffer needs to swap the data every two bytes.
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
/* Get the default channel configuration by the helper macro.
* |
false,
.ws_inv = false,
},
},
};
/ * Initialize the channel */
i2s_channel_init_std_mode(tx_handle, &std_cfg);
/ * Before writing data, start the TX channel first */
i2s_channel_enable(tx_handle);
i2s_channel_write(tx_handle, src_buf, bytes_to_write, bytes_written, ticks_to_wait);
/* If the configurations of slot or clock need to be updated,
* stop the channel first and then update it */
// i2s_channel_disable(tx_handle);
// std_cfg.slot_cfg.slot_mode = I2S_SLOT_MODE_MONO; // Default is stereo
// i2s_channel_reconfig_std_slot(tx_handle, &std_cfg.slot_cfg);
// std_cfg.clk_cfg.sample_rate_hz = 96000;
// i2s_channel_reconfig_std_clock(tx_handle, &std_cfg.clk_cfg);
/* Have to stop the channel before deleting it */
i2s_channel_disable(tx_handle);
/ * |
If the handle is not needed any more, delete it to release the channel resources */
i2s_del_channel(tx_handle);
STD RX Mode
Taking 16-bit data width for example, when the data on the line are:
|
WS low
|
WS high
|
WS low
|
WS high
|
WS low
|
WS high
|
WS low
|
WS high
|
...
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
|
...
Here is the table of the data received in the buffer with different
i2s_std_slot_config_t::slot_mode and
i2s_std_slot_config_t::slot_mask.
|
data bit width
|
slot mode
|
slot mask
|
data 0
|
data 1
|
data 2
|
data 3
|
data 4
|
data 5
|
data 6
|
data 7
|
16 bit
|
mono
|
left
|
0x0001
|
0x0000
|
0x0005
|
0x0003
|
0x0009
|
0x0007
|
0x000d
|
0x000b
|
right
|
0x0002
|
0x0000
|
0x0006
|
0x0004
|
0x000a
|
0x0008
|
0x000e
|
0x000c
|
stereo
|
any
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
Note
The receive case is a little bit complicated on ESP32. |
Firstly, when the data width is 8-bit or 24-bit, the received data will still align with two bytes or four bytes, which means that the valid data are put in the high 8 bits in every two bytes and high 24 bits in every four bytes. For example, the received data will be
0x5A00 when the data on the line is
0x5A in 8-bit width, and
0x0000 5A00 if the data on the line is
0x00 005A. Secondly, for the 8-bit or 16-bit mono case, the data in buffer is swapped every two data, so it may be necessary to manually swap the data back to the correct order.
|
|
slot mode
|
slot mask
|
left
|
right
|
left
|
right
|
left
|
right
|
left
|
right
|
mono
|
left
|
0x0001
|
0x0000
|
0x0002
|
0x0000
|
0x0003
|
0x0000
|
0x0004
|
0x0000
|
right
|
0x0000
|
0x0001
|
0x0000
|
0x0002
|
0x0000
|
0x0003
|
0x0000
|
0x0004
|
both
|
0x0001
|
0x0001
|
0x0002
|
0x0002
|
0x0003
|
0x0003
|
0x0004
|
0x0004
|
stereo
|
left
|
0x0001
|
0x0001
|
0x0003
|
0x0003
|
0x0005
|
0x0005
|
0x0007
|
0x0007
|
right
|
0x0002
|
0x0002
|
0x0004
|
0x0004
|
0x0006
|
0x0006
|
0x0008
|
0x0008
|
both
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
/* Allocate an I2S TX channel */
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
i2s_new_channel(&chan_cfg, &tx_handle, NULL);
/* Init the channel into PDM TX mode */
i2s_pdm_tx_config_t pdm_tx_cfg = |
When the data on the line (The PDM format on the line is transferred to PCM format for easier comprehension) is:
|
left
|
right
|
left
|
right
|
left
|
right
|
left
|
right
|
...
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
|
...
Here is the table of the data received in a
int16_t buffer with different
i2s_pdm_rx_slot_config_t::slot_mode and
i2s_pdm_rx_slot_config_t::slot_mask.
|
slot mode
|
slot mask
|
data 0
|
data 1
|
data 2
|
data 3
|
data 4
|
data 5
|
data 6
|
data 7
|
mono
|
left
|
0x0001
|
0x0003
|
0x0005
|
0x0007
|
0x0009
|
0x000b
|
0x000d
|
0x000f
|
right
|
0x0002
|
0x0004
|
0x0006
|
0x0008
|
0x000a
|
0x000c
|
0x000e
|
0x0010
|
stereo
|
both
|
0x0001
|
0x0002
|
0x0003
|
0x0004
|
0x0005
|
0x0006
|
0x0007
|
0x0008
#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
i2s_chan_handle_t rx_handle;
/* Allocate an I2S RX channel */
|
Here is an example of how to allocate a pair of full-duplex channels:
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
i2s_chan_handle_t rx_handle;
/* Allocate a pair of I2S channel */
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER);
/* Allocate for TX and RX channel at the same time, then they will work in full-duplex mode */
i2s_new_channel(&chan_cfg, &tx_handle, &rx_handle);
/* Set the configurations for BOTH TWO channels, since TX and RX channel have to be same in full-duplex mode * |
#include "driver/i2s_std.h"
#include "driver/gpio.h"
i2s_chan_handle_t tx_handle;
i2s_chan_handle_t rx_handle;
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER);
i2s_new_channel(&chan_cfg, &tx_handle, NULL);
i2s_std_config_t std_tx_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(48000),
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = GPIO_NUM_0,
.bclk = GPIO_NUM_4,
.ws = GPIO_NUM_5,
.dout = GPIO_NUM_18,
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = |
false,
.ws_inv = false,
},
},
};
/ * Initialize the channel */
i2s_channel_init_std_mode(tx_handle, &std_tx_cfg);
i2s_channel_enable(tx_handle);
/* RX channel will be registered on another I2S, if no other available I2S unit found
* it will return ESP_ERR_NOT_FOUND */
i2s_new_channel(&chan_cfg, NULL, &rx_handle);
i2s_std_config_t std_rx_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(16000),
.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = GPIO_NUM_6,
.ws = GPIO_NUM_7,
.dout = I2S_GPIO_UNUSED,
.din = GPIO_NUM_19,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = |
Application Notes
How to Prevent Data Lost
For applications that need a high frequency sample rate, the massive data throughput may cause data lost. Users can receive data lost event by registering the ISR callback function to receive the event queue:
static IRAM_ATTR bool i2s_rx_queue_overflow_callback(i2s_chan_handle_t handle, i2s_event_data_t *event, void *user_ctx) { // handle RX queue overflow event ... return false; } i2s_event_callbacks_t cbs = { .on_recv = NULL, .on_recv_q_ovf = i2s_rx_queue_overflow_callback, .on_sent = NULL, .on_send_q_ovf = NULL, }; TEST_ESP_OK(i2s_channel_register_event_callback(rx_handle, &cbs, NULL));
Please follow these steps to prevent data lost:
Determine the interrupt interval. Generally, when data lost happens, the bigger the interval, the better, which helps to reduce the interrupt times. This means
dma_frame_numshould be as big as possible while the DMA buffer size is below the maximum value of 4092. |
polling_cycle / interrupt_interval
Determine the receiving buffer size. The receiving buffer offered by users in
i2s_channel_readshould be able to take all the data in all DMA buffers, which means that it should be larger than the total size of all the DMA buffers:
recv_buffer_size > dma_desc_num * dma_buffer_size
For example, if there is an I2S application, and the known values are:
sample_rate = 144000 Hz
data_bit_width = 32 bits
slot_num = 2
polling_cycle = 10 ms
Then the parameters
dma_frame_num,
dma_desc_num, and
recv_buf_size can be calculated as follows:
|
3
recv_buffer_size > dma_desc_num * dma_buffer_size = 3 * 4092 = 12276 bytes
API Reference
Standard Mode
Header File
This header file can be included with:
#include "driver/i2s_std.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 i2s_channel_init_std_mode(i2s_chan_handle_t handle, const i2s_std_config_t *std_cfg)
Initialize I2S channel to standard mode.
Note
Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED.
- Parameters
handle -- [in] I2S channel handler
std_cfg -- [in] Configurations for standard mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro
I2S_STD_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro
I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG,
|
[in] Standard mode clock configuration, can be generated by
I2S_STD_CLK_DEFAULT_CONFIG
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_std_slot(i2s_chan_handle_t handle, const i2s_std_slot_config_t *slot_cfg)
Reconfigure the I2S slot for standard mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to standard mode, i.e.,
i2s_channel_init_std_modehas been called before reconfiguring
- Parameters
handle -- |
[in] Standard mode slot configuration, can be generated by
I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG,
I2S_STD_PCM_SLOT_DEFAULT_CONFIGand
I2S_STD_MSB_SLOT_DEFAULT_CONFIG.
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_NO_MEM No memory for DMA buffer
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not standard mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_std_gpio(i2s_chan_handle_t handle, const i2s_std_gpio_config_t *gpio_cfg)
Reconfigure the I2S GPIO for standard mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to standard mode, i.e.,
i2s_channel_init_std_modehas been called before reconfiguring
- Parameters
handle -- |
[in] Configurations for PDM RX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro
I2S_PDM_RX_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro
I2S_PDM_RX_SLOT_DEFAULT_CONFIG
-
- Returns
ESP_OK Initialize successfully
ESP_ERR_NO_MEM No memory for storing the channel information
ESP_ERR_INVALID_ARG NULL pointer or invalid configuration
ESP_ERR_INVALID_STATE This channel is not registered
-
-
esp_err_t i2s_channel_reconfig_pdm_rx_clock(i2s_chan_handle_t handle, const i2s_pdm_rx_clk_config_t *clk_cfg)
Reconfigure the I2S clock for PDM RX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM RX mode, i.e.,
i2s_channel_init_pdm_rx_modehas been called before reconfiguring
- Parameters
handle -- |
[in] PDM RX mode clock configuration, can be generated by
I2S_PDM_RX_CLK_DEFAULT_CONFIG
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_pdm_rx_slot(i2s_chan_handle_t handle, const i2s_pdm_rx_slot_config_t *slot_cfg)
Reconfigure the I2S slot for PDM RX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM RX mode, i.e.,
i2s_channel_init_pdm_rx_modehas been called before reconfiguring
- Parameters
handle -- |
[in] I2S RX channel handler
slot_cfg -- [in] PDM RX mode slot configuration, can be generated by
I2S_PDM_RX_SLOT_DEFAULT_CONFIG
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_NO_MEM No memory for DMA buffer
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_pdm_rx_gpio(i2s_chan_handle_t handle, const i2s_pdm_rx_gpio_config_t *gpio_cfg)
Reconfigure the I2S GPIO for PDM RX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM RX mode, i.e.,
i2s_channel_init_pdm_rx_modehas been called before reconfiguring
- Parameters
handle -- |
[in] PDM RX mode GPIO configuration, specified by user
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_init_pdm_tx_mode(i2s_chan_handle_t handle, const i2s_pdm_tx_config_t *pdm_tx_cfg)
Initialize I2S channel to PDM TX mode.
Note
Only allowed to be called when the channel state is REGISTERED, (i.e., channel has been allocated, but not initialized) and the state will be updated to READY if initialization success, otherwise the state will return to REGISTERED.
- Parameters
handle -- |
[in] Configurations for PDM TX mode, including clock, slot and GPIO The clock configuration can be generated by the helper macro
I2S_PDM_TX_CLK_DEFAULT_CONFIGThe slot configuration can be generated by the helper macro
I2S_PDM_TX_SLOT_DEFAULT_CONFIG
-
- Returns
ESP_OK Initialize successfully
ESP_ERR_NO_MEM No memory for storing the channel information
ESP_ERR_INVALID_ARG NULL pointer or invalid configuration
ESP_ERR_INVALID_STATE This channel is not registered
-
-
esp_err_t i2s_channel_reconfig_pdm_tx_clock(i2s_chan_handle_t handle, const i2s_pdm_tx_clk_config_t *clk_cfg)
Reconfigure the I2S clock for PDM TX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM TX mode, i.e.,
i2s_channel_init_pdm_tx_modehas been called before reconfiguring
- Parameters
handle -- |
[in] PDM TX mode clock configuration, can be generated by
I2S_PDM_TX_CLK_DEFAULT_CONFIG
-
- Returns
ESP_OK Set clock successfully
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_pdm_tx_slot(i2s_chan_handle_t handle, const i2s_pdm_tx_slot_config_t *slot_cfg)
Reconfigure the I2S slot for PDM TX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM TX mode, i.e.,
i2s_channel_init_pdm_tx_modehas been called before reconfiguring
- Parameters
handle -- |
No memory for DMA buffer
ESP_ERR_INVALID_ARG NULL pointer, invalid configuration or not PDM mode
ESP_ERR_INVALID_STATE This channel is not initialized or not stopped
-
-
esp_err_t i2s_channel_reconfig_pdm_tx_gpio(i2s_chan_handle_t handle, const i2s_pdm_tx_gpio_config_t *gpio_cfg)
Reconfigure the I2S GPIO for PDM TX mode.
Note
Only allowed to be called when the channel state is READY, i.e., channel has been initialized, but not started this function won't change the state.
i2s_channel_disableshould be called before calling this function if I2S has started.
Note
The input channel handle has to be initialized to PDM TX mode, i.e.,
i2s_channel_init_pdm_tx_modehas been called before reconfiguring
- Parameters
handle -- |
If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted.
- Parameters
rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear)
-
-
I2S_PDM_TX_CLK_DAC_DEFAULT_CONFIG(rate)
I2S default PDM TX clock configuration for DAC line mode.
Note
TX PDM can only be set to the following two up-sampling rate configurations: 1: fp = 960, fs = sample_rate_hz / 100, in this case, Fpdm = 128*48000 2: fp = 960, fs = 480, in this case, Fpdm = 128*Fpcm = 128*sample_rate_hz |
If the PDM receiver do not care the PDM serial clock, it's recommended set Fpdm = 128*48000. Otherwise, the second configuration should be adopted.
Note
The noise might be different with different configurations, this macro provides a set of configurations that have relatively high SNR (Signal Noise Ratio), you can also adjust them to fit your case.
- Parameters
rate -- sample rate (not suggest to exceed 48000 Hz, otherwise more glitches and noise may appear)
-
I2S Driver
Header File
This header file can be included with:
#include "driver/i2s_common.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 i2s_new_channel(const i2s_chan_config_t *chan_cfg, i2s_chan_handle_t *ret_tx_handle, i2s_chan_handle_t *ret_rx_handle)
Allocate new I2S channel(s)
Note
The new created I2S channel handle will be REGISTERED state after it is allocated successfully.
Note
When the port id in channel configuration is I2S_NUM_AUTO, driver will allocate I2S port automatically on one of the I2S controller, otherwise driver will try to allocate the new channel on the selected port.
|
and rx_handle are not NULL, it means this I2S controller will work at full-duplex mode, the RX and TX channels will be allocated on a same I2S port in this case. Note that some configurations of TX/RX channel are shared on ESP32 and ESP32S2, so please make sure they are working at same condition and under same status(start/stop). Currently, full-duplex mode can't guarantee TX/RX channels write/read synchronously, they can only share the clock signals for now.
Note
If tx_handle OR rx_handle is NULL, it means this I2S controller will work at simplex mode. For ESP32 and ESP32S2, the whole I2S controller (i.e. both RX and TX channel) will be occupied, even if only one of RX or TX channel is registered. For the other targets, another channel on this controller will still available.
|
This channel has not stated
-
-
esp_err_t i2s_channel_preload_data(i2s_chan_handle_t tx_handle, const void *src, size_t size, size_t *bytes_loaded)
Preload the data into TX DMA buffer.
Note
Only allowed to be called when the channel state is READY, (i.e., channel has been initialized, but not started)
Note
As the initial DMA buffer has no data inside, it will transmit the empty buffer after enabled the channel, this function is used to preload the data into the DMA buffer, so that the valid data can be transmitted immediately after the channel is enabled.
Note
This function can be called multiple times before enabling the channel, the buffer that loaded later will be concatenated behind the former loaded buffer. But when all the DMA buffers have been loaded, no more data can be preload then, please check the
bytes_loadedparameter to see how many bytes are loaded successfully, when the
bytes_loadedis smaller than the
size, it means the DMA buffers are full.
- Parameters
tx_handle -- |
[in] I2S TX channel handler
src -- [in] The pointer of the source buffer to be loaded
size -- [in] The source buffer size
bytes_loaded -- [out] The bytes that successfully been loaded into the TX DMA buffer
-
- Returns
ESP_OK Load data successful
ESP_ERR_INVALID_ARG NULL pointer or not TX direction
ESP_ERR_INVALID_STATE This channel has not stated
-
-
esp_err_t i2s_channel_write(i2s_chan_handle_t handle, const void *src, size_t size, size_t *bytes_written, uint32_t timeout_ms)
I2S write data.
Note
Only allowed to be called when the channel state is RUNNING, (i.e., TX channel has been started and is not writing now) but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line.
- Parameters
handle -- |
[out] Byte number that actually be sent, can be NULL if not needed
timeout_ms -- [in] Max block time
-
- Returns
ESP_OK Write successfully
ESP_ERR_INVALID_ARG NULL pointer or this handle is not TX handle
ESP_ERR_TIMEOUT Writing timeout, no writing event received from ISR within ticks_to_wait
ESP_ERR_INVALID_STATE I2S is not ready to write
-
-
esp_err_t i2s_channel_read(i2s_chan_handle_t handle, void *dest, size_t size, size_t *bytes_read, uint32_t timeout_ms)
I2S read data.
Note
Only allowed to be called when the channel state is RUNNING but the RUNNING only stands for the software state, it doesn't mean there is no the signal transporting on line.
- Parameters
handle -- [in] I2S channel handler
dest -- [in] The pointer of receiving data buffer
size -- [in] Max data buffer length
bytes_read -- [out] Byte number that actually be read, can be NULL if not needed
timeout_ms -- [in] Max block time
-
- Returns
ESP_OK Read successfully
ESP_ERR_INVALID_ARG NULL pointer or this handle is not RX handle
ESP_ERR_TIMEOUT Reading timeout, no reading event received from ISR within ticks_to_wait
ESP_ERR_INVALID_STATE I2S is not ready to read
-
-
esp_err_t i2s_channel_register_event_callback(i2s_chan_handle_t handle, const i2s_event_callbacks_t *callbacks, void *user_data)
Set event callbacks for I2S channel.
Note
Only allowed to be called when the channel state is REGISTERED / READY, (i.e., before channel starts)
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_I2S_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 or internal RAM as well.
- Parameters
handle -- |
[in] I2S channel handle, created from
i2s_new_channel()
- Param event
[in] I2S event data
- Param user_ctx
[in] User registered context, passed from
i2s_channel_register_event_callback()
- Return
Whether a high priority task has been waken up by this callback function
Enumerations
-
enum i2s_port_t
I2S controller port number, the max port number is (SOC_I2S_NUM -1).
Values:
-
enumerator I2S_NUM_0
I2S controller port 0
-
enumerator I2S_NUM_1
I2S controller port 1
-
enumerator I2S_NUM_AUTO
Select whichever port is available
- enumerator I2S_NUM_0
-
enum i2s_comm_mode_t
I2S controller communication mode.
Values:
-
enumerator I2S_COMM_MODE_STD
I2S controller using standard communication mode, support Philips/MSB/PCM format
-
enumerator I2S_COMM_MODE_PDM
I2S controller using PDM communication mode, support PDM output or input
-
enumerator I2S_COMM_MODE_NONE
Unspecified I2S controller mode
- enumerator I2S_COMM_MODE_STD
-
enum i2s_mclk_multiple_t
The multiple of MCLK to sample rate.
Values:
-
enumerator I2S_MCLK_MULTIPLE_128
MCLK = sample_rate * 128
-
enumerator I2S_MCLK_MULTIPLE_256
MCLK = sample_rate * 256
-
enumerator I2S_MCLK_MULTIPLE_384
MCLK = sample_rate * 384
-
enumerator I2S_MCLK_MULTIPLE_512
MCLK = sample_rate * 512
- enumerator I2S_MCLK_MULTIPLE_128
Header File
This header file can be included with:
#include "hal/i2s_types.h"
Type Definitions
-
typedef soc_periph_i2s_clk_src_t i2s_clock_src_t
I2S clock source
Enumerations
-
enum i2s_slot_mode_t
I2S channel slot mode.
|
LCD
Introduction
ESP chips can generate various kinds of timings that needed by common LCDs on the market, like SPI LCD, I80 LCD (a.k.a Intel 8080 parallel LCD), RGB/SRGB LCD, I2C LCD, etc. The
esp_lcd component is officially to support those LCDs with a group of universal APIs across chips.
Functional Overview
In
esp_lcd, an LCD panel is represented by
esp_lcd_panel_handle_t, which plays the role of an abstract frame buffer, regardless of the frame memory is allocated inside ESP chip or in external LCD controller. Based on the location of the frame buffer and the hardware connection interface, the LCD panel drivers are mainly grouped into the following categories:
Controller based LCD driver involves multiple steps to get a panel handle, like bus allocation, IO device registration and controller driver install. The frame buffer is located in the controller's internal GRAM (Graphical RAM). ESP-IDF provides only a limited number of LCD controller drivers out of the box (e.g., ST7789, SSD1306), More Controller Based LCD Drivers are maintained in the Espressif Component Registry.
SPI Interfaced LCD describes the steps to install the SPI LCD IO driver and then get the panel handle.
I2C Interfaced LCD describes the steps to install the I2C LCD IO driver and then get the panel handle.
I80 Interfaced LCD describes the steps to install the I80 LCD IO driver and then get the panel handle.
LCD Panel IO Operations - provides a set of APIs to operate the LCD panel, like turning on/off the display, setting the orientation, etc. These operations are common for either controller-based LCD panel driver or RGB LCD panel driver.
SPI Interfaced LCD
Create an SPI bus. Please refer to SPI Master API doc for more details.
|
spi_bus_config_t buscfg = { .sclk_io_num = EXAMPLE_PIN_NUM_SCLK, .mosi_io_num = EXAMPLE_PIN_NUM_MOSI, .miso_io_num = EXAMPLE_PIN_NUM_MISO, .quadwp_io_num = -1, // Quad SPI LCD driver is not yet supported .quadhd_io_num = -1, // Quad SPI LCD driver is not yet supported .max_transfer_sz = EXAMPLE_LCD_H_RES * 80 * sizeof(uint16_t), // transfer 80 lines of pixels (assume pixel is RGB565) at most in one SPI transaction }; ESP_ERROR_CHECK(spi_bus_initialize(LCD_HOST, &buscfg, SPI_DMA_CH_AUTO)); // Enable the DMA feature
Allocate an LCD IO device handle from the SPI bus. In this step, you need to provide the following information:
esp_lcd_panel_io_spi_config_t::dc_gpio_num: Sets the gpio number for the DC signal line (some LCD calls this
RSline). The LCD driver uses this GPIO to switch between sending command and sending data.
esp_lcd_panel_io_spi_config_t::cs_gpio_num: Sets the gpio number for the CS signal line. The LCD driver uses this GPIO to select the LCD chip. If the SPI bus only has one device attached (i.e., this LCD), you can set the gpio number to
-1to occupy the bus exclusively.
esp_lcd_panel_io_spi_config_t::pclk_hzsets the frequency of the pixel clock, in Hz. The value should not exceed the range recommended in the LCD spec.
esp_lcd_panel_io_spi_config_t::spi_modesets the SPI mode. The LCD driver uses this mode to communicate with the LCD. For the meaning of the SPI mode, please refer to the SPI Master API doc.
esp_lcd_panel_io_spi_config_t::lcd_cmd_bitsand
esp_lcd_panel_io_spi_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance.
esp_lcd_panel_io_spi_config_t::trans_queue_depthsets the depth of the SPI transaction queue. A bigger value means more transactions can be queued up, but it also consumes more memory.
|
esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_spi_config_t io_config = { .dc_gpio_num = EXAMPLE_PIN_NUM_LCD_DC, .cs_gpio_num = EXAMPLE_PIN_NUM_LCD_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, .spi_mode = 0, .trans_queue_depth = 10, }; // Attach the LCD to the SPI bus ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_HOST, &io_config, &io_handle));
-
Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the SPI IO device handle that allocated in the last step, and some panel specific configurations:
esp_lcd_panel_dev_config_t::reset_gpio_numsets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to
-1.
esp_lcd_panel_dev_config_t::rgb_ele_ordersets the R-G-B element order of each color data.
esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip.
esp_lcd_panel_dev_config_t::data_endianspecifies the data endian to be transmitted to the screen. No need to specify for color data within 1 byte, like RGB232. For drivers that do not support specifying data endian, this field would be ignored.
|
i2c_master_bus_handle_t i2c_bus = NULL; i2c_master_bus_config_t bus_config = { .clk_source = I2C_CLK_SRC_DEFAULT, .glitch_ignore_cnt = 7, .i2c_port = I2C_BUS_PORT, .sda_io_num = EXAMPLE_PIN_NUM_SDA, .scl_io_num = EXAMPLE_PIN_NUM_SCL, .flags.enable_internal_pullup = true, }; ESP_ERROR_CHECK(i2c_new_master_bus(&bus_config, &i2c_bus));
Allocate an LCD IO device handle from the I2C bus. In this step, you need to provide the following information:
esp_lcd_panel_io_i2c_config_t::dev_addrsets the I2C device address of the LCD controller chip. The LCD driver uses this address to communicate with the LCD controller chip.
esp_lcd_panel_io_i2c_config_t::scl_speed_hzsets the I2C clock frequency in Hz. The value should not exceed the range recommended in the LCD spec.
esp_lcd_panel_io_i2c_config_t::lcd_cmd_bitsand
esp_lcd_panel_io_i2c_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance.
|
esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i2c_config_t io_config = { .dev_addr = EXAMPLE_I2C_HW_ADDR, .scl_speed_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .control_phase_bytes = 1, // refer to LCD spec .dc_bit_offset = 6, // refer to LCD spec .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_CMD_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i2c(i2c_bus, &io_config, &io_handle));
-
Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I2C IO device handle that allocated in the last step, and some panel specific configurations:
esp_lcd_panel_dev_config_t::reset_gpio_numsets the LCD's hardware reset GPIO number. If the LCD does not have a hardware reset pin, set this to
-1.
esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip.
|
You need to set up the following parameters for an Intel 8080 parallel bus:
esp_lcd_i80_bus_config_t::clk_srcsets the clock source of the I80 bus. Note, the default clock source may be different between ESP targets.
esp_lcd_i80_bus_config_t::wr_gpio_numsets the GPIO number of the pixel clock (also referred as
WRin some LCD spec)
esp_lcd_i80_bus_config_t::dc_gpio_numsets the GPIO number of the data/command select pin (also referred as
RSin some LCD spec)
esp_lcd_i80_bus_config_t::bus_widthsets the bit width of the data bus (only support
8or
16)
esp_lcd_i80_bus_config_t::data_gpio_numsis the array of the GPIO number of the data bus. The number of GPIOs should be equal to the
esp_lcd_i80_bus_config_t::bus_widthvalue.
esp_lcd_i80_bus_config_t::max_transfer_bytessets the maximum number of bytes that can be transferred in one transaction.
esp_lcd_i80_bus_handle_t i80_bus = NULL; esp_lcd_i80_bus_config_t bus_config = { .clk_src = LCD_CLK_SRC_DEFAULT, .dc_gpio_num = EXAMPLE_PIN_NUM_DC, .wr_gpio_num = EXAMPLE_PIN_NUM_PCLK, .data_gpio_nums = { EXAMPLE_PIN_NUM_DATA0, EXAMPLE_PIN_NUM_DATA1, EXAMPLE_PIN_NUM_DATA2, EXAMPLE_PIN_NUM_DATA3, EXAMPLE_PIN_NUM_DATA4, EXAMPLE_PIN_NUM_DATA5, EXAMPLE_PIN_NUM_DATA6, EXAMPLE_PIN_NUM_DATA7, }, .bus_width = 8, .max_transfer_bytes = EXAMPLE_LCD_H_RES * 100 * sizeof(uint16_t), // transfer 100 lines of pixels (assume pixel is RGB565) at most in one transaction .psram_trans_align = EXAMPLE_PSRAM_DATA_ALIGNMENT, .sram_trans_align = 4, }; ESP_ERROR_CHECK(esp_lcd_new_i80_bus(&bus_config, &i80_bus));
-
Allocate an LCD IO device handle from the I80 bus. In this step, you need to provide the following information:
esp_lcd_panel_io_i80_config_t::cs_gpio_numsets the GPIO number of the chip select pin.
esp_lcd_panel_io_i80_config_t::pclk_hzsets the pixel clock frequency in Hz. Higher pixel clock frequency results in higher refresh rate, but may cause flickering if the DMA bandwidth is not sufficient or the LCD controller chip does not support high pixel clock frequency.
esp_lcd_panel_io_i80_config_t::lcd_cmd_bitsand
esp_lcd_panel_io_i80_config_t::lcd_param_bitsset the bit width of the command and parameter that recognized by the LCD controller chip. This is chip specific, you should refer to your LCD spec in advance.
esp_lcd_panel_io_i80_config_t::trans_queue_depthsets the maximum number of transactions that can be queued in the LCD IO device. A bigger value means more transactions can be queued up, but it also consumes more memory.
|
esp_lcd_panel_io_handle_t io_handle = NULL; esp_lcd_panel_io_i80_config_t io_config = { .cs_gpio_num = EXAMPLE_PIN_NUM_CS, .pclk_hz = EXAMPLE_LCD_PIXEL_CLOCK_HZ, .trans_queue_depth = 10, .dc_levels = { .dc_idle_level = 0, .dc_cmd_level = 0, .dc_dummy_level = 0, .dc_data_level = 1, }, .lcd_cmd_bits = EXAMPLE_LCD_CMD_BITS, .lcd_param_bits = EXAMPLE_LCD_PARAM_BITS, }; ESP_ERROR_CHECK(esp_lcd_new_panel_io_i80(i80_bus, &io_config, &io_handle));
-
Install the LCD controller driver. The LCD controller driver is responsible for sending the commands and parameters to the LCD controller chip. In this step, you need to specify the I80 IO device handle that allocated in the last step, and some panel specific configurations:
esp_lcd_panel_dev_config_t::bits_per_pixelsets the bit width of the pixel color data. The LCD driver uses this value to calculate the number of bytes to send to the LCD controller chip.
esp_lcd_panel_dev_config_t::reset_gpio_numsets the GPIO number of the reset pin. If the LCD controller chip does not have a reset pin, you can set this value to
-1.
esp_lcd_panel_dev_config_t::rgb_ele_ordersets the color order the pixel color data.
|
To declare that your component depends on
esp_lcd, add the following to your CMakeLists.txt:
REQUIRES esp_lcd
or
PRIV_REQUIRES esp_lcd
Type Definitions
-
typedef struct esp_lcd_panel_io_t *esp_lcd_panel_io_handle_t
Type of LCD panel IO handle
-
typedef struct esp_lcd_panel_t *esp_lcd_panel_handle_t
Type of LCD panel handle
Header File
This header file can be included with:
#include "esp_lcd_panel_io.h"
This header file is a part of the API provided by the
esp_lcdcomponent. To declare that your component depends on
esp_lcd, add the following to your CMakeLists.txt:
REQUIRES esp_lcd
or
PRIV_REQUIRES |
Transmit LCD command and receive corresponding parameters.
Note
Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by
esp_lcd_panel_io_tx_color()are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s).
- Parameters
io -- [in] LCD panel IO handle, which is created by other factory API like
esp_lcd_new_panel_io_spi()
lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed
param -- [out] Buffer for the command data
param_size -- [in] Size of
parambuffer
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_NOT_SUPPORTED if read is not supported by transport
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_io_tx_param(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *param, size_t param_size )
Transmit LCD command and corresponding parameters.
|
Note
Commands sent by this function are short, so they are sent using polling transactions. The function does not return before the command transfer is completed. If any queued transactions sent by
esp_lcd_panel_io_tx_color()are still pending when this function is called, this function will wait until they are finished and the queue is empty before sending the command(s).
- Parameters
io -- [in] LCD panel IO handle, which is created by other factory API like
esp_lcd_new_panel_io_spi()
lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed
param -- [in] Buffer that holds the command specific parameters, set to NULL if no parameter is needed for the command
param_size -- [in] Size of
paramin memory, in bytes, set to zero if no parameter is needed for the command
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_io_tx_color(esp_lcd_panel_io_handle_t io, int lcd_cmd, const void *color, size_t color_size)
Transmit LCD RGB data.
Note
This function will package the command and RGB data into a transaction, and push into a queue. The real transmission is performed in the background (DMA+interrupt). The caller should take care of the lifecycle of the
colorbuffer. Recycling of color buffer should be done in the callback
on_color_trans_done().
- Parameters
io -- [in] LCD panel IO handle, which is created by factory API like
esp_lcd_new_panel_io_spi()
lcd_cmd -- [in] The specific LCD command, set to -1 if no command needed
color -- [in] Buffer that holds the RGB color data
color_size -- [in] Size of
colorin memory, in bytes
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_io_del(esp_lcd_panel_io_handle_t io)
Destroy LCD panel IO handle (deinitialize panel and free all corresponding resource)
- Parameters
io -- [in] LCD panel IO handle, which is created by factory API like
esp_lcd_new_panel_io_spi()
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_io_register_event_callbacks(esp_lcd_panel_io_handle_t io, const esp_lcd_panel_io_callbacks_t *cbs, void *user_ctx)
Register LCD panel IO callbacks.
- Parameters
io -- [in] LCD panel IO handle, which is created by factory API like
esp_lcd_new_panel_io_spi()
cbs -- [in] structure with all LCD panel IO callbacks
user_ctx -- [in] User private data, passed directly to callback's user_ctx
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_OK on success
-
-
esp_err_t esp_lcd_new_panel_io_spi(esp_lcd_spi_bus_handle_t bus, const esp_lcd_panel_io_spi_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io)
Create LCD panel IO handle, for SPI interface.
- Parameters
bus -- [in] SPI bus handle
io_config -- [in] IO configuration, for SPI interface
ret_io -- [out] Returned IO handle
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_NO_MEM |
[in] Bus configuration
ret_bus -- [out] Returned bus handle
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_NO_MEM if out of memory
ESP_ERR_NOT_FOUND if no free bus is available
ESP_OK on success
-
-
esp_err_t esp_lcd_del_i80_bus(esp_lcd_i80_bus_handle_t bus)
Destroy Intel 8080 bus handle.
- Parameters
bus -- [in] Intel 8080 bus handle, created by
esp_lcd_new_i80_bus()
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_INVALID_STATE if there still be some device attached to the bus
ESP_OK on success
-
-
esp_err_t esp_lcd_new_panel_io_i80(esp_lcd_i80_bus_handle_t bus, const esp_lcd_panel_io_i80_config_t *io_config, esp_lcd_panel_io_handle_t *ret_io)
Create LCD panel IO, for Intel 8080 interface.
- Parameters
bus -- [in] Intel 8080 bus handle, created by
esp_lcd_new_i80_bus()
io_config -- [in] IO configuration, for i80 interface
ret_io -- |
[in] I2C bus handle
io_config -- [in] IO configuration, for I2C interface
ret_io -- [out] Returned IO handle
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_NO_MEM if out of memory
ESP_OK on success
-
Type Definitions
-
typedef void *esp_lcd_spi_bus_handle_t
Type of LCD SPI bus handle
-
typedef uint32_t esp_lcd_i2c_bus_handle_t
Type of LCD I2C bus handle
-
typedef struct esp_lcd_i80_bus_t *esp_lcd_i80_bus_handle_t
Type of LCD intel 8080 bus handle
-
typedef bool (*esp_lcd_panel_io_color_trans_done_cb_t)(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_io_event_data_t *edata, void *user_ctx)
Declare the prototype of the function that will be invoked when panel IO finishes transferring color data.
- Param panel_io
[in] LCD panel IO handle, which is created by factory API like
esp_lcd_new_panel_io_spi()
- Param edata
[in] Panel IO event data, fed by driver
- Param user_ctx
[in] User data, passed from
esp_lcd_panel_io_xxx_config_t
- Return
Whether a high priority task has been waken up by this function
Header File
This header file can be included with:
#include "esp_lcd_panel_ops.h"
This header file is a part of the API provided by the
esp_lcdcomponent. To declare that your component depends on
esp_lcd, add the following to your CMakeLists.txt:
REQUIRES esp_lcd
or
PRIV_REQUIRES |
esp_lcd
Functions
-
esp_err_t esp_lcd_panel_reset(esp_lcd_panel_handle_t panel)
Reset LCD panel.
Note
Panel reset must be called before attempting to initialize the panel using
esp_lcd_panel_init().
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_init(esp_lcd_panel_handle_t panel)
Initialize LCD panel.
Note
Before calling this function, make sure the LCD panel has finished the
resetstage by
esp_lcd_panel_reset().
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_del(esp_lcd_panel_handle_t panel)
Deinitialize the LCD panel.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_draw_bitmap(esp_lcd_panel_handle_t panel, int x_start, int y_start, int x_end, int y_end, const void *color_data)
Draw bitmap on LCD panel.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
x_start -- [in] Start index on x-axis (x_start included)
y_start -- [in] Start index on y-axis (y_start included)
|
[in] RGB color data that will be dumped to the specific window range
-
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_mirror(esp_lcd_panel_handle_t panel, bool mirror_x, bool mirror_y)
Mirror the LCD panel on specific axis.
Note
Combined with
esp_lcd_panel_swap_xy(), one can realize screen rotation
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
mirror_x -- [in] Whether the panel will be mirrored about the x axis
mirror_y -- [in] Whether the panel will be mirrored about the y axis
-
- Returns
ESP_OK on success
ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
-
-
esp_err_t esp_lcd_panel_swap_xy(esp_lcd_panel_handle_t panel, bool swap_axes)
Swap/Exchange x and y axis.
Note
Combined with
esp_lcd_panel_mirror(), one can realize screen rotation
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
swap_axes -- [in] Whether to swap the x and y axis
-
- Returns
ESP_OK on success
ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
-
-
esp_err_t esp_lcd_panel_set_gap(esp_lcd_panel_handle_t panel, int x_gap, int y_gap)
Set extra gap in x and y axis.
The gap is the space (in pixels) between the left/top sides of the LCD panel and the first row/column respectively of the actual contents displayed.
Note
Setting a gap is useful when positioning or centering a frame that is smaller than the LCD.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
x_gap -- [in] |
Extra gap on y axis, in pixels
-
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_invert_color(esp_lcd_panel_handle_t panel, bool invert_color_data)
Invert the color (bit-wise invert the color data line)
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
invert_color_data -- [in] Whether to invert the color data
-
- Returns
ESP_OK on success
-
-
esp_err_t esp_lcd_panel_disp_on_off(esp_lcd_panel_handle_t panel, bool on_off)
Turn on or off the display.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
on_off -- [in] True to turns on display, False to turns off display
-
- Returns
ESP_OK on success
ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
-
-
esp_err_t esp_lcd_panel_disp_off(esp_lcd_panel_handle_t panel, bool off)
Turn off the display.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
off -- [in] Whether to turn off the screen
-
- Returns
ESP_OK on success
ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
-
-
esp_err_t esp_lcd_panel_disp_sleep(esp_lcd_panel_handle_t panel, bool sleep)
Enter or exit sleep mode.
- Parameters
panel -- [in] LCD panel handle, which is created by other factory API like
esp_lcd_new_panel_st7789()
sleep -- [in] True to enter sleep mode, False to wake up
-
- Returns
ESP_OK on success
ESP_ERR_NOT_SUPPORTED if this function is not supported by the panel
-
Header File
This header file can be included with:
#include "esp_lcd_panel_rgb.h"
This header file is a part of the API provided by the
esp_lcdcomponent. To declare that your component depends on
esp_lcd, add the following to your CMakeLists.txt:
REQUIRES esp_lcd
or
PRIV_REQUIRES esp_lcd
Header File
This header file can be included with:
#include "esp_lcd_panel_vendor.h"
This header file is a part of the API provided by the
esp_lcdcomponent. To declare that your component depends on
esp_lcd, add the following to your CMakeLists.txt:
REQUIRES esp_lcd
or
PRIV_REQUIRES |
[in] LCD panel IO handle
panel_dev_config -- [in] general panel device configuration
ret_panel -- [out] Returned LCD panel handle
-
- Returns
ESP_ERR_INVALID_ARG if parameter is invalid
ESP_ERR_NO_MEM if out of memory
ESP_OK on success
-
Structures
-
struct esp_lcd_panel_dev_config_t
Configuration structure for panel device.
Public Members
-
int reset_gpio_num
GPIO used to reset the LCD panel, set to -1 if it's not used
-
lcd_rgb_element_order_t color_space
- Deprecated:
Set RGB color space, please use rgb_ele_order instead
-
lcd_rgb_element_order_t rgb_endian
- Deprecated:
Set RGB data endian, please use rgb_ele_order instead
-
lcd_rgb_element_order_t rgb_ele_order
Set RGB element order, RGB or BGR
-
lcd_rgb_data_endian_t data_endian
Set the data endian for color data larger than 1 byte
-
unsigned int bits_per_pixel
Color depth, in bpp
-
unsigned int reset_active_high
Setting this if the panel reset is high level active
-
struct esp_lcd_panel_dev_config_t::[anonymous] flags
LCD panel config flags
-
void *vendor_config
vendor specific configuration, optional, left as NULL if not used
- int reset_gpio_num |
LED Control (LEDC)
Introduction
The LED control (LEDC) peripheral is primarily designed to control the intensity of LEDs, although it can also be used to generate PWM signals for other purposes. It has 8 channels which can generate independent waveforms that can be used, for example, to drive RGB LED devices.
LEDC channels are divided into two groups of 8 channels each. One group of LEDC channels operates in high speed mode. This mode is implemented in hardware and offers automatic and glitch-free changing of the PWM duty cycle. The other group of channels operate in low speed mode, the PWM duty cycle must be changed by the driver in software. Each group of channels is also able to use different clock sources.
The PWM controller can automatically increase or decrease the duty cycle gradually, allowing for fades without any processor interference.
Functionality Overview
Setting up a channel of the LEDC in either high or low speed mode is done in three steps:
Timer Configuration by specifying the PWM signal's frequency and duty cycle resolution.
Channel Configuration by associating it with the timer and GPIO to output the PWM signal.
Change PWM Signal that drives the output in order to change LED's intensity. This can be done under the full control of software or with hardware fading functions.
As an optional step, it is also possible to set up an interrupt on fade end.
|
For an initial setup, it is recommended to configure for the timers first (by calling
ledc_timer_config()), and then for the channels (by calling
ledc_channel_config()). This ensures the PWM frequency is at the desired value since the appearance of the PWM signal from the IO pad.
Timer Configuration
Setting the timer is done by calling the function
ledc_timer_config() and passing the data structure
ledc_timer_config_t that contains the following configuration settings:
Speed mode
ledc_mode_t
Timer number
ledc_timer_t
PWM signal frequency in Hz
Resolution of PWM duty
Source clock
ledc_clk_cfg_t
The frequency and the duty resolution are interdependent. The higher the PWM frequency, the lower the duty resolution which is available, and vice versa. This relationship might be important if you are planning to use this API for purposes other than changing the intensity of LEDs. For more details, see Section Supported Range of Frequency and Duty Resolutions.
The source clock can also limit the PWM frequency. The higher the source clock frequency, the higher the maximum PWM frequency can be configured.
|
This ensures the accuracy of output PWM signal frequency.
The LEDC driver offers a helper function
ledc_find_suitable_duty_resolution() to find the maximum possible resolution for the timer, given the source clock frequency and the desired PWM signal frequency.
When a timer is no longer needed by any channel, it can be deconfigured by calling the same function
ledc_timer_config(). The configuration structure
ledc_timer_config_t passes in should be:
ledc_timer_config_t::speed_modeThe speed mode of the timer which wants to be deconfigured belongs to (
ledc_mode_t)
ledc_timer_config_t::timer_numThe ID of the timers which wants to be deconfigured (
ledc_timer_t)
ledc_timer_config_t::deconfigureSet this to true so that the timer specified can be deconfigured
Channel Configuration
When the timer is set up, configure the desired channel (one out of
ledc_channel_t). This is done by calling the function
ledc_channel_config().
Similar to the timer configuration, the channel setup function should be passed a structure
ledc_channel_config_t that contains the channel's configuration parameters.
At this point, the channel should start operating and generating the PWM signal on the selected GPIO, as configured in
ledc_channel_config_t, with the frequency specified in the timer settings and the given duty cycle. The channel operation (signal generation) can be suspended at any time by calling the function
ledc_stop().
Change PWM Signal
Once the channel starts operating and generating the PWM signal with the constant duty cycle and frequency, there are a couple of ways to change this signal. When driving LEDs, primarily the duty cycle is changed to vary the light intensity.
The following two sections describe how to change the duty cycle using software and hardware fading. If required, the signal's frequency can also be changed; it is covered in Section Change PWM Frequency.
Change PWM Duty Cycle Using Software
To set the duty cycle, use the dedicated function
ledc_set_duty(). After that, call
ledc_update_duty() to activate the changes. To check the currently set value, use the corresponding
_get_ function
ledc_get_duty().
Another way to set the duty cycle, as well as some other channel parameters, is by calling
ledc_channel_config() covered in Section Channel Configuration.
The range of the duty cycle values passed to functions depends on selected
duty_resolution and should be from
0 to
(2 ** duty_resolution). For example, if the selected duty resolution is 10, then the duty cycle values can range from 0 to 1024. |
Supported Range of Frequency and Duty Resolutions
The LED PWM Controller is designed primarily to drive LEDs. It provides a large flexibility of PWM duty cycle settings. For instance, the PWM frequency of 5 kHz can have the maximum duty resolution of 13 bits. This means that the duty can be set anywhere from 0 to 100% with a resolution of ~ 0.012% (2 ** 13 = 8192 discrete levels of the LED intensity). Note, however, that these parameters depend on the clock signal clocking the LED PWM Controller timer which in turn clocks the channel (see timer configuration and the ESP32 Technical Reference Manual > LED PWM Controller (LEDC) |
The LEDC can be used for generating signals at much higher frequencies that are sufficient enough to clock other devices, e.g., a digital camera module. In this case, the maximum available frequency is 40 MHz with duty resolution of 1 bit. This means that the duty cycle is fixed at 50% and cannot be adjusted.
The LEDC API is designed to report an error when trying to set a frequency and a duty resolution that exceed the range of LEDC's hardware. For example, an attempt to set the frequency to 20 MHz and the duty resolution to 3 bits results in the following error reported on a serial monitor:
E (196) ledc: requested frequency and duty resolution cannot be achieved, try reducing freq_hz or duty_resolution. div_param=128
In such a situation, either the duty resolution or the frequency must be reduced. |
For example, setting the duty resolution to 2 resolves this issue and makes it possible to set the duty cycle at 25% steps, i.e., at 25%, 50% or 75%.
The LEDC driver also captures and reports attempts to configure frequency/duty resolution combinations that are below the supported minimum, e.g.,:
E (196) ledc: requested frequency and duty resolution cannot be achieved, try increasing freq_hz or duty_resolution. div_param=128000000
The duty resolution is normally set using
ledc_timer_bit_t. This enumeration covers the range from 10 to 15 bits. If a smaller duty resolution is required (from 10 down to 1), enter the equivalent numeric values directly.
|
Application Example
The LEDC basic example: peripherals/ledc/ledc_basic.
The LEDC change duty cycle and fading control example: peripherals/ledc/ledc_fade.
API Reference
Header File
This header file can be included with:
#include "driver/ledc.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 ledc_channel_config(const ledc_channel_config_t *ledc_conf)
LEDC channel configuration Configure LEDC channel with the given channel/output gpio_num/interrupt/source timer/frequency(Hz)/LEDC duty.
- Parameters
ledc_conf -- Pointer of LEDC channel configure struct
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
uint32_t ledc_find_suitable_duty_resolution(uint32_t src_clk_freq, uint32_t timer_freq)
Helper function to find the maximum possible duty resolution in bits for ledc_timer_config()
- Parameters
src_clk_freq -- LEDC timer source clock frequency (Hz) (See doxygen comments of
ledc_clk_cfg_tor get from
esp_clk_tree_src_get_freq_hz)
timer_freq -- Desired LEDC timer frequency (Hz)
-
- Returns
0 The timer frequency cannot be achieved
Others The largest duty resolution value to be set
-
-
esp_err_t ledc_timer_config(const ledc_timer_config_t *timer_conf)
LEDC timer configuration Configure LEDC timer with the given source timer/frequency(Hz)/duty_resolution.
- Parameters
timer_conf -- Pointer of LEDC timer configure struct
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution.
ESP_ERR_INVALID_STATE Timer cannot be de-configured because timer is not configured or is not paused
-
-
esp_err_t ledc_update_duty(ledc_mode_t speed_mode, ledc_channel_t channel)
LEDC update channel parameters.
Note
Call this function to activate the LEDC updated parameters. After ledc_set_duty, we need to call this function to update the settings. And the new LEDC parameters don't take effect until the next PWM cycle.
Note
ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update
Note
If
CONFIG_LEDC_CTRL_FUNC_IN_IRAMis enabled, this function will be placed in the IRAM by linker, makes it possible to execute even when the Cache is disabled.
Note
This function is allowed to run within ISR context.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
Note that not all targets support high speed mode.
timer_num -- LEDC timer index (0-3), select from ledc_timer_t
freq_hz -- Set the LEDC frequency
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
ESP_FAIL Can not find a proper pre-divider number base on the given frequency and the current duty_resolution.
-
-
uint32_t ledc_get_freq(ledc_mode_t speed_mode, ledc_timer_t timer_num)
LEDC get channel frequency (Hz)
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint)
LEDC set duty and hpoint value Only after calling ledc_update_duty will the duty update.
Note
ledc_set_duty, ledc_set_duty_with_hpoint and ledc_update_duty are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_duty_and_update
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)]
hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1]
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
-
-
int ledc_get_hpoint(ledc_mode_t speed_mode, ledc_channel_t channel)
LEDC get hpoint value, the counter value when the output is set high level.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
-
- Returns
LEDC_ERR_VAL if parameter error
Others Current hpoint value of LEDC channel
-
-
esp_err_t ledc_set_duty(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty)
LEDC set duty This function do not change the hpoint value of this channel. |
This function returns the duty at the present PWM cycle. You shouldn't expect the function to return the new duty in the same cycle of calling ledc_update_duty, because duty update doesn't take effect until the next cycle.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
-
- Returns
LEDC_ERR_DUTY if parameter error
Others Current LEDC duty
-
-
esp_err_t ledc_set_fade(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, ledc_duty_direction_t fade_direction, uint32_t step_num, uint32_t duty_cycle_num, uint32_t duty_scale)
LEDC set gradient Set LEDC gradient, After the function calls the ledc_update_duty function, the function can take effect.
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
Note
ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
Note
ledc_set_fade_with_step, ledc_set_fade_with_time and ledc_fade_start are not thread-safe, do not call these functions to control one LEDC channel in different tasks at the same time. A thread-safe version of API is ledc_set_fade_step_and_start
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
target_duty -- Target duty of fading [0, (2**duty_resolution)]
max_fade_time_ms -- The maximum time of the fading ( ms ).
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
ESP_ERR_INVALID_STATE Channel not initialized
ESP_FAIL Fade function init error
-
-
esp_err_t ledc_fade_func_install(int intr_alloc_flags)
Install LEDC fade function. This function will occupy interrupt of LEDC module.
- Parameters
intr_alloc_flags -- Flags used to allocate the interrupt. |
Call this API right after ledc_set_fade_with_time or ledc_set_fade_with_step before to start fading.
Note
Starting fade operation with this API is not thread-safe, use with care.
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
channel -- LEDC channel number
fade_mode -- Whether to block until fading done. |
Note that this function will not return until fading to the target duty if LEDC_FADE_WAIT_DONE mode is selected.
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_STATE Channel not initialized or fade function not installed.
ESP_ERR_INVALID_ARG Parameter error.
-
-
esp_err_t ledc_set_duty_and_update(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t duty, uint32_t hpoint)
A thread-safe API to set duty for LEDC channel and return when duty updated.
Note
For ESP32, hardware does not support any duty change while a fade operation is running in progress on that channel. Other duty operations will have to wait until the fade operation has finished.
- Parameters
speed_mode -- Select the LEDC channel group with specified speed mode. Note that not all targets support high speed mode.
|
channel -- LEDC channel (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
duty -- Set the LEDC duty, the range of duty setting is [0, (2**duty_resolution)]
hpoint -- Set the LEDC hpoint value, the range is [0, (2**duty_resolution)-1]
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_STATE Channel not initialized
ESP_ERR_INVALID_ARG Parameter error
ESP_FAIL Fade function init error
-
-
esp_err_t ledc_set_fade_time_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t max_fade_time_ms, ledc_fade_mode_t fade_mode)
A thread-safe API to set and start LEDC fade function, with a limited time.
|
channel -- LEDC channel index (0 - LEDC_CHANNEL_MAX-1), select from ledc_channel_t
target_duty -- Target duty of fading [0, (2**duty_resolution)]
max_fade_time_ms -- The maximum time of the fading ( ms ).
fade_mode -- choose blocking or non-blocking mode
-
- Returns
ESP_OK Success
ESP_ERR_INVALID_ARG Parameter error
ESP_ERR_INVALID_STATE Channel not initialized
ESP_FAIL Fade function init error
-
-
esp_err_t ledc_set_fade_step_and_start(ledc_mode_t speed_mode, ledc_channel_t channel, uint32_t target_duty, uint32_t scale, uint32_t cycle_num, ledc_fade_mode_t fade_mode)
A thread-safe API to set and start LEDC fade function.
|
Enumerations
-
enum ledc_mode_t
Values:
-
enumerator LEDC_HIGH_SPEED_MODE
LEDC high speed speed_mode
-
enumerator LEDC_LOW_SPEED_MODE
LEDC low speed speed_mode
-
enumerator LEDC_SPEED_MODE_MAX
LEDC speed limit
- enumerator LEDC_HIGH_SPEED_MODE
-
enum ledc_intr_type_t
Values:
-
enumerator LEDC_INTR_DISABLE
Disable LEDC interrupt
-
enumerator LEDC_INTR_FADE_END
Enable LEDC interrupt
-
enumerator LEDC_INTR_MAX
- enumerator LEDC_INTR_DISABLE
-
enum ledc_duty_direction_t
Values:
-
enumerator LEDC_DUTY_DIR_DECREASE
LEDC duty decrease direction
-
enumerator LEDC_DUTY_DIR_INCREASE
LEDC duty increase direction
-
enumerator LEDC_DUTY_DIR_MAX
- enumerator LEDC_DUTY_DIR_DECREASE
-
enum ledc_slow_clk_sel_t
LEDC global clock sources.
Values:
-
enumerator LEDC_SLOW_CLK_RC_FAST
LEDC low speed timer clock source is RC_FAST clock
-
enumerator LEDC_SLOW_CLK_APB
LEDC low speed timer clock source is 80MHz APB clock
-
enumerator LEDC_SLOW_CLK_RTC8M
Alias of 'LEDC_SLOW_CLK_RC_FAST'
- enumerator LEDC_SLOW_CLK_RC_FAST
-
enum ledc_clk_src_t
LEDC timer-specific clock sources.
|
Values:
-
enumerator LEDC_REF_TICK
LEDC timer clock divided from reference tick (1Mhz)
-
enumerator LEDC_APB_CLK
LEDC timer clock divided from APB clock (80Mhz)
-
enumerator LEDC_SCLK
Selecting this value for LEDC_TICK_SEL_TIMER let the hardware take its source clock from LEDC_APB_CLK_SEL
- enumerator LEDC_REF_TICK
-
enum ledc_timer_t
Values:
-
enumerator LEDC_TIMER_0
LEDC timer 0
-
enumerator LEDC_TIMER_1
LEDC timer 1
-
enumerator LEDC_TIMER_2
LEDC timer 2
-
enumerator LEDC_TIMER_3
LEDC timer 3
-
enumerator LEDC_TIMER_MAX
- enumerator LEDC_TIMER_0
-
enum ledc_channel_t
Values:
-
enumerator LEDC_CHANNEL_0
LEDC channel 0
-
enumerator LEDC_CHANNEL_1
LEDC channel 1
-
enumerator LEDC_CHANNEL_2
LEDC channel 2
-
enumerator LEDC_CHANNEL_3
LEDC channel 3
-
enumerator LEDC_CHANNEL_4
LEDC channel 4
-
enumerator LEDC_CHANNEL_5
LEDC channel 5
-
enumerator LEDC_CHANNEL_6
LEDC channel 6
-
enumerator LEDC_CHANNEL_7
LEDC channel 7
-
enumerator LEDC_CHANNEL_MAX
- enumerator LEDC_CHANNEL_0
-
enum ledc_timer_bit_t
Values:
-
enumerator LEDC_TIMER_1_BIT
LEDC PWM duty resolution of 1 bits
-
enumerator LEDC_TIMER_2_BIT
LEDC PWM duty resolution of 2 bits
-
enumerator LEDC_TIMER_3_BIT
LEDC PWM duty resolution of 3 bits
-
enumerator LEDC_TIMER_4_BIT
LEDC PWM duty resolution of 4 bits
-
enumerator LEDC_TIMER_5_BIT
LEDC PWM duty resolution of 5 bits
-
enumerator LEDC_TIMER_6_BIT
LEDC PWM duty resolution of 6 bits
-
enumerator LEDC_TIMER_7_BIT
LEDC PWM duty resolution of 7 bits
-
enumerator LEDC_TIMER_8_BIT
LEDC PWM duty resolution of 8 bits
-
enumerator LEDC_TIMER_9_BIT
LEDC PWM duty resolution of 9 bits
-
enumerator LEDC_TIMER_10_BIT
LEDC PWM duty resolution of 10 bits
-
enumerator LEDC_TIMER_11_BIT
LEDC PWM duty resolution of 11 bits
-
enumerator LEDC_TIMER_12_BIT
LEDC PWM duty resolution of 12 bits
-
enumerator LEDC_TIMER_13_BIT
LEDC PWM duty resolution of 13 bits
-
enumerator LEDC_TIMER_14_BIT
LEDC PWM duty resolution of 14 bits
-
enumerator LEDC_TIMER_15_BIT
LEDC PWM duty resolution of 15 bits
-
enumerator LEDC_TIMER_16_BIT
LEDC PWM duty resolution of 16 bits
-
enumerator LEDC_TIMER_17_BIT
LEDC PWM duty resolution of 17 bits
-
enumerator LEDC_TIMER_18_BIT
LEDC PWM duty resolution of 18 bits
-
enumerator LEDC_TIMER_19_BIT
LEDC PWM duty resolution of 19 bits
-
enumerator LEDC_TIMER_20_BIT
LEDC PWM duty resolution of 20 bits
-
enumerator LEDC_TIMER_BIT_MAX
- enumerator LEDC_TIMER_1_BIT |
The MCPWM peripheral is a versatile PWM generator, which contains various submodules to make it a key element in power electronic applications like motor control, digital power, and so on. Typically, the MCPWM peripheral can be used in the following scenarios:
Digital motor control, e.g., brushed/brushless DC motor, RC servo motor
Switch mode-based digital power conversion
Power DAC, where the duty cycle is equivalent to a DAC analog value
Calculate external pulse width, and convert it into other analog values like speed, distance
Generate Space Vector PWM (SVPWM) signals for Field Oriented Control (FOC)
The main submodules are listed in the following diagram:
MCPWM Timer: The time base of the final PWM signal. It also determines the event timing of other submodules.
MCPWM Operator: The key module that is responsible for generating the PWM waveforms. It consists of other submodules, like comparator, PWM generator, dead time, and carrier modulator.
MCPWM Comparator: The compare module takes the time-base count value as input, and continuously compares it to the threshold value configured. When the timer is equal to any of the threshold values, a compare event will be generated and the MCPWM generator can update its level accordingly.
MCPWM Generator: One MCPWM generator can generate a pair of PWM waves, complementarily or independently, based on various events triggered by other submodules like MCPWM Timer and MCPWM Comparator.
MCPWM Fault: The fault module is used to detect the fault condition from outside, mainly via the GPIO matrix. Once the fault signal is active, MCPWM Operator will force all the generators into a predefined state to protect the system from damage.
|
Please note, timers located in different groups are totally independent.
mcpwm_timer_config_t::intr_prioritysets the priority of the 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.
mcpwm_timer_config_t::clk_srcsets the clock source of the timer.
mcpwm_timer_config_t::resolution_hzsets the expected resolution of the timer. The driver internally sets a proper divider based on the clock source and the resolution.
mcpwm_timer_config_t::count_modesets the count mode of the timer.
mcpwm_timer_config_t::period_tickssets the period of the timer, in ticks (the tick resolution is set in the
mcpwm_timer_config_t::resolution_hz).
mcpwm_timer_config_t::update_period_on_emptysets whether to update the period value when the timer counts to zero.
mcpwm_timer_config_t::update_period_on_syncsets whether to update the period value when the timer takes a sync signal.
The
mcpwm_new_timer() will return a pointer to the allocated timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free timers in the MCPWM group, this function will return the
ESP_ERR_NOT_FOUND error. 1
On the contrary, calling the
mcpwm_del_timer() function will free the allocated timer object.
MCPWM Operators
You can allocate a MCPWM operator object by calling
mcpwm_new_operator()() function, with a configuration structure
mcpwm_operator_config_t as the parameter. The configuration structure is defined as:
mcpwm_operator_config_t::group_idspecifies the MCPWM group ID. The ID should belong to [0,
SOC_MCPWM_GROUPS- 1] range. |
Please note, operators located in different groups are totally independent.
mcpwm_operator_config_t::intr_prioritysets the priority of the 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.
mcpwm_operator_config_t::update_gen_action_on_tezsets whether to update the generator action when the timer counts to zero. Here and below, the timer refers to the one that is connected to the operator by
mcpwm_operator_connect_timer().
mcpwm_operator_config_t::update_gen_action_on_tepsets whether to update the generator action when the timer counts to peak.
mcpwm_operator_config_t::update_gen_action_on_syncsets whether to update the generator action when the timer takes a sync signal.
mcpwm_operator_config_t::update_dead_time_on_tezsets whether to update the dead time when the timer counts to zero.
mcpwm_operator_config_t::update_dead_time_on_tepsets whether to update the dead time when the timer counts to the peak.
mcpwm_operator_config_t::update_dead_time_on_syncsets whether to update the dead time when the timer takes a sync signal.
The
mcpwm_new_operator()() will return a pointer to the allocated operator object if the allocation succeeds. |
The configuration structure is defined as:
mcpwm_comparator_config_t::intr_prioritysets the priority of the 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.
mcpwm_comparator_config_t::update_cmp_on_tezsets whether to update the compare threshold when the timer counts to zero.
mcpwm_comparator_config_t::update_cmp_on_tepsets whether to update the compare threshold when the timer counts to the peak.
mcpwm_comparator_config_t::update_cmp_on_syncsets whether to update the compare threshold when the timer takes a sync signal.
The
mcpwm_new_comparator() will return a pointer to the allocated comparator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free comparators in the MCPWM operator, this function will return the
ESP_ERR_NOT_FOUND error. 1
On the contrary, calling the
mcpwm_del_comparator() function will free the allocated comparator object.
MCPWM Generators
You can allocate a MCPWM generator object by calling the
mcpwm_new_generator() function, with a MCPWM operator handle and configuration structure
mcpwm_generator_config_t as the parameter. |
It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral.
mcpwm_generator_config_t::io_od_modeconfigures the PWM GPIO as open-drain output.
mcpwm_generator_config_t::pull_upand
mcpwm_generator_config_t::pull_downcontrols whether to enable the internal pull-up and pull-down resistors accordingly.
The
mcpwm_new_generator() will return a pointer to the allocated generator object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free generators in the MCPWM operator, this function will return the
ESP_ERR_NOT_FOUND error. 1
On the contrary, calling the
mcpwm_del_generator() function will free the allocated generator object.
MCPWM Faults
There are two types of faults: A fault signal reflected from the GPIO and a fault generated by software.
To allocate a GPIO fault object, you can call the
mcpwm_new_gpio_fault() function, with the configuration structure
mcpwm_gpio_fault_config_t as the parameter. The configuration structure is defined as:
mcpwm_gpio_fault_config_t::group_idsets the MCPWM group ID. The ID should belong to [0,
SOC_MCPWM_GROUPS- 1] range. |
Please note, GPIO faults located in different groups are totally independent, i.e., GPIO faults in group 0 can not be detected by the operator in group 1.
mcpwm_gpio_fault_config_t::intr_prioritysets the priority of the 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.
mcpwm_gpio_fault_config_t::gpio_numsets the GPIO number used by the fault.
mcpwm_gpio_fault_config_t::active_levelsets the active level of the fault signal.
mcpwm_gpio_fault_config_t::pull_upand
mcpwm_gpio_fault_config_t::pull_downset whether to pull up and/or pull down the GPIO internally.
mcpwm_gpio_fault_config_t::io_loop_backsets whether to enable the loopback mode. It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral.
The
mcpwm_new_gpio_fault() will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO faults in the MCPWM group, this function will return the
ESP_ERR_NOT_FOUND error. 1
Software fault object can be used to trigger a fault by calling the function
mcpwm_soft_fault_activate() instead of waiting for a real fault signal on the GPIO. A software fault object can be allocated by calling the
mcpwm_new_soft_fault() function, with configuration structure
mcpwm_soft_fault_config_t as the parameter. Currently, this configuration structure is left for future purposes.
The
mcpwm_new_soft_fault() function will return a pointer to the allocated fault object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the fault object, this function will return the
ESP_ERR_NO_MEM error. Although the software fault and GPIO fault are of different types, the returned fault handle is of the same type.
On the contrary, calling the
mcpwm_del_fault() function will free the allocated fault object, this function works for both software and GPIO fault.
MCPWM Sync Sources
The sync source is what can be used to synchronize the MCPWM timer and MCPWM capture timer. There are three types of sync sources: a sync source reflected from the GPIO, a sync source generated by software, and a sync source generated by an MCPWM timer event.
To allocate a GPIO sync source, you can call the
mcpwm_new_gpio_sync_src() function, with configuration structure
mcpwm_gpio_sync_src_config_t as the parameter. The configuration structure is defined as:
mcpwm_gpio_sync_src_config_t::group_idsets the MCPWM group ID. The ID should belong to [0,
SOC_MCPWM_GROUPS- 1] range. |
Please note, the GPIO sync sources located in different groups are totally independent, i.e., GPIO sync source in group 0 can not be detected by the timers in group 1.
mcpwm_gpio_sync_src_config_t::gpio_numsets the GPIO number used by the sync source.
mcpwm_gpio_sync_src_config_t::active_negsets whether the sync signal is active on falling edges.
mcpwm_gpio_sync_src_config_t::pull_upand
mcpwm_gpio_sync_src_config_t::pull_downset whether to pull up and/or pull down the GPIO internally.
mcpwm_gpio_sync_src_config_t::io_loop_backsets whether to enable the Loop-back mode. |
It is for debugging purposes only. It enables both the GPIO's input and output ability through the GPIO matrix peripheral.
The
mcpwm_new_gpio_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there are no more free GPIO sync sources in the MCPWM group, this function will return the
ESP_ERR_NOT_FOUND error. 1
To allocate a timer event sync source, you can call the
mcpwm_new_timer_sync_src() function, with configuration structure
mcpwm_timer_sync_src_config_t as the parameter. The configuration structure is defined as:
mcpwm_timer_sync_src_config_t::timer_eventspecifies on what timer event to generate the sync signal.
mcpwm_timer_sync_src_config_t::propagate_input_syncsets whether to propagate the input sync signal (i.e., the input sync signal will be routed to its sync output).
The
mcpwm_new_timer_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, if a sync source has been allocated from the same timer before, this function will return the
ESP_ERR_INVALID_STATE error.
Last but not least, to allocate a software sync source, you can call the
mcpwm_new_soft_sync_src() function, with configuration structure
mcpwm_soft_sync_config_t as the parameter. Currently, this configuration structure is left for future purposes.
mcpwm_new_soft_sync_src() will return a pointer to the allocated sync source object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no memory left for the sync source object, this function will return the
ESP_ERR_NO_MEM error. Please note, to make a software sync source take effect, do not forget to call
mcpwm_soft_sync_activate().
On the contrary, calling the
mcpwm_del_sync_src() function will free the allocated sync source object. This function works for all types of sync sources.
MCPWM Capture Timer and Channels
The MCPWM group has a dedicated timer which is used to capture the timestamp when a specific event occurred. The capture timer is connected to several independent channels, each channel is assigned a GPIO.
To allocate a capture timer, you can call the
mcpwm_new_capture_timer() function, with configuration structure
mcpwm_capture_timer_config_t as the parameter. The configuration structure is defined as:
mcpwm_capture_timer_config_t::group_idsets the MCPWM group ID. The ID should belong to [0,
SOC_MCPWM_GROUPS- 1] range.
|
mcpwm_capture_timer_config_t::clk_srcsets the clock source of the capture timer.
mcpwm_capture_timer_config_t::resolution_hzThe driver internally will set a proper divider based on the clock source and the resolution. If it is set to
0, the driver will pick an appropriate resolution on its own, and you can subsequently view the current timer resolution via
mcpwm_capture_timer_get_resolution().
Note
In ESP32,
mcpwm_capture_timer_config_t::resolution_hz parameter is invalid, the capture timer resolution is always equal to the
MCPWM_CAPTURE_CLK_SRC_APB.
The
mcpwm_new_capture_timer() will return a pointer to the allocated capture timer object if the allocation succeeds. Otherwise, it will return an error code. Specifically, when there is no free capture timer left in the MCPWM group, this function will return the
ESP_ERR_NOT_FOUND error. 1
Next, to allocate a capture channel, you can call the
mcpwm_new_capture_channel() function, with a capture timer handle and configuration structure
mcpwm_capture_channel_config_t as the parameter. The configuration structure is defined as:
mcpwm_capture_channel_config_t::intr_prioritysets the priority of the 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.
mcpwm_capture_channel_config_t::gpio_numsets the GPIO number used by the capture channel.
mcpwm_capture_channel_config_t::prescalesets the prescaler of the input signal.
mcpwm_capture_channel_config_t::pos_edgeand
mcpwm_capture_channel_config_t::neg_edgeset whether to capture on the positive and/or falling edge of the input signal.
mcpwm_capture_channel_config_t::pull_upand
mcpwm_capture_channel_config_t::pull_downset whether to pull up and/or pull down the GPIO internally.
mcpwm_capture_channel_config_t::invert_cap_signalsets whether to invert the capture signal.
mcpwm_capture_channel_config_t::io_loop_backsets whether to enable the Loop-back mode. |
Please note, fault event does not have variadic function like
mcpwm_generator_set_actions_on_fault_event().
Set Generator Action on Sync Event
One generator can set action on sync based trigger events, by calling
mcpwm_generator_set_action_on_sync_event() with an action configurations. The action configuration is defined in
mcpwm_gen_sync_event_action_t:
mcpwm_gen_sync_event_action_t::directionspecifies the timer direction. The supported directions are listed in
mcpwm_timer_direction_t.
mcpwm_gen_sync_event_action_t::syncspecifies the sync source used for the trigger. See MCPWM Sync Sources for how to allocate a sync source.
mcpwm_gen_sync_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in
mcpwm_generator_action_t.
When no free trigger slot is left in the operator to which the generator belongs, this function will return the
ESP_ERR_NOT_FOUND error. 1
The trigger only support one sync action, regardless of the kinds. When set sync actions more than once, this function will return the
ESP_ERR_INVALID_STATE error.
There is a helper macro
MCPWM_GEN_SYNC_EVENT_ACTION to simplify the construction of a trigger event action entry.
|
Please note, sync event does not have variadic function like
mcpwm_generator_set_actions_on_sync_event().
Generator Configurations for Classical PWM Waveforms
This section will demonstrate the classical PWM waveforms that can be generated by the pair of generators. The code snippet that is used to generate the waveforms is also provided below the diagram. Some general summary:
The Symmetric or Asymmetric of the waveforms is determined by the count mode of the MCPWM timer.
The active level of the waveform pair is determined by the level of the PWM with a smaller duty cycle.
The period of the PWM waveform is determined by the timer's period and count mode.
The duty cycle of the PWM waveform is determined by the generator's various action combinations.
|
This requires the use of a rectifier bridge and an inverter bridge. Each bridge arm has two power electronic devices, such as MOSFET, IGBT, etc. The two MOSFETs on the same arm can not conduct at the same time, otherwise there will be a short circuit. The fact is that, although the PWM wave shows it is turning off the switch, the MOSFET still needs a small time window to make that happen. This requires an extra delay to be added to the existing PWM wave generated by setting Generator Actions on Events.
The dead time driver works like a decorator. This is also reflected in the function parameters of
mcpwm_generator_set_dead_time(), where it takes the primary generator handle (
in_generator), and returns a new generator (
out_generator) after applying the dead time. Please note, if the
out_generator and
in_generator are the same, it means you are adding the time delay to the PWM waveform in an "in-place" fashion. In turn, if the
out_generator and
in_generator are different, it means you are deriving a new PWM waveform from the existing
in_generator.
Dead time specific configuration is listed in the
mcpwm_dead_time_config_t structure:
mcpwm_dead_time_config_t::posedge_delay_ticksand
mcpwm_dead_time_config_t::negedge_delay_ticksset the number of ticks to delay the PWM waveform on the rising and falling edge. Specifically, setting both of them to zero means bypassing the dead time module. The resolution of the dead time tick is the same as the timer that is connected with the operator by
mcpwm_operator_connect_timer().
mcpwm_dead_time_config_t::invert_outputsets whether to invert the signal after applying the dead time, which can be used to control the delay edge polarity.
Warning
Due to the hardware limitation, one delay module (either
posedge delay or
negedge delay) can not be applied to multiple MCPWM generators at the same time. e.g., the following configuration is invalid:
mcpwm_dead_time_config_t |
This is invalid, you can not apply the posedge delay to another generator
mcpwm_generator_set_dead_time(mcpwm_gen_b, mcpwm_gen_b, &dt_config);
However, you can apply
posedge delay to generator A and
negedge delay to generator B. You can also set both
posedge delay and
negedge delay for generator A, while letting generator B bypass the dead time module.
Note
It is also possible to generate the required dead time by setting Generator Actions on Events, especially by controlling edge placement using different comparators. However, if the more classical edge delay-based dead time with polarity control is required, then the dead time submodule should be used.
Dead Time Configurations for Classical PWM Waveforms
This section demonstrates the classical PWM waveforms that can be generated by the dead time submodule. The code snippet that is used to generate the waveforms is also provided below the diagram.
|
gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb)
{
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW)));
}
static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb)
{
mcpwm_dead_time_config_t dead_time_config = {
.posedge_delay_ticks = 50,
.negedge_delay_ticks = 0
};
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config));
dead_time_config.posedge_delay_ticks = 0;
dead_time_config.negedge_delay_ticks = 100;
dead_time_config.flags.invert_output = true;
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config));
}
Active Low Complementary
static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb)
{
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW)));
}
static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb)
{
mcpwm_dead_time_config_t dead_time_config = {
.posedge_delay_ticks = 50,
.negedge_delay_ticks = 0,
.flags.invert_output = true
};
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config));
dead_time_config.posedge_delay_ticks = 0;
dead_time_config.negedge_delay_ticks = 100;
dead_time_config.flags.invert_output = false;
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, genb, &dead_time_config));
}
Active High
static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb)
{
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW)));
}
static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb)
|
= 0,
};
// generator_a bypass the deadtime module (no delay)
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config));
// apply dead time to generator_b
dead_time_config.negedge_delay_ticks = 50;
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config));
}
Rising and Falling Delay on PWMB and Bypass Dead Time for PWMA
static void gen_action_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb, mcpwm_cmpr_handle_t cmpa, mcpwm_cmpr_handle_t cmpb)
{
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(gena,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(gena,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpa, MCPWM_GEN_ACTION_LOW)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_timer_event(genb,
MCPWM_GEN_TIMER_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, MCPWM_TIMER_EVENT_EMPTY, MCPWM_GEN_ACTION_HIGH)));
ESP_ERROR_CHECK(mcpwm_generator_set_action_on_compare_event(genb,
MCPWM_GEN_COMPARE_EVENT_ACTION(MCPWM_TIMER_DIRECTION_UP, cmpb, MCPWM_GEN_ACTION_LOW)));
}
static void dead_time_config(mcpwm_gen_handle_t gena, mcpwm_gen_handle_t genb)
{
mcpwm_dead_time_config_t |
dead_time_config = {
.posedge_delay_ticks = 0,
.negedge_delay_ticks = 0,
};
// generator_a bypass the deadtime module (no delay)
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(gena, gena, &dead_time_config));
// apply dead time on both edge for generator_b
dead_time_config.negedge_delay_ticks = 50;
dead_time_config.posedge_delay_ticks = 50;
ESP_ERROR_CHECK(mcpwm_generator_set_dead_time(genb, genb, &dead_time_config));
}
Carrier Modulation
The MCPWM operator has a carrier submodule that can be used if galvanic isolation from the motor driver is required (e.g., isolated digital power application) by passing the PWM output signals through transformers. |
Set Generator Action on Brake Event
One generator can set multiple actions on different brake events, by calling
mcpwm_generator_set_actions_on_brake_event() with a variable number of action configurations. The action configuration is defined in
mcpwm_gen_brake_event_action_t:
mcpwm_gen_brake_event_action_t::directionspecifies the timer direction. The supported directions are listed in
mcpwm_timer_direction_t.
mcpwm_gen_brake_event_action_t::brake_modespecifies the brake mode. The supported brake modes are listed in the
mcpwm_operator_brake_mode_t.
mcpwm_gen_brake_event_action_t::actionspecifies the generator action to be taken. The supported actions are listed in
mcpwm_generator_action_t.
There is a helper macro
MCPWM_GEN_BRAKE_EVENT_ACTION to simplify the construction of a brake event action entry.
Please note, the argument list of
mcpwm_generator_set_actions_on_brake_event() must be terminated by
MCPWM_GEN_BRAKE_EVENT_ACTION_END.
You can also set the brake action one by one by calling
mcpwm_generator_set_action_on_brake_event() without varargs.
Register Fault Event Callbacks
The MCPWM fault detector can inform you when it detects a valid fault or a fault signal disappears. If you have some function that should be called when such an event happens, you should hook your function to the interrupt service routine by calling
mcpwm_fault_register_event_callbacks(). The callback function prototype is declared in
mcpwm_fault_event_cb_t. All supported event callbacks are listed in the
mcpwm_fault_event_callbacks_t:
mcpwm_fault_event_callbacks_t::on_fault_entersets the callback function that will be called when a fault is detected.
mcpwm_fault_event_callbacks_t::on_fault_exitsets the callback function that will be called when a fault is cleared.
The callback function is called within the ISR context, so it should not attempt to block. For example, you may make sure that only FreeRTOS APIs with the
ISR suffix are called within the function.
The parameter
user_data of
mcpwm_fault_register_event_callbacks() function is used to save your own context. It is passed to the callback function directly.
This function will lazy the install interrupt service for the MCPWM fault, whereas the service can only be removed in
mcpwm_del_fault.
Register Brake Event Callbacks
The MCPWM operator can inform you when it is going to take a brake action. If you have some function that should be called when this event happens, you should hook your function to the interrupt service routine by calling
mcpwm_operator_register_event_callbacks(). The callback function prototype is declared in
mcpwm_brake_event_cb_t. All supported event callbacks are listed in the
mcpwm_operator_event_callbacks_t:
mcpwm_operator_event_callbacks_t::on_brake_cbcsets |
false, // By default, a posedge pulse can trigger a sync event
};
ESP_ERROR_CHECK(mcpwm_new_gpio_sync_src(&gpio_sync_config, &gpio_sync_source));
mcpwm_timer_sync_phase_config_t sync_phase_config = {
.count_value = 0, // sync phase: target count value
.direction = MCPWM_TIMER_DIRECTION_UP, // sync phase: count direction
.sync_src = gpio_sync_source, // sync source
};
for (int i = 0; i < 3; i++) {
ESP_ERROR_CHECK(mcpwm_timer_set_phase_on_sync(timers[i], &sync_phase_config));
}
}
Capture
The basic functionality of MCPWM capture is to record the time when any pulse edge of the capture signal turns active. |
Application Examples
Brushed DC motor speed control by PID algorithm: peripherals/mcpwm/mcpwm_bdc_speed_control
BLDC motor control with hall sensor feedback: peripherals/mcpwm/mcpwm_bldc_hall_control
Ultrasonic sensor (HC-SR04) distance measurement: peripherals/mcpwm/mcpwm_capture_hc_sr04
Servo motor angle control: peripherals/mcpwm/mcpwm_servo_control
MCPWM synchronization between timers: peripherals/mcpwm/mcpwm_sync
API Reference
Header File
This header file can be included with:
#include "driver/mcpwm_timer.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 mcpwm_new_timer(const mcpwm_timer_config_t *config, mcpwm_timer_handle_t *ret_timer)
Create MCPWM timer.
- Parameters
config -- |
[in] MCPWM timer handle, allocated by
mcpwm_new_timer()
- Returns
ESP_OK: Delete MCPWM timer successfully
ESP_ERR_INVALID_ARG: Delete MCPWM timer failed because of invalid argument
ESP_ERR_INVALID_STATE: Delete MCPWM timer failed because timer is not in init state
ESP_FAIL: Delete MCPWM timer failed because of other error
-
-
esp_err_t mcpwm_timer_set_period(mcpwm_timer_handle_t timer, uint32_t period_ticks)
Set a new period for MCPWM timer.
Note
If
mcpwm_timer_config_t::update_period_on_emptyand
mcpwm_timer_config_t::update_period_on_syncare not set, the new period will take effect immediately. Otherwise, the new period will take effect when timer counts to zero or on sync event.
Note
You may need to use
mcpwm_comparator_set_compare_valueto set a new compare value for MCPWM comparator in order to keep the same PWM duty cycle.
- Parameters
timer -- |
[in] MCPWM timer handle, allocated by
mcpwm_new_timer
period_ticks -- [in] New period in count ticks
-
- Returns
ESP_OK: Set new period for MCPWM timer successfully
ESP_ERR_INVALID_ARG: Set new period for MCPWM timer failed because of invalid argument
ESP_FAIL: Set new period for MCPWM timer failed because of other error
-
-
esp_err_t mcpwm_timer_enable(mcpwm_timer_handle_t timer)
Enable MCPWM timer.
- Parameters
timer -- [in] MCPWM timer handle, allocated by
mcpwm_new_timer()
- Returns
ESP_OK: Enable MCPWM timer successfully
ESP_ERR_INVALID_ARG: Enable MCPWM timer failed because of invalid argument
ESP_ERR_INVALID_STATE: Enable MCPWM timer failed because timer is enabled already
ESP_FAIL: Enable MCPWM timer failed because of other error
-
-
esp_err_t mcpwm_timer_disable(mcpwm_timer_handle_t timer)
Disable MCPWM timer.
- Parameters
timer -- [in] MCPWM timer handle, allocated by
mcpwm_new_timer()
- Returns
ESP_OK: Disable MCPWM timer successfully
ESP_ERR_INVALID_ARG: Disable MCPWM timer failed because of invalid argument
ESP_ERR_INVALID_STATE: Disable MCPWM timer failed because timer is disabled already
ESP_FAIL: Disable MCPWM timer failed because of other error
-
-
esp_err_t mcpwm_timer_start_stop(mcpwm_timer_handle_t timer, mcpwm_timer_start_stop_cmd_t command)
Send specific start/stop commands to MCPWM timer.
- Parameters
timer -- [in] MCPWM timer handle, allocated by
mcpwm_new_timer()
command -- [in] Supported command list for MCPWM timer
-
- Returns
ESP_OK: Start or stop MCPWM timer successfully
ESP_ERR_INVALID_ARG: Start or stop MCPWM timer failed because of invalid argument
ESP_ERR_INVALID_STATE: Start or stop MCPWM timer failed because timer is not enabled
ESP_FAIL: Start or stop MCPWM timer failed because of other error
-
-
esp_err_t mcpwm_timer_register_event_callbacks(mcpwm_timer_handle_t timer, const mcpwm_timer_event_callbacks_t *cbs, void *user_data)
Set event callbacks for MCPWM timer.
Note
The first call to this function needs to be before the call to
mcpwm_timer_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] MCPWM timer handle, allocated by
mcpwm_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 timer is not in init state
ESP_FAIL: Set event callbacks failed because of other error
-
-
esp_err_t mcpwm_timer_set_phase_on_sync(mcpwm_timer_handle_t timer, const mcpwm_timer_sync_phase_config_t *config)
Set sync phase for MCPWM timer.
- Parameters
timer -- |
[in] MCPWM timer sync phase configuration
-
- Returns
ESP_OK: Set sync phase for MCPWM timer successfully
ESP_ERR_INVALID_ARG: Set sync phase for MCPWM timer failed because of invalid argument
ESP_FAIL: Set sync phase for MCPWM timer failed because of other error
-
Structures
-
struct mcpwm_timer_event_callbacks_t
Group of supported MCPWM timer event callbacks.
Note
The callbacks are all running under ISR environment
Public Members
-
mcpwm_timer_event_cb_t on_full
callback function when MCPWM timer counts to peak value
-
mcpwm_timer_event_cb_t on_empty
callback function when MCPWM timer counts to zero
-
mcpwm_timer_event_cb_t on_stop
callback function when MCPWM timer stops
- mcpwm_timer_event_cb_t on_full
-
struct mcpwm_timer_config_t
MCPWM timer configuration.
Public Members
-
int group_id
Specify from which group to allocate the MCPWM timer
-
mcpwm_timer_clock_source_t clk_src
MCPWM timer clock source
-
uint32_t resolution_hz
Counter resolution in Hz The step size of each count tick equals to (1 / resolution_hz) seconds
-
mcpwm_timer_count_mode_t count_mode
Count mode
-
uint32_t period_ticks
Number of count ticks within a period
-
int intr_priority
MCPWM timer interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3)
-
uint32_t update_period_on_empty
Whether to update period when timer counts to zero
-
uint32_t update_period_on_sync
Whether to update period on sync event
-
struct mcpwm_timer_config_t::[anonymous] flags
Extra configuration flags for timer
- int group_id
-
struct mcpwm_timer_sync_phase_config_t
MCPWM Timer sync phase configuration.
Public Members
-
mcpwm_sync_handle_t sync_src
The sync event source. Set to NULL will disable the timer being synced by others
-
uint32_t count_value
The count value that should lock to upon sync event
-
mcpwm_timer_direction_t direction
The count direction that should lock to upon sync event
- mcpwm_sync_handle_t sync_src
Header File
This header file can be included with:
#include "driver/mcpwm_oper.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 mcpwm_new_operator(const mcpwm_operator_config_t *config, mcpwm_oper_handle_t *ret_oper)
Create MCPWM operator.
- Parameters
config -- |
[in] MCPWM operator handle, allocated by
mcpwm_new_operator()
timer -- [in] MCPWM timer handle, allocated by
mcpwm_new_timer()
-
- Returns
ESP_OK: Connect MCPWM operator and timer successfully
ESP_ERR_INVALID_ARG: Connect MCPWM operator and timer failed because of invalid argument
ESP_FAIL: Connect MCPWM operator and timer failed because of other error
-
-
esp_err_t mcpwm_operator_set_brake_on_fault(mcpwm_oper_handle_t oper, const mcpwm_brake_config_t *config)
Set brake method for MCPWM operator.
- Parameters
oper -- [in] MCPWM operator, allocated by
mcpwm_new_operator()
config -- |
Recover from fault failed because of invalid argument
ESP_ERR_INVALID_STATE: Recover from fault failed because the fault source is still active
ESP_FAIL: Recover from fault failed because of other error
-
-
esp_err_t mcpwm_operator_register_event_callbacks(mcpwm_oper_handle_t oper, const mcpwm_operator_event_callbacks_t *cbs, void *user_data)
Set event callbacks for MCPWM operator.
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
cbsstructure to NULL.
- Parameters
oper -- |
[in] MCPWM operator handle, allocated by
mcpwm_new_operator()
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_FAIL: Set event callbacks failed because of other error
-
-
esp_err_t mcpwm_operator_apply_carrier(mcpwm_oper_handle_t oper, const mcpwm_carrier_config_t *config)
Apply carrier feature for MCPWM operator.
- Parameters
oper -- |
Create MCPWM comparator failed because of other error
-
-
esp_err_t mcpwm_del_comparator(mcpwm_cmpr_handle_t cmpr)
Delete MCPWM comparator.
- Parameters
cmpr -- [in] MCPWM comparator handle, allocated by
mcpwm_new_comparator()
- Returns
ESP_OK: Delete MCPWM comparator successfully
ESP_ERR_INVALID_ARG: Delete MCPWM comparator failed because of invalid argument
ESP_FAIL: Delete MCPWM comparator failed because of other error
-
-
esp_err_t mcpwm_comparator_register_event_callbacks(mcpwm_cmpr_handle_t cmpr, const mcpwm_comparator_event_callbacks_t *cbs, void *user_data)
Set event callbacks for MCPWM comparator.
Note
User can deregister a previously registered callback by calling this function and setting the callback member in the
cbsstructure to NULL.
- Parameters
cmpr -- |
[in] MCPWM comparator handle, allocated by
mcpwm_new_comparator()
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_FAIL: Set event callbacks failed because of other error
-
-
esp_err_t mcpwm_comparator_set_compare_value(mcpwm_cmpr_handle_t cmpr, uint32_t cmp_ticks)
Set MCPWM comparator's compare value.
- Parameters
cmpr -- |
Set MCPWM compare value failed because the operator doesn't have a timer connected
ESP_FAIL: Set MCPWM compare value failed because of other error
-
Structures
-
struct mcpwm_comparator_config_t
MCPWM comparator configuration.
Public Members
-
int intr_priority
MCPWM comparator interrupt priority, if set to 0, the driver will try to allocate an interrupt with a relative low priority (1,2,3)
-
uint32_t update_cmp_on_tez
Whether to update compare value when timer count equals to zero (tez)
-
uint32_t update_cmp_on_tep
Whether to update compare value when timer count equals to peak (tep)
-
uint32_t update_cmp_on_sync
Whether to update compare value on sync event
-
struct mcpwm_comparator_config_t::[anonymous] flags
Extra configuration flags for comparator
- int intr_priority
-
struct mcpwm_comparator_event_callbacks_t
Group of supported MCPWM compare event callbacks.
Note
The callbacks are all running under ISR environment
Public Members
-
mcpwm_compare_event_cb_t on_reach
ISR callback function which would be invoked when counter reaches compare value
- mcpwm_compare_event_cb_t on_reach
Header File
This header file can be included with:
#include "driver/mcpwm_gen.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 mcpwm_new_generator(mcpwm_oper_handle_t oper, const mcpwm_generator_config_t *config, mcpwm_gen_handle_t *ret_gen)
Allocate MCPWM generator from given operator.
- Parameters
oper -- |
[in] MCPWM operator, allocated by
mcpwm_new_operator()
config -- [in] MCPWM generator configuration
ret_gen -- [out] Returned MCPWM generator
-
- Returns
ESP_OK: Create MCPWM generator successfully
ESP_ERR_INVALID_ARG: Create MCPWM generator failed because of invalid argument
ESP_ERR_NO_MEM: Create MCPWM generator failed because out of memory
ESP_ERR_NOT_FOUND: Create MCPWM generator failed because can't find free resource
ESP_FAIL: Create MCPWM generator failed because of other error
-
-
esp_err_t mcpwm_del_generator(mcpwm_gen_handle_t gen)
Delete MCPWM generator.
- Parameters
gen -- |