Use the TLV320 with in-built I2S object to stream audio data from an SD Card and send it to the TLV320 CODEC for audio playback

Dependencies:   I2SSlave mbed TLV320



File content as of revision 1:9ea0cc2fa567:

#include "mbed.h"
#include "SDHCFileSystem.h"
#include "TLV320.h"
TLV320 audio(p9, p10, 52, p5, p6, p7, p8, p29); //TLV320 object
SDFileSystem sd(p11, p12, p13, p14, "sd");      //SD Card object
InterruptIn volumeSet(p17);                     
AnalogIn aIn(p19); 
FILE *infp;                                     //File pointer object
/* Buffers */
int circularBuffer[4096];    
volatile int readPointer = 0;
volatile int theta = 0;
/* Wav file header data, for setting up the transfer protocol */
short channels;
long sampleRate;
short wordWidth;
/* Function to set volume*/
void setVolume(void){
    audio.outputVolume(aIn, aIn);                
/* Function to read from circular buffer and send data to TLV320 */
void play(void){ 
        audio.write(circularBuffer, readPointer, 8);      
        //Pointer fun :-)
        readPointer += 8;
        readPointer &= 0xfff;
        theta -= 8;
/* Function to load circular buffer from SD Card */
void fillBuffer(void){
    while(!feof(infp)){                                         //fill the circular buffer until the end of the file
        static volatile int writePointer = 0;
        if(theta < 4096){
            fread(&circularBuffer[writePointer], 4, 4, infp);   //read 4 integers into the circular buffer at a time
            //More pointer fun :D
            writePointer &= 0xfff;
/* main */
int main(){   
    infp = fopen("/sd/test.wav", "r");      //open file
        if(infp == NULL){                   //make sure it's been opened
        perror("Error opening file!");
    /* Parse wav file header */
    fseek(infp, 22, SEEK_SET);                      
    fread(&channels, 2, 1, infp);
    fseek(infp, 24, SEEK_SET);
    fread(&sampleRate, 4, 1, infp);
    fseek(infp, 34, SEEK_SET);
    fread(&wordWidth, 2, 1, infp);
    volumeSet.rise(&setVolume);             //attach set volume function to digital input
    audio.power(0x07);                      //power up TLV apart from analogue input
    audio.frequency(sampleRate);            //set sample frequency
    audio.format(wordWidth, (2-channels));  //set transfer protocol
    audio.attach(&play);                    //attach interrupt handler to send data to TLV320
    for(int j = 0; j < 4096; ++j){          //upon interrupt generation
        circularBuffer[j] = 0;              //clear circular buffer
    audio.start(TRANSMIT);                  //interrupt come from the I2STXFIFO only
    fillBuffer();                           //continually fill circular buffer