ECE 2036 Project

Dependencies:   mbed wave_player 4DGL-uLCD-SE

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers <title>Speaker.h Source File</title>

Speaker.h

00001 class Speaker
00002 {
00003 public:
00004     Speaker(PinName pin) : _pin(pin) {
00005 // _pin(pin) means pass pin to the Speaker Constructor
00006 // precompute 32 sample points on one sine wave cycle
00007 // used for continuous sine wave output later
00008         for(int k=0; k<32; k++) {
00009             Analog_out_data[k] = int (65536.0 * ((1.0 + sin((float(k)/32.0*6.28318530717959)))/2.0));
00010             // scale the sine wave to 16-bits - as needed for AnalogOut write_u16 arg
00011         }
00012 
00013     }
00014 // class method to play a note based on AnalogOut class
00015     void PlayNote(float frequency, float duration, float volume) {
00016         // scale samples using current volume level arg
00017         for(int k=0; k<32; k++) {
00018             Analog_scaled_data[k] = Analog_out_data[k] * volume;
00019         }
00020         // reset to start of sample array
00021         i=0;
00022         // turn on timer interrupts to start sine wave output
00023         Sample_Period.attach(this, &Speaker::Sample_timer_interrupt, 1.0/(frequency*32.0));
00024         // play note for specified time
00025         wait(duration);
00026         // turns off timer interrupts
00027         Sample_Period.detach();
00028         // sets output to mid range - analog zero
00029         this->_pin.write_u16(32768);
00030 
00031     }
00032 private:
00033 // sets up specified pin for analog using AnalogOut class
00034     AnalogOut _pin;
00035     // set up a timer to be used for sample rate interrupts
00036     Ticker Sample_Period;
00037 
00038     //variables used by interrupt routine and PlayNote
00039     volatile int i;
00040     short unsigned Analog_out_data[32];
00041     short unsigned Analog_scaled_data[32];
00042 
00043 // Interrupt routine
00044 // used to output next analog sample whenever a timer interrupt occurs
00045     void Sample_timer_interrupt(void) {
00046         // send next analog sample out to D to A
00047         this->_pin.write_u16(Analog_scaled_data[i]);
00048         // increment pointer and wrap around back to 0 at 32
00049         i = (i+1) & 0x01F;
00050     }
00051 };
00052