ESP32 Sample Service

        // SampleBuffferInitI2S
	// Do the initial setup required if we're going to capture the audio with I2S

	//i2s number
	#define EXAMPLE_I2S_NUM           (I2S_NUM_0)
	//i2s sample rate
	//enable display buffer for debug
	#define EXAMPLE_I2S_BUF_DEBUG     (0)
	//I2S read buffer length
	//I2S built-in ADC unit
	#define I2S_ADC_UNIT              ADC_UNIT_1
	//I2S built-in ADC channel
	#define I2S_ADC_CHANNEL           ADC1_CHANNEL_0

	//flash record size, for recording 5 second
	void SampleBufferInitI2S()
		i2s_config_t i2s_config;
		i2s_config.mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_RX | I2S_MODE_ADC_BUILT_IN);
    	        i2s_config.sample_rate = SAMPLING_FREQUENCY;            
    	        i2s_config.dma_buf_len = MAX_SAMPLES;                   
    	        i2s_config.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT;
    	        i2s_config.channel_format = I2S_CHANNEL_FMT_ONLY_LEFT;  
    	        i2s_config.use_apll = false,
    	        i2s_config.communication_format = I2S_COMM_FORMAT_I2S_MSB;
    	        i2s_config.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1;
    	        i2s_config.dma_buf_count = 2;

		//install and start i2s driver

		ESP_ERROR_CHECK( adc_gpio_init(ADC_UNIT_1, ADC_CHANNEL_0) );
		ESP_ERROR_CHECK( i2s_driver_install(EXAMPLE_I2S_NUM, &i2s_config,  0, NULL) );
		ESP_ERROR_CHECK( i2s_set_adc_mode(I2S_ADC_UNIT, I2S_ADC_CHANNEL) );		


	void FillBufferI2S()
		uint16_t byteBuffer[MAX_SAMPLES];

		if (IsBufferFull())
			Serial.printf("BUG: FillBUfferI2S found buffer already full.");
		size_t bytesRead = 0;
    	        ESP_ERROR_CHECK( i2s_adc_enable(EXAMPLE_I2S_NUM) );
                ESP_ERROR_CHECK( i2s_read(EXAMPLE_I2S_NUM, (void*) byteBuffer, sizeof(byteBuffer), &bytesRead, portMAX_DELAY) );
	        ESP_ERROR_CHECK( i2s_adc_disable(EXAMPLE_I2S_NUM) );

		_cSamples = _MaxSamples;
		if (bytesRead != sizeof(byteBuffer))
			Serial.printf("Could only read %u byttes of %u in FillBufferI2S()\n", bytesRead, sizeof(byteBuffer));

		for (int i = 0; i < ARRAYSIZE(byteBuffer); i++)
			_vReal[i] = byteBuffer[i];

		//for (int i = 0; i < 128; i++)
		//	Serial.printf("%d, %f\n", i, _vReal[i]);

		_cSamples = MAX_SAMPLES;


Need to try this (from Reddit): ADC configured as an I2S peripheral that writes directly to system memory (DMA).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s