by Rob Toulson and Tim Wilmshurst from textbook "Fast and Effective Embedded Systems Design: Applying the ARM mbed"

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* Program Example 11.5: 16-bit mono wave player
00002                                                              */
00003 #include "mbed.h"
00004 #include "SDFileSystem.h"
00005 #define BUFFERSIZE 4096              // number of data in circular buffer
00006 SDFileSystem sd(p5, p6, p7, p8, "sd");
00007 AnalogOut DACout(p18);
00008 Ticker SampleTicker;
00009 int SampleRate;
00010 float SamplePeriod;                       // sample period in microseconds
00011 int CircularBuffer[BUFFERSIZE];           // circular buffer array
00012 int ReadPointer=0;
00013 int WritePointer=0;
00014 bool EndOfFileFlag=0;
00015 
00016 void DACFunction(void);                   // function prototype
00017 
00018 int main() {
00019   FILE  *fp = fopen("/sd/testa.wav", "rb");     // open wave file
00020   fseek(fp, 24, SEEK_SET);                      // move to byte 24
00021   fread(&SampleRate, 4, 1, fp);                 // get sample frequency
00022   SamplePeriod=(float)1/SampleRate;   // calculate sample period as float
00023   SampleTicker.attach(&DACFunction,SamplePeriod);   // start output tick
00024 
00025   while (!feof(fp)) {          // loop until end of file is encountered 
00026     fread(&CircularBuffer[WritePointer], 2, 1, fp);
00027     WritePointer=WritePointer+1;        // increment Write Pointer
00028     if (WritePointer>=BUFFERSIZE) {     // if end of circular buffer
00029         WritePointer=0;                 // go back to start of buffer   
00030     }
00031   }
00032   EndOfFileFlag=1;
00033   fclose(fp);
00034 }
00035 
00036 // DAC function called at rate SamplePeriod
00037 void DACFunction(void) {
00038   if ((EndOfFileFlag==0)|(ReadPointer>0)) { // output while data available
00039     DACout.write_u16(CircularBuffer[ReadPointer]);   // output to DAC
00040     ReadPointer=ReadPointer+1;                       // increment pointer
00041     if (ReadPointer>=BUFFERSIZE) {
00042       ReadPointer=0;                      // reset pointer if necessary
00043     }
00044   }
00045 }
00046