#include <SPI.h>
#include <SD.h> // SD card library
#include "TMRpcm.h" // For reading WAV audio files
#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char* sbrk(int incr);
#else // __ARM__
extern char *__brkval;
#endif // __arm__
#define audioIn A0 // audio input port
#define CS_PIN 53 // sd card setup
#define WINDOW_SIZE 160
const double samplingFrequency = 4000; //Hz, must be less than 10000 due to ADC
const double refreshRate = 20; //Hz
unsigned int sampling_period_us;
unsigned long usampling_microseconds;
int16_t vReal[WINDOW_SIZE];
File root;
TMRpcm audio;
/*
These values can be changed in order to evaluate the functions
*/
#define CHANNEL A0
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
sampling_period_us = round(1000000*(1.0/samplingFrequency)); // change based on our design
Serial.print("Initializing SD card...");
if (!SD.begin(CS_PIN)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
printfreeMem(0);
delay(2000); // wait for initializing
analogReference(DEFAULT);
audio.speakerPin = 0; // set speaker output to pin 0 -> used to read .wav file
audio.setVolume(5); // 0 to 7. Set volume level
audio.quality(0); // Set 1 for 2x oversampling Set 0 for normal
Serial.println("done!");
}
void loop(void) {
if ( !audio.isPlaying() ) {
File entry = SD.open("PinkPanther30.wav");
audio.play( entry.name() ); // play the audio file
Serial.print("Playing file: ");
Serial.println( entry.name() );
}
/*SAMPLING*/
usampling_microseconds = micros();
for(int i=0; i< WINDOW_SIZE; i++) // check for /2
{
vReal[i] = analogRead(audioIn); // reading from A0
while(micros() - usampling_microseconds < sampling_period_us){
//empty loop
}
usampling_microseconds += sampling_period_us;
}
printfreeMem(3);
byte buffer[2 * WINDOW_SIZE];
for (int i = 0; i < WINDOW_SIZE; i++) {
int16_t sample = vReal[i];
buffer[2 * i] = lowByte(sample);
buffer[2 * i + 1] = highByte(sample);
}
Serial.write(buffer, 2 * WINDOW_SIZE);
while(1);
}
//MEMORY LIMITATIONS???
//https://forum.arduino.cc/t/arduino-uno-ssd1306-allocation-failed-need-help-downsizing/604698/5
//https://cdn-learn.adafruit.com/downloads/pdf/memories-of-an-arduino.pdf
//https://www.instructables.com/Playing-Wave-file-using-arduino/
//https://simple-circuit.com/arduino-wave-audio-player-sd-card/
void printfreeMem(int index) {
Serial.print("Freemem ");
Serial.print(index);
Serial.print(": ");
Serial.println(freeMemory());
}
int freeMemory() {
char top;
#ifdef __arm__
return &top - reinterpret_cast<char*>(sbrk(0));
#elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151)
return &top - __brkval;
#else // __arm__
return __brkval ? &top - __brkval : &top - __malloc_heap_start;
#endif // __arm__
}