/*
* SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Unlicense OR CC0-1.0
*/
/* I2S Digital Microphone Recording Example */
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "sdkconfig.h"
#include "esp_log.h"
#include "esp_err.h"
#include "esp_system.h"
#include "esp_vfs_fat.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/i2s_pdm.h"
#include "driver/gpio.h"
#include "driver/spi_common.h"
#include "sdkconfig.h"
static const char *TAG = "pdm_rec_example";
#define SPI_DMA_CHAN SPI_DMA_CH_AUTO
#define NUM_CHANNELS (1) // For mono recording only!
#define SAMPLE_SIZE (16 * 1024)
#define SAMPLE_RATE 44100
#define BYTE_RATE (SAMPLE_RATE * (16 / 8)) * 1
i2s_chan_handle_t rx_handle = NULL;
static int16_t i2s_readraw_buff[SAMPLE_SIZE];
size_t bytes_read;
// STD simplex pins
#define EXAMPLE_I2S_BCLK_IO1 GPIO_NUM_2 // I2S bit clock io number
#define EXAMPLE_I2S_WS_IO1 GPIO_NUM_3 // I2S word select io number
#define EXAMPLE_I2S_DOUT_IO1 GPIO_NUM_4 // I2S data out io number
#define EXAMPLE_I2S_DIN_IO1 GPIO_NUM_5 // I2S data in io number
#define EXAMPLE_I2S_CLK_GPIO GPIO_NUM_16
#define EXAMPLE_I2S_DATA_GPIO EXAMPLE_I2S_DIN_IO1
void init_microphone(void)
{
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER);
ESP_ERROR_CHECK(i2s_new_channel(&chan_cfg, NULL, &rx_handle));
i2s_pdm_rx_config_t pdm_rx_cfg = {
.clk_cfg = I2S_PDM_RX_CLK_DEFAULT_CONFIG(SAMPLE_RATE),
/* The default mono slot is the left slot (whose 'select pin' of the PDM microphone is pulled down) */
.slot_cfg = I2S_PDM_RX_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_MONO),
.gpio_cfg = {
.clk = EXAMPLE_I2S_CLK_GPIO,
.din = EXAMPLE_I2S_DATA_GPIO,
.invert_flags = {
.clk_inv = false,
},
},
};
ESP_ERROR_CHECK(i2s_channel_init_pdm_rx_mode(rx_handle, &pdm_rx_cfg));
ESP_ERROR_CHECK(i2s_channel_enable(rx_handle));
}
void app_main() {
printf("PDM microphone recording example start\n--------------------------------------\n");
// Acquire a I2S PDM channel for the PDM digital microphone
init_microphone();
// Start Recording
// Stop I2S driver and destroy
ESP_ERROR_CHECK(i2s_channel_disable(rx_handle));
ESP_ERROR_CHECK(i2s_del_channel(rx_handle));
}