[Defect] PDM Gain example incorrect

Hi,

I’ve found a defect in the example code for setting the Gain on the PDM microphone.

The setGain method is described here Arduino - PDMsetGain

Where first the gain is set, then PDM begin is called.

  // optionally set the gain, defaults to 20
  PDM.setGain(30);

  // initialize PDM with:
  // - one channel (mono mode)
  // - a 16 kHz sample rate
  if (!PDM.begin(1, 16000)) {
    Serial.println("Failed to start PDM!");
    while (1);
  }

When calling PDM.begin the Gain is set to back default, overwriting the Gain.

int PDMClass::begin(int channels, long sampleRate)
{
  _channels = channels;

  // Enable high frequency oscillator if not already enabled
  if (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0) {
    NRF_CLOCK->TASKS_HFCLKSTART    = 1;
    while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0) { }
  }

  // configure the sample rate and channels
  switch (sampleRate) {
    case 16000:
      NRF_PDM->RATIO = ((PDM_RATIO_RATIO_Ratio80 << PDM_RATIO_RATIO_Pos) & PDM_RATIO_RATIO_Msk);
      nrf_pdm_clock_set(NRF_PDM_FREQ_1280K);
      break;
    case 41667:
      nrf_pdm_clock_set(NRF_PDM_FREQ_2667K);
      break;
    default:
      return 0; // unsupported
  }

  switch (channels) {
    case 2:
      nrf_pdm_mode_set(NRF_PDM_MODE_STEREO, NRF_PDM_EDGE_LEFTFALLING);
      break;

    case 1:
      nrf_pdm_mode_set(NRF_PDM_MODE_MONO, NRF_PDM_EDGE_LEFTFALLING);
      break;

    default:
      return 0; // unsupported
  }

  setGain(DEFAULT_PDM_GAIN);  // <== LINE 83 Resets gain

   ....

As a separate defect in the same document, it suggests the values should be 0-255, however as the implementation uses the nRF library, according to Nordic the correct range values should be :

Macros
#define NRF_PDM_GAIN_MINIMUM 0x00

#define NRF_PDM_GAIN_DEFAULT 0x28

#define NRF_PDM_GAIN_MAXIMUM 0x50

Found here: Nordic Semiconductor Infocenter

Here are three different waveforms recorded using 1000Hz tone generated by iphone app, sampled by Nano 33 BLE Sense at 16000 sample rate using PDM.h library, at differing gains (0x00, 0x50 and 0xFF)

It shows that setting the gain after begin() is called works, and also that gains 0x50 and 0xFF are not significantly different. Gain 0x00 has a much lower amplitude.

I believe this document should be reviewed and corrected to prevent others wasting time wondering why the PDM samples are not changing, when following the example code.