Code flow in Microphone examples

I had a few questions on the code flow in the Arduino Microphone example (the non-continuous one).

In the pdm_data_ready_inference_callback() function, which is called when there is new microphone samples ready, it looks like samples are constantly being written to the inference buffer. This happens even after a sample has been collected and is being passed off for inference.

Instead of if (record_ready == true || inference.buf_ready == 1) would it be better to have if ( record_ready == true && inference.buf_ready == 0) so that the inference buffer is only written to during the audio capture phase at the beginning of the loop. If you don’t do this, it seems like the buffer would be modified while inference is being performed and some of collected data will be overwritten with new data.

Also - in the if(inference.buf_count >= inference.n_samples) section, should a break be added? Otherwise the for loop will keep going and write outside the memory allocated for the buffer.

I maybe missing some underlying mechanics, so I wanted to check.

static void pdm_data_ready_inference_callback(void)
{
    int bytesAvailable = PDM.available();

    // read into the sample buffer
    int bytesRead = PDM.read((char *)&sampleBuffer[0], bytesAvailable);

    if (record_ready == true || inference.buf_ready == 1) {
        for(int i = 0; i < bytesRead>>1; i++) {
            inference.buffer[inference.buf_count++] = sampleBuffer[i];

            if(inference.buf_count >= inference.n_samples) {
                inference.buf_count = 0;
                inference.buf_ready = 1;
            }
        }
    }
}

Hi Robotastic,

Thanks for your feedback! Both points you bring up are valid.

if ( record_ready == true && inference.buf_ready == 0) should be used to not overwrite the sample buffer. For this example record_ready can be removed entirely since the PDM shouldn’t start if somethings goes wrong.
And yes, a break should be added in the for loop to prevent writing samples at the start of the buffer again.

Data won’t be written outside of memory, since the buffer pointer inference.buf_count is reset to 0

I will update the example.

Thanks for checking @Arjan ! It may not impact the accuracy, but I was saving the inference buffer to an SD card and was getting weird sounding files.

Good point on there not being a problem of memory being written outside the buffer!