How do I print microphone input to the serial port of arduino nano 33 ble sense?
Good day,
I have an arduino nano 33 ble sense with a microphone on it. Using the PDM.h library I extract the audio into a sample buffer 512 bytes at a time. I use a type of ping pong buffer to save data while I print to the serial port but it keeps crashing, what did I do wrong?
#include <PDM.h>
#include <stdlib.h>
// buffer to read samples into, each sample is 16-bits
char sampleBuffer[512];
//ping pong buffer
//total bytes is how many bytes the microphone recorded
//write offset switches between first or second half of the ping pong buffer
//read offset switches between first or second half of the ping pong buffer
//ready to print indicates that the data is ready to print
char audio[66000];
long int totalBytes = 0;
int writeOffset = 0;
int readOffset = 0;
int half = 32768;
bool readyToPrint = false;
void setup() {
//the sample rate is 16Khz with a 16-bit depth that means 32KBytes/s are needed to fully transfer this signal
//the baud rate represents the bit rate of the signal, 32*8 is 256Kbits/s, closest compatible baud rate of the nano is 500kbaud
Serial.begin(500000);
while (!Serial);
// configure the data receive callback
PDM.onReceive(onPDMdata);
// 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);
}
}
void loop() {
}
void printToSerial(){
Serial.write(audio + readOffset, half);
readOffset = readOffset ^ half;
}
void onPDMdata() {
// query the number of bytes available
int bytesAvailable = PDM.available();
// read into the sample buffer
PDM.read(sampleBuffer, bytesAvailable);
if(totalBytes < half){
memcpy(audio + writeOffset + totalBytes, sampleBuffer, bytesAvailable);
totalBytes += bytesAvailable;
}
else{
totalBytes = 0;
writeOffset = writeOffset ^ half;
printToSerial();
}
}
Comments
Post a Comment