add some code

This commit is contained in:
2025-09-05 13:25:11 +08:00
parent 9ff0a99e7a
commit 3cf1229a85
8911 changed files with 2535396 additions and 0 deletions

View File

@@ -0,0 +1 @@
ca6ef69bba4dc0d3e0ce53937635ed2734d38ac947881da81b8526e6851a71a4

View File

@@ -0,0 +1,23 @@
# ChangeLog
## v0.2.1 - 2025-08-08
### Fixes:
* Fixed a crash when calling `esp_codec_dev_open` and `esp_codec_dev_close` across tasks.
### Note:
* This version creates an internal task, whose priority and task size can be adjusted via `menuconfig`. Correspondingly, the memory overhead will increase by the configured amount.
## v0.2.0 - 2024-05-22
### Enhancements:
* Add config ADC_MIC_APPLY_GAIN to apply gain to the ADC mic.
## v0.1.0 - 2024-05-22
### Enhancements:
* Initial version.

View File

@@ -0,0 +1 @@
{"version": "1.0", "algorithm": "sha256", "created_at": "2025-08-19T02:52:04.482971+00:00", "files": [{"path": "CHANGELOG.md", "size": 501, "hash": "6e37fc331c56d0b18dae50294535c8a5d373761a638e89065e471a90193888ed"}, {"path": "CMakeLists.txt", "size": 198, "hash": "cf0669c282c5ddc149d54a977dfe2d458ab55ab8a8906ee7b51cc46af407027f"}, {"path": "Kconfig", "size": 1224, "hash": "5ee4533b3e24839b93391f544d58220c6595dead7678851d0c522cb64f86a598"}, {"path": "README.md", "size": 863, "hash": "cf64c031c6e4cdd5d4a758f8fff16d6be64e1e48d087d537cfe6b05ee0410ba8"}, {"path": "adc_mic.c", "size": 15863, "hash": "d1e596534f8f93aa59f52c9f619378d8bf83de9085611bab95a49c3bc9b30d88"}, {"path": "adc_mic.h", "size": 3449, "hash": "30aa424c85930cd244d6706131e8d65409639a16a910e86754929b8221f8ceaa"}, {"path": "idf_component.yml", "size": 591, "hash": "edad86903cbfedc9a087b2b5650de571ee503e517fbdbb42039c4bd38cc0f55f"}, {"path": "license.txt", "size": 11358, "hash": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"}, {"path": "test_apps/CMakeLists.txt", "size": 352, "hash": "afe15b9bff99e89a0e1f44c6dc14b2707d827d177e5f7bc333fa011414ddb7b5"}, {"path": "test_apps/sdkconfig.defaults", "size": 255, "hash": "8787e6e841902500d50684d32fb2e42d962908b9d48114b0c8415174942ddfbd"}, {"path": "test_apps/main/CMakeLists.txt", "size": 114, "hash": "ef8db1c6618f6af135742f9dfe28bc3391b0f3ae280714c8110c0235f9091b20"}, {"path": "test_apps/main/adc_mic_test.c", "size": 3900, "hash": "f7140377aad94e7dd1033877d8f139be74183e06e56e7a9e541fc50a4d3ca7c2"}, {"path": "test_apps/main/adc_mic_test_main.c", "size": 1142, "hash": "6e751011ddb38032830a3df04e5a6f5856bf582af5b6b11f4e09333b62af8d21"}]}

View File

@@ -0,0 +1,6 @@
idf_component_register(SRCS "adc_mic.c"
INCLUDE_DIRS "."
REQUIRES "esp_adc")
include(package_manager)
cu_pkg_define_version(${CMAKE_CURRENT_LIST_DIR})

View File

@@ -0,0 +1,44 @@
menu "ADC Mic"
config ADC_MIC_APPLY_GAIN
int "Apply Gain"
default 3
range 0 4
help
Apply gain to the ADC mic.
0: No gain applied
1: Left shift 1 bit (2x gain)
2: Left shift 2 bits (4x gain)
3: Left shift 3 bits (8x gain)
4: Left shift 4 bits (16x gain)
config ADC_MIC_OFFSET
int
default 2048 if ADC_MIC_APPLY_GAIN = 0
default 4095 if ADC_MIC_APPLY_GAIN = 1
default 8190 if ADC_MIC_APPLY_GAIN = 2
default 16380 if ADC_MIC_APPLY_GAIN = 3
default 32760 if ADC_MIC_APPLY_GAIN = 4
config ADC_MIC_TASK_PRIORITY
int "Task Priority"
default 1
range 0 15
help
Task priority for the ADC mic worker task.
config ADC_MIC_TASK_STACK_SIZE
int "Task Stack Size"
default 3072
range 2048 8192
help
Stack size for the ADC mic worker task.
config ADC_MIC_TASK_CORE
int "Task Core"
default -1
range -1 1
help
Core for the ADC mic worker task, -1 means no affinity.
depends on SOC_CPU_CORES_NUM > 1 && !FREERTOS_UNICORE
endmenu

View File

@@ -0,0 +1,21 @@
[![Component Registry](https://components.espressif.com/components/espressif/adc_mic/badge.svg)](https://components.espressif.com/components/espressif/adc_mic)
# Component: ADC Mic
The **ADC MIC** can collect analog microphone data through the ADC.
Currently supported features:
* Supports single-channel/multi-channel ADC audio sampling.
* Compliant with the esp_codec_dev architecture.
## Add component to your project
Please use the component manager command `add-dependency` to add the `adc_mic` to your project's dependency, during the `CMake` step the component will be downloaded automatically
```
idf.py add-dependency "espressif/adc_mic=*"
```
## Known Issues
* In IDF versions lower than ``5.2``, the internal ring buffer does not automatically clear old data when full. Please ensure old data is cleared in time or manually refresh the buffer.

View File

@@ -0,0 +1,397 @@
/*
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include "esp_log.h"
#include "esp_check.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "audio_codec_data_if.h"
#include "adc_mic.h"
#include "esp_codec_dev_defaults.h"
#include "esp_idf_version.h"
#include "soc/soc_caps.h"
static const char *TAG = "adc_if";
#ifndef CONFIG_ADC_MIC_TASK_CORE
#define CONFIG_ADC_MIC_TASK_CORE tskNO_AFFINITY
#endif
typedef struct {
audio_codec_data_if_t base;
adc_continuous_handle_t handle;
adc_unit_t unit_id; /*!< ADC unit */
adc_atten_t atten; /*!< ADC attenuation */
bool if_config_by_user; /*!< If the ADC is configured by the user, the internal initialization will not be performed. */
bool is_open;
bool enable;
uint8_t *adc_channel;
uint8_t adc_channel_num;
uint32_t conv_frame_size;
#if SOC_ADC_DIGI_RESULT_BYTES != 2
uint32_t *conv_data;
#endif
TaskHandle_t worker_task_handle;
QueueHandle_t worker_queue;
} adc_data_t;
/* Actions handled by the worker task to ensure all start/stop are executed in the same task */
typedef enum {
ADC_MIC_ACTION_NONE = 0,
ADC_MIC_ACTION_ENABLE,
ADC_MIC_ACTION_DISABLE,
ADC_MIC_ACTION_DESTROY,
} adc_mic_action_t;
typedef struct {
adc_mic_action_t action;
TaskHandle_t msg_sender_task; /* Notify this task when action is handled */
int *result_ptr; /* Where to store operation result (ESP_CODEC_DEV_OK/ERR) */
} adc_mic_msg_t;
static void adc_mic_worker_task(void *arg)
{
adc_data_t *adc_data = (adc_data_t *)arg;
adc_mic_msg_t msg;
while (true) {
if (xQueueReceive(adc_data->worker_queue, &msg, portMAX_DELAY)) {
switch (msg.action) {
case ADC_MIC_ACTION_ENABLE: {
esp_err_t ret = ESP_OK;
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
ret = adc_continuous_flush_pool(adc_data->handle);
if (ret != ESP_OK) {
if (msg.result_ptr) {
*msg.result_ptr = ESP_CODEC_DEV_DRV_ERR;
}
break;
}
#endif
ret = adc_continuous_start(adc_data->handle);
if (ret == ESP_OK) {
adc_data->enable = true;
if (msg.result_ptr) {
*msg.result_ptr = ESP_CODEC_DEV_OK;
}
} else {
if (msg.result_ptr) {
*msg.result_ptr = ESP_CODEC_DEV_DRV_ERR;
}
}
break;
}
case ADC_MIC_ACTION_DISABLE: {
esp_err_t ret = adc_continuous_stop(adc_data->handle);
if (ret == ESP_OK) {
adc_data->enable = false;
if (msg.result_ptr) {
*msg.result_ptr = ESP_CODEC_DEV_OK;
}
} else {
if (msg.result_ptr) {
*msg.result_ptr = ESP_CODEC_DEV_DRV_ERR;
}
}
break;
}
case ADC_MIC_ACTION_DESTROY: {
if (adc_data->enable) {
(void)adc_continuous_stop(adc_data->handle);
adc_data->enable = false;
}
adc_data->worker_task_handle = NULL;
if (msg.msg_sender_task) {
xTaskNotifyGive(msg.msg_sender_task);
}
vTaskDelete(NULL);
assert(0); /* should not reach here */
}
case ADC_MIC_ACTION_NONE:
default:
break;
}
if (msg.msg_sender_task) {
xTaskNotifyGive(msg.msg_sender_task);
}
}
}
}
static esp_err_t adc_channel_config(adc_data_t *adc_data, uint8_t *channel, uint8_t channel_num, int sample_freq_hz, adc_atten_t atten)
{
adc_digi_convert_mode_t conv_mode = adc_data->unit_id == ADC_UNIT_1 ? ADC_CONV_SINGLE_UNIT_1 : ADC_CONV_SINGLE_UNIT_2;
adc_continuous_config_t dig_cfg = {
.sample_freq_hz = sample_freq_hz * channel_num,
.conv_mode = conv_mode,
};
/**
* @brief For ESP32 and ESP32-S2, only `type1` can obtain 12-bit data.
*
*/
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
dig_cfg.format = ADC_DIGI_OUTPUT_FORMAT_TYPE1;
#else
dig_cfg.format = ADC_DIGI_OUTPUT_FORMAT_TYPE2;
#endif
adc_digi_pattern_config_t *adc_pattern = calloc(channel_num, sizeof(adc_digi_pattern_config_t));
ESP_RETURN_ON_FALSE(adc_pattern != NULL, ESP_ERR_NO_MEM, TAG, "adc_pattern is NULL");
dig_cfg.pattern_num = channel_num;
for (int i = 0; i < dig_cfg.pattern_num; i++) {
adc_pattern[i].atten = atten;
adc_pattern[i].channel = channel[i];
adc_pattern[i].unit = adc_data->unit_id;
adc_pattern[i].bit_width = SOC_ADC_DIGI_MAX_BITWIDTH;
}
dig_cfg.adc_pattern = adc_pattern;
esp_err_t ret = adc_continuous_config(adc_data->handle, &dig_cfg);
ESP_RETURN_ON_ERROR(ret, TAG, "adc_continuous_config failed");
free(adc_pattern);
return ESP_OK;
}
static bool _adc_data_is_open(const audio_codec_data_if_t *h)
{
adc_data_t *adc_data = (adc_data_t *) h;
if (adc_data) {
return adc_data->is_open;
}
return false;
}
static int _adc_data_enable(const audio_codec_data_if_t *h, esp_codec_dev_type_t dev_type, bool enable)
{
adc_data_t *adc_data = (adc_data_t *) h;
ESP_RETURN_ON_FALSE(adc_data != NULL, ESP_CODEC_DEV_INVALID_ARG, TAG, "adc_data is NULL");
ESP_RETURN_ON_FALSE(adc_data->is_open, ESP_CODEC_DEV_WRONG_STATE, TAG, "adc_data is not open");
ESP_RETURN_ON_FALSE(dev_type == ESP_CODEC_DEV_TYPE_IN, ESP_CODEC_DEV_INVALID_ARG, TAG, "Invalid device type");
// Route start/stop into the dedicated worker task to avoid cross-task mutex issues
ESP_RETURN_ON_FALSE(adc_data->worker_queue != NULL, ESP_CODEC_DEV_WRONG_STATE, TAG, "worker not initialized");
int op_result = ESP_CODEC_DEV_OK;
adc_mic_msg_t msg = {
.action = enable ? ADC_MIC_ACTION_ENABLE : ADC_MIC_ACTION_DISABLE,
.msg_sender_task = xTaskGetCurrentTaskHandle(),
.result_ptr = &op_result,
};
BaseType_t ok = xQueueSend(adc_data->worker_queue, &msg, portMAX_DELAY);
ESP_RETURN_ON_FALSE(ok == pdTRUE, ESP_CODEC_DEV_DRV_ERR, TAG, "worker queue send failed");
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
return op_result;
}
/**
* @brief Read ADC data from the continuous ADC interface.
*
* This function reads ADC data from the continuous ADC interface and processes the raw values.
* The data is left-shifted to amplify the audio signal. The function ensures that the requested
* read size is valid and properly aligned with the ADC data format.
*
* @param h Pointer to the audio codec data interface handle.
* @param data Pointer to the buffer where the ADC data will be stored.
* @param size Number of bytes to read, must be a multiple of SOC_ADC_DIGI_DATA_BYTES_PER_CONV.
* @return int Returns ESP_CODEC_DEV_OK on success, or an error code on failure.
*/
static int _adc_data_read(const audio_codec_data_if_t *h, uint8_t *data, int size)
{
adc_data_t *adc_data = (adc_data_t *) h;
ESP_RETURN_ON_FALSE(adc_data != NULL, ESP_CODEC_DEV_INVALID_ARG, TAG, "adc_data is NULL");
ESP_RETURN_ON_FALSE(adc_data->is_open, ESP_CODEC_DEV_WRONG_STATE, TAG, "adc_data is not open");
if (size % SOC_ADC_DIGI_DATA_BYTES_PER_CONV != 0) {
ESP_LOGE(TAG, "Invalid size, must be multiple of %d", SOC_ADC_DIGI_DATA_BYTES_PER_CONV);
}
ESP_LOGV(TAG, "adc mic read %d bytes", size);
// Note: must be 16bit
uint32_t ret_num = 0;
int left_size = size;
int cnt = 0;
#if SOC_ADC_DIGI_RESULT_BYTES == 2
while (left_size > 0) {
int request_size = left_size > adc_data->conv_frame_size ? adc_data->conv_frame_size : left_size;
adc_continuous_read(adc_data->handle, &data[cnt], request_size, &ret_num, portMAX_DELAY);
adc_digi_output_data_t *buffer = (adc_digi_output_data_t *)&data[cnt];
uint16_t *p = (uint16_t *)&data[cnt];
size_t item_count = ret_num / sizeof(adc_digi_output_data_t);
for (int i = 0; i < item_count; i++) {
uint16_t raw_value = buffer[i].val;
// Left shift to amplify audio.
p[i] = (raw_value << CONFIG_ADC_MIC_APPLY_GAIN) - CONFIG_ADC_MIC_OFFSET;
}
cnt += ret_num;
left_size -= ret_num;
}
#else
while (left_size > 0) {
int request_size = left_size > adc_data->conv_frame_size ? adc_data->conv_frame_size : left_size;
adc_continuous_read(adc_data->handle, (uint8_t *)adc_data->conv_data, request_size * 2, &ret_num, portMAX_DELAY);
adc_digi_output_data_t *buffer = (adc_digi_output_data_t *)adc_data->conv_data;
uint16_t *p = (uint16_t *)&data[cnt];
size_t item_count = ret_num / sizeof(adc_digi_output_data_t);
for (int i = 0; i < item_count; i++) {
uint16_t raw_value = buffer[i].val & 0xFFFF;
// Left shift to amplify audio.
p[i] = (raw_value << CONFIG_ADC_MIC_APPLY_GAIN) - CONFIG_ADC_MIC_OFFSET;
}
cnt += ret_num / 2;
left_size -= ret_num / 2;
}
#endif
return ESP_CODEC_DEV_OK;
}
static int _adc_data_close(const audio_codec_data_if_t *h)
{
adc_data_t *adc_data = (adc_data_t *) h;
ESP_RETURN_ON_FALSE(adc_data != NULL, ESP_CODEC_DEV_INVALID_ARG, TAG, "adc_data is NULL");
ESP_RETURN_ON_FALSE(adc_data->enable == false, ESP_CODEC_DEV_WRONG_STATE, TAG, "adc_data is enable, please disable it first");
// Ensure worker task is destroyed before deinit
if (adc_data->worker_queue && adc_data->worker_task_handle) {
adc_mic_msg_t msg = {
.action = ADC_MIC_ACTION_DESTROY,
.msg_sender_task = xTaskGetCurrentTaskHandle(),
.result_ptr = NULL,
};
(void)xQueueSend(adc_data->worker_queue, &msg, portMAX_DELAY);
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
vQueueDelete(adc_data->worker_queue);
adc_data->worker_queue = NULL;
}
if (!adc_data->if_config_by_user) {
adc_continuous_deinit(adc_data->handle);
}
#if SOC_ADC_DIGI_RESULT_BYTES != 2
if (adc_data->conv_data) {
free(adc_data->conv_data);
}
#endif
if (adc_data->adc_channel) {
free(adc_data->adc_channel);
}
// adc_data will be deleted by the esp_code_dev interface.
return ESP_CODEC_DEV_OK;
}
/**
* @brief Configure the format of ADC data.
*
* This function sets the sample format for the ADC data interface. It ensures that the ADC is properly configured
* with the expected sample rate, channel count, and bit depth. Before setting the format, the ADC should be stopped.
*
* @note adc_data only supports 16-bit samples
*
* @param h Pointer to the audio codec data interface handle.
* @param dev_type Type of the codec device (not used in this function).
* @param fs Pointer to the sample format structure, specifying sample rate, channels, and bit depth.
* @return int Returns ESP_CODEC_DEV_OK on success, or an error code on failure.
*/
static int _adc_data_set_fmt(const audio_codec_data_if_t *h, esp_codec_dev_type_t dev_type, esp_codec_dev_sample_info_t *fs)
{
adc_data_t *adc_data = (adc_data_t *) h;
ESP_RETURN_ON_FALSE(adc_data != NULL, ESP_CODEC_DEV_INVALID_ARG, TAG, "adc_data is NULL");
ESP_RETURN_ON_FALSE(adc_data->is_open, ESP_CODEC_DEV_WRONG_STATE, TAG, "adc_data is not open");
ESP_RETURN_ON_FALSE(fs->bits_per_sample == 16, ESP_CODEC_DEV_INVALID_ARG, TAG, "adc_data only support 16-bit samples");
ESP_RETURN_ON_FALSE(fs->channel == adc_data->adc_channel_num, ESP_CODEC_DEV_INVALID_ARG, TAG, "channel num not match");
esp_err_t ret = adc_channel_config(adc_data, adc_data->adc_channel, adc_data->adc_channel_num, fs->sample_rate, adc_data->atten);
return ret == ESP_OK ? ESP_CODEC_DEV_OK : ESP_CODEC_DEV_DRV_ERR;
}
const audio_codec_data_if_t *audio_codec_new_adc_data(audio_codec_adc_cfg_t *adc_cfg)
{
ESP_LOGI(TAG, "ADC MIC Version: %d.%d.%d", ADC_MIC_VER_MAJOR, ADC_MIC_VER_MINOR, ADC_MIC_VER_PATCH);
ESP_RETURN_ON_FALSE(adc_cfg != NULL, NULL, TAG, "adc_cfg is NULL");
esp_err_t ret = ESP_OK;
adc_data_t *adc_data = (adc_data_t *)calloc(1, sizeof(adc_data_t));
ESP_RETURN_ON_FALSE(adc_data != NULL, NULL, TAG, "calloc failed");
adc_data->conv_frame_size = adc_cfg->conv_frame_size;
/**
* @brief If the conversion result takes up 4 bytes, we need to use a temporary
* buffer for the conversion instead of copying it directly into the provided
* buffer, as this would result in some efficiency loss.
*/
#if SOC_ADC_DIGI_RESULT_BYTES != 2
adc_data->conv_data = calloc(1, adc_data->conv_frame_size * 2);
ESP_GOTO_ON_FALSE(adc_data->conv_data != NULL, ESP_CODEC_DEV_NO_MEM, err, TAG, "calloc failed");
#endif
adc_data->adc_channel = malloc(adc_cfg->adc_channel_num * sizeof(uint8_t));
ESP_GOTO_ON_FALSE(adc_data->adc_channel != NULL, ESP_CODEC_DEV_NO_MEM, err, TAG, "malloc failed");
adc_data->adc_channel_num = adc_cfg->adc_channel_num;
if (adc_cfg->handle == NULL) {
adc_continuous_handle_cfg_t adc_config = {
.max_store_buf_size = adc_cfg->max_store_buf_size,
.conv_frame_size = adc_cfg->conv_frame_size,
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 0)
.flags.flush_pool = true,
#endif
};
ret = adc_continuous_new_handle(&adc_config, &adc_data->handle);
ESP_GOTO_ON_FALSE(ret == ESP_OK, ESP_CODEC_DEV_DRV_ERR, err, TAG, "adc_continuous_new_handle failed");
adc_data->if_config_by_user = false;
} else {
adc_data->handle = *adc_cfg->handle;
adc_data->if_config_by_user = true;
}
adc_data->unit_id = adc_cfg->unit_id;
adc_data->atten = adc_cfg->atten;
memcpy(adc_data->adc_channel, adc_cfg->adc_channel_list, adc_cfg->adc_channel_num * sizeof(uint8_t));
adc_channel_config(adc_data, adc_data->adc_channel, adc_data->adc_channel_num, adc_cfg->sample_rate_hz, adc_cfg->atten);
adc_data->base.open = NULL;
adc_data->base.is_open = _adc_data_is_open;
adc_data->base.enable = _adc_data_enable;
adc_data->base.read = _adc_data_read;
adc_data->base.write = NULL;
adc_data->base.set_fmt = _adc_data_set_fmt;
adc_data->base.close = _adc_data_close;
adc_data->is_open = true;
adc_data->worker_queue = xQueueCreate(8, sizeof(adc_mic_msg_t));
if (adc_data->worker_queue == NULL) {
goto err;
}
BaseType_t task_ok = xTaskCreatePinnedToCore(
adc_mic_worker_task,
"adc_mic_task",
CONFIG_ADC_MIC_TASK_STACK_SIZE,
adc_data,
CONFIG_ADC_MIC_TASK_PRIORITY,
&adc_data->worker_task_handle,
(BaseType_t) CONFIG_ADC_MIC_TASK_CORE
);
if (task_ok != pdPASS) {
goto err;
}
return &adc_data->base;
err:
if (adc_data) {
if (adc_data->worker_queue) {
vQueueDelete(adc_data->worker_queue);
}
free(adc_data);
}
return NULL;
}

View File

@@ -0,0 +1,84 @@
/*
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef ADC_MIC_H
#define ADC_MIC_H
#include <stdint.h>
#include "audio_codec_data_if.h"
#include "esp_adc/adc_continuous.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DEFAULT_AUDIO_CODEC_ADC_MONO_CFG(_channel, _sample) \
{ \
.handle = NULL, \
.max_store_buf_size = 1024 * 2, \
.conv_frame_size = 1024, \
.unit_id = ADC_UNIT_1, \
.adc_channel_list = ((uint8_t[]){_channel}), \
.adc_channel_num = 1, \
.sample_rate_hz = _sample, \
}
#define DEFAULT_AUDIO_CODEC_ADC_STEREO_CFG(_channel_l, _channel_r,_sample) \
{ \
.handle = NULL, \
.max_store_buf_size = 1024 * 2, \
.conv_frame_size = 1024, \
.unit_id = ADC_UNIT_1, \
.adc_channel_list = ((uint8_t[]){_channel_l, _channel_r}), \
.adc_channel_num = 1, \
.atten = ADC_ATTEN_DB_0, \
.sample_rate_hz = _sample, \
}
/**************************************************************************************************
*
* ADC MIC
*
* After create a adc mic driver, it can be accessed with stdio functions ie.:
* \code{.c}
* const audio_codec_data_if_t *adc_if = audio_codec_new_adc_data(&cfg);
* esp_codec_dev_cfg_t codec_dev_cfg = {
* .dev_type = ESP_CODEC_DEV_TYPE_IN,
* .data_if = adc_if,
* };
* esp_codec_dev_handle_t dev = esp_codec_dev_new(&codec_dev_cfg);
* esp_codec_dev_open(dev, &fs);
* esp_codec_dev_read(dev, audio_buffer, buffer_len);
* \endcode
**************************************************************************************************/
/**
* @brief codec adc configuration
*
*/
typedef struct {
adc_continuous_handle_t *handle; /*!< Type of adc continuous mode driver handle, if NULL will create new one internal, else will use the handle */
size_t max_store_buf_size; /*!< Max length of the conversion results that driver can store, in bytes. */
size_t conv_frame_size; /*!< Conversion frame size, in bytes. This should be in multiples of `SOC_ADC_DIGI_DATA_BYTES_PER_CONV` */
adc_unit_t unit_id; /*!< ADC unit */
uint8_t *adc_channel_list; /*!< Channel of ADC */
uint8_t adc_channel_num; /*!< Number of channels */
adc_atten_t atten; /*!< It should correspond to the actual range, with 0dB attenuation having the least ripple. */
uint32_t sample_rate_hz; /*!< Sample rate of ADC */
} audio_codec_adc_cfg_t;
/**
* @brief Initialize codec adc.
*
* @param adc_cfg pointer of configuration struct
* @return const audio_codec_data_if_t* adc data interface.
*/
const audio_codec_data_if_t *audio_codec_new_adc_data(audio_codec_adc_cfg_t *adc_cfg);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,14 @@
dependencies:
espressif/cmake_utilities: '*'
espressif/esp_codec_dev:
version: ^1.3.*
idf: '>=5.0'
description: ADC mic input driver for ESP32 Series socs
documentation: https://docs.espressif.com/projects/esp-iot-solution/en/latest/audio/adc_mic.html
issues: https://github.com/espressif/esp-iot-solution/issues
repository: git://github.com/espressif/esp-iot-solution.git
repository_info:
commit_sha: af9f2435ac94a70ad6d21b164e1d52d23d3c424a
path: components/audio/adc_mic
url: https://github.com/espressif/esp-iot-solution/tree/master/components/audio/adc_mic
version: 0.2.1

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,9 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/tools/unit-test-app/components"
"../../adc_mic")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(adc_mic_test)

View File

@@ -0,0 +1,3 @@
idf_component_register(SRC_DIRS "."
INCLUDE_DIRS "."
WHOLE_ARCHIVE)

View File

@@ -0,0 +1,137 @@
/*
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "unity.h"
#include "esp_log.h"
#include "adc_mic.h"
#include "esp_codec_dev.h"
static const char *TAG = "adc_mic_test";
TEST_CASE("adc_mic_test_mono", "[adc_mic][mono]")
{
audio_codec_adc_cfg_t cfg = DEFAULT_AUDIO_CODEC_ADC_MONO_CFG(ADC_CHANNEL_0, 16000);
const audio_codec_data_if_t *adc_if = audio_codec_new_adc_data(&cfg);
esp_codec_dev_cfg_t codec_dev_cfg = {
.dev_type = ESP_CODEC_DEV_TYPE_IN,
.data_if = adc_if,
};
esp_codec_dev_handle_t dev = esp_codec_dev_new(&codec_dev_cfg);
TEST_ASSERT(dev);
esp_codec_dev_sample_info_t fs = {
.sample_rate = 16000,
.channel = 1,
.bits_per_sample = 16,
};
int ret = esp_codec_dev_open(dev, &fs);
TEST_ASSERT(ret == 0);
uint16_t *audio_buffer = malloc(16000 * sizeof(uint16_t));
assert(audio_buffer);
while (1) {
ret = esp_codec_dev_read(dev, audio_buffer, sizeof(uint16_t) * 16000);
ESP_LOGI(TAG, "ret: %d, esp_codec_dev_read len: %d\n", ret, sizeof(uint16_t) * 16000);
}
}
TEST_CASE("adc_mic_test memory leak", "[adc_mic][memory_leak]")
{
audio_codec_adc_cfg_t cfg = DEFAULT_AUDIO_CODEC_ADC_MONO_CFG(ADC_CHANNEL_0, 16000);
const audio_codec_data_if_t *adc_if = audio_codec_new_adc_data(&cfg);
esp_codec_dev_cfg_t codec_dev_cfg = {
.dev_type = ESP_CODEC_DEV_TYPE_IN,
.data_if = adc_if,
};
esp_codec_dev_handle_t dev = esp_codec_dev_new(&codec_dev_cfg);
TEST_ASSERT(dev);
esp_codec_dev_delete(dev);
audio_codec_delete_data_if(adc_if);
}
typedef struct {
esp_codec_dev_handle_t dev;
esp_codec_dev_sample_info_t fs;
TaskHandle_t partner;
int loops;
} cross_task_ctx_t;
static void task_open_then_wait(void *arg)
{
cross_task_ctx_t *ctx = (cross_task_ctx_t *)arg;
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
for (int i = 0; i < ctx->loops; ++i) {
TEST_ASSERT_EQUAL(0, esp_codec_dev_open(ctx->dev, &ctx->fs));
xTaskNotifyGive(ctx->partner);
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
}
vTaskDelete(NULL);
}
static void task_wait_then_close(void *arg)
{
cross_task_ctx_t *ctx = (cross_task_ctx_t *)arg;
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
for (int i = 0; i < ctx->loops; ++i) {
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
TEST_ASSERT_EQUAL(0, esp_codec_dev_close(ctx->dev));
xTaskNotifyGive(ctx->partner);
}
vTaskDelete(NULL);
}
TEST_CASE("adc_mic_cross_task_enable_disable", "[adc_mic][cross_task]")
{
audio_codec_adc_cfg_t cfg = DEFAULT_AUDIO_CODEC_ADC_MONO_CFG(ADC_CHANNEL_0, 16000);
const audio_codec_data_if_t *adc_if = audio_codec_new_adc_data(&cfg);
esp_codec_dev_cfg_t codec_dev_cfg = {
.dev_type = ESP_CODEC_DEV_TYPE_IN,
.data_if = adc_if,
};
esp_codec_dev_handle_t dev = esp_codec_dev_new(&codec_dev_cfg);
TEST_ASSERT(dev);
esp_codec_dev_sample_info_t fs = {
.sample_rate = 16000,
.channel = 1,
.bits_per_sample = 16,
};
cross_task_ctx_t a = {
.dev = dev,
.fs = fs,
.partner = NULL,
.loops = 10,
};
cross_task_ctx_t b = a;
TaskHandle_t taskA = NULL;
TaskHandle_t taskB = NULL;
xTaskCreate(task_open_then_wait, "t_open", 3072, &a, 3, &taskA);
xTaskCreate(task_wait_then_close, "t_close", 3072, &b, 3, &taskB);
a.partner = taskB;
b.partner = taskA;
xTaskNotifyGive(taskA);
xTaskNotifyGive(taskB);
while (eTaskGetState(taskA) != eDeleted || eTaskGetState(taskB) != eDeleted) {
vTaskDelay(pdMS_TO_TICKS(10));
}
esp_codec_dev_delete(dev);
audio_codec_delete_data_if(adc_if);
}

View File

@@ -0,0 +1,41 @@
/*
* SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "unity.h"
#include "unity_test_runner.h"
#include "unity_test_utils_memory.h"
#include "esp_heap_caps.h"
#include "sdkconfig.h"
#define LEAKS (400)
void setUp(void)
{
unity_utils_record_free_mem();
}
void tearDown(void)
{
unity_utils_evaluate_leaks_direct(LEAKS);
}
void app_main(void)
{
// _____ _____ __ __ _____ _____
// /\ | __ \ / ____| | \/ |_ _/ ____|
// / \ | | | | | | \ / | | || |
// / /\ \ | | | | | | |\/| | | || |
// / ____ \| |__| | |____ | | | |_| || |____
// /_/ \_\_____/ \_____| |_| |_|_____\_____|
printf(" _____ _____ __ __ _____ _____\n");
printf(" /\\ | __ \\ / ____| | \\/ |_ _/ ____|\n");
printf(" / \\ | | | | | | \\ / | | || |\n");
printf(" / /\\ \\ | | | | | | |\\/| | | || |\n");
printf(" / ____ \\| |__| | |____ | | | |_| || |____\n");
printf(" /_/ \\_\\_____/ \\_____| |_| |_|_____|_____|\n");
unity_run_menu();
}

View File

@@ -0,0 +1,6 @@
# This file was generated using idf.py save-defconfig. It can be edited manually.
# Espressif IoT Development Framework (ESP-IDF) 5.4.0 Project Minimal Configuration
#
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_ESP_TASK_WDT_EN=n
CONFIG_FREERTOS_HZ=1000