Skip to content

Commit 3379272

Browse files
committed
PDM: RP2040: calculate the correct decimation factor
Fixes #289
1 parent 176e405 commit 3379272

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

libraries/PDM/src/rp2040/PDM.cpp

+18-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "Arduino.h"
44
#include "PDM.h"
55
#include "OpenPDMFilter.h"
6+
#include "mbed_interface.h"
67

78
extern "C" {
89
#include "hardware/pio.h"
@@ -67,6 +68,18 @@ int PDMClass::begin(int channels, int sampleRate)
6768
int finalBufferLength = _doubleBuffer.availableForWrite() / sizeof(int16_t);
6869
_doubleBuffer.swap(0);
6970

71+
// The mic accepts an input clock from 1.2 to 3.25 Mhz
72+
// Setup the decimation factor accordingly
73+
if ((sampleRate * decimation * 2) > 3250000) {
74+
decimation = 64;
75+
}
76+
77+
// Sanity check, abort if still over 3.25Mhz
78+
if ((sampleRate * decimation * 2) > 3250000) {
79+
mbed_error_printf("Sample rate too high, the mic would glitch\n");
80+
mbed_die();
81+
}
82+
7083
int rawBufferLength = RAW_BUFFER_SIZE / (decimation / 8);
7184
// Saturate number of samples. Remaining bytes are dropped.
7285
if (rawBufferLength > finalBufferLength) {
@@ -179,7 +192,11 @@ void PDMClass::IrqHandler(bool halftranfer)
179192
}
180193

181194
// fill final buffer with PCM samples
182-
Open_PDM_Filter_128(rawBuffer[rawBufferIndex], finalBuffer, 1, &filter);
195+
if (filter.Decimation == 128) {
196+
Open_PDM_Filter_128(rawBuffer[rawBufferIndex], finalBuffer, 1, &filter);
197+
} else {
198+
Open_PDM_Filter_64(rawBuffer[rawBufferIndex], finalBuffer, 1, &filter);
199+
}
183200

184201
if (cutSamples) {
185202
memset(finalBuffer, 0, cutSamples);

0 commit comments

Comments
 (0)