Hello,
I'm trying to play a microphone analog input into my IS2 earphones using my ESP32, but something is incorrect in my code.
I'm a bit confused into the conversion of input / output. I hear very small high pitch sounds once in a while in the earphones but that's it. I can confirm the pin configuration is correct.
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "driver/i2s_std.h"
#include "esp_adc/adc_continuous.h"
#include "esp_err.h"
#include "esp_log.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/ringbuf.h"
adc_continuous_handle_t handle = NULL;
i2s_chan_handle_t tx_chan = NULL;
#define BUFFER_SIZE 512 // Microphone buffer size
#define SAMPLE_RATE 20000 // Speaker sample rate
#define ADC_SAMPLE_RATE 20000 // Microphone sample rate
static const char *TAG = "AudioLoop";
void init_microphone() {
adc_continuous_handle_cfg_t adc_config = {
.max_store_buf_size = 4 * BUFFER_SIZE,
.conv_frame_size = BUFFER_SIZE,
};
ESP_ERROR_CHECK(adc_continuous_new_handle(&adc_config, &handle));
adc_continuous_config_t dig_cfg = {
.sample_freq_hz = ADC_SAMPLE_RATE,
.conv_mode = ADC_CONV_SINGLE_UNIT_1,
.format = ADC_DIGI_OUTPUT_FORMAT_TYPE1,
.pattern_num = 1,
};
adc_digi_pattern_config_t adc_pattern = {
.atten = ADC_ATTEN_DB_0,
.channel = ADC_CHANNEL_6, // GPIO 34
.unit = ADC_UNIT_1,
.bit_width = ADC_BITWIDTH_12,
};
dig_cfg.adc_pattern = &adc_pattern;
ESP_ERROR_CHECK(adc_continuous_config(handle, &dig_cfg));
ESP_ERROR_CHECK(adc_continuous_start(handle));
}
void init_speaker() {
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_1, I2S_ROLE_MASTER);
chan_cfg.auto_clear = true;
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(SAMPLE_RATE),
.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = 26,
.ws = 25,
.dout = 22,
.din = I2S_GPIO_UNUSED,
.invert_flags = {
.mclk_inv = false,
.bclk_inv = false,
.ws_inv = false,
},
},
};
ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, &tx_chan, NULL));
ESP_ERROR_CHECK(i2s_channel_init_std_mode(tx_chan, &std_cfg));
ESP_ERROR_CHECK(i2s_channel_enable(tx_chan));
}
void app_main() {
ESP_LOGI(TAG, "Initializing audio loop");
// Initialize microphone and speaker
init_microphone();
init_speaker();
uint8_t mic_in[BUFFER_SIZE];
uint32_t mic_bytes_read;
int16_t speaker_out[BUFFER_SIZE];
while (1) {
ESP_ERROR_CHECK(adc_continuous_read(handle, mic_in, BUFFER_SIZE, &mic_bytes_read, portMAX_DELAY));
for (size_t i = 0; i < mic_bytes_read; i++) {
adc_digi_output_data_t *p = (adc_digi_output_data_t *)&mic_in[i * sizeof(adc_digi_output_data_t)];
speaker_out[i] = p->type1.data;
ESP_LOGI(TAG, "data = %" PRId16 "", p->type1.data);
}
size_t bytes_written;
ESP_ERROR_CHECK(i2s_channel_write(tx_chan, speaker_out, BUFFER_SIZE, &bytes_written, portMAX_DELAY));
}
}
Thanks in advance if you can help out !