|
4 | 4 | Arduino IDE can be used to plot the audio data (Tools -> Serial Plotter)
|
5 | 5 |
|
6 | 6 | Circuit:
|
7 |
| - - Arduino Nano 33 BLE board |
| 7 | + - Arduino Nano 33 BLE board or |
| 8 | + - Arduino Portenta H7 board plus Portenta Vision Shield |
8 | 9 |
|
9 | 10 | This example code is in the public domain.
|
10 | 11 | */
|
11 | 12 |
|
12 | 13 | #include <PDM.h>
|
13 | 14 |
|
14 |
| -// buffer to read samples into, each sample is 16-bits |
| 15 | +// Buffer to read samples into, each sample is 16-bits |
15 | 16 | short sampleBuffer[256];
|
16 | 17 |
|
17 |
| -// number of samples read |
| 18 | +// Number of audio samples read |
18 | 19 | volatile int samplesRead;
|
19 | 20 |
|
20 | 21 | void setup() {
|
21 | 22 | Serial.begin(9600);
|
22 | 23 | while (!Serial);
|
23 | 24 |
|
24 |
| - // configure the data receive callback |
| 25 | + // Configure the data receive callback |
25 | 26 | PDM.onReceive(onPDMdata);
|
26 | 27 |
|
27 |
| - // optionally set the gain, defaults to 20 |
| 28 | + // Optionally set the gain |
| 29 | + // Defaults to 20 on the BLE Sense and -10 on the Portenta Vision Shield |
28 | 30 | // PDM.setGain(30);
|
29 | 31 |
|
30 |
| - // initialize PDM with: |
| 32 | + // Initialize PDM with: |
31 | 33 | // - one channel (mono mode)
|
32 |
| - // - a 16 kHz sample rate |
| 34 | + // - a 16 kHz sample rate for the Arduino Nano 33 BLE Sense |
| 35 | + // - a 32 kHz or 64 kHz sample rate for the Arduino Portenta Vision Shield |
33 | 36 | if (!PDM.begin(1, 16000)) {
|
34 | 37 | Serial.println("Failed to start PDM!");
|
35 | 38 | while (1);
|
36 | 39 | }
|
37 | 40 | }
|
38 | 41 |
|
39 | 42 | void loop() {
|
40 |
| - // wait for samples to be read |
| 43 | + // Wait for samples to be read |
41 | 44 | if (samplesRead) {
|
42 | 45 |
|
43 |
| - // print samples to the serial monitor or plotter |
| 46 | + // Print samples to the serial monitor or plotter |
44 | 47 | for (int i = 0; i < samplesRead; i++) {
|
45 | 48 | Serial.println(sampleBuffer[i]);
|
46 | 49 | }
|
47 | 50 |
|
48 |
| - // clear the read count |
| 51 | + // Clear the read count |
49 | 52 | samplesRead = 0;
|
50 | 53 | }
|
51 | 54 | }
|
52 | 55 |
|
| 56 | +/** |
| 57 | + * Callback function to process the data from the PDM microphone. |
| 58 | + * NOTE: This callback is executed as part of an ISR. |
| 59 | + * Therefore using `Serial` to print messages inside this function isn't supported. |
| 60 | + * */ |
53 | 61 | void onPDMdata() {
|
54 |
| - // query the number of bytes available |
| 62 | + // Query the number of available bytes |
55 | 63 | int bytesAvailable = PDM.available();
|
56 | 64 |
|
57 |
| - // read into the sample buffer |
| 65 | + // Read into the sample buffer |
58 | 66 | PDM.read(sampleBuffer, bytesAvailable);
|
59 | 67 |
|
60 | 68 | // 16-bit, 2 bytes per sample
|
|
0 commit comments