Bluetooth Enabled Keyboard/Synthesizer for mbed

Dependencies:   mbed 4DGL-uLCD-SE SDFileSystem mbed-rtos

Committer:
Jake867
Date:
Sat Apr 30 20:44:20 2016 +0000
Revision:
21:0df25c61c475
Parent:
8:f6699fd30737
Child:
23:cf9d43d5a5b4
Enabled playback for all waveform types and notes.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
jmpin 8:f6699fd30737 1 class Speaker
jmpin 8:f6699fd30737 2 {
jmpin 8:f6699fd30737 3 public:
jmpin 8:f6699fd30737 4 Speaker(PinName pin) : _pin(pin) {
jmpin 8:f6699fd30737 5 // _pin(pin) means pass pin to the Speaker Constructor
jmpin 8:f6699fd30737 6 // precompute 32 sample points on one sine wave cycle
jmpin 8:f6699fd30737 7 // used for continuous sine wave output later
jmpin 8:f6699fd30737 8
jmpin 8:f6699fd30737 9 }
jmpin 8:f6699fd30737 10 // class method to play a note based on AnalogOut class
Jake867 21:0df25c61c475 11 void PlayNote(float frequency, float duration, float volume, short unsigned Analog_out_data[32]) {
jmpin 8:f6699fd30737 12 // scale samples using current volume level arg
jmpin 8:f6699fd30737 13 for(int k=0; k<32; k++) {
jmpin 8:f6699fd30737 14 Analog_scaled_data[k] = Analog_out_data[k] * volume;
jmpin 8:f6699fd30737 15 }
jmpin 8:f6699fd30737 16 // reset to start of sample array
jmpin 8:f6699fd30737 17 i=0;
jmpin 8:f6699fd30737 18 // turn on timer interrupts to start sine wave output
jmpin 8:f6699fd30737 19 Sample_Period.attach(this, &Speaker::Sample_timer_interrupt, 1.0/(frequency*32.0));
jmpin 8:f6699fd30737 20 // play note for specified time
jmpin 8:f6699fd30737 21 wait(duration);
jmpin 8:f6699fd30737 22 // turns off timer interrupts
jmpin 8:f6699fd30737 23 Sample_Period.detach();
jmpin 8:f6699fd30737 24 // sets output to mid range - analog zero
jmpin 8:f6699fd30737 25 this->_pin.write_u16(32768);
jmpin 8:f6699fd30737 26
jmpin 8:f6699fd30737 27 }
jmpin 8:f6699fd30737 28 private:
jmpin 8:f6699fd30737 29 // sets up specified pin for analog using AnalogOut class
jmpin 8:f6699fd30737 30 AnalogOut _pin;
jmpin 8:f6699fd30737 31 // set up a timer to be used for sample rate interrupts
jmpin 8:f6699fd30737 32 Ticker Sample_Period;
jmpin 8:f6699fd30737 33
jmpin 8:f6699fd30737 34 //variables used by interrupt routine and PlayNote
jmpin 8:f6699fd30737 35 volatile int i;
jmpin 8:f6699fd30737 36 short unsigned Analog_scaled_data[32];
jmpin 8:f6699fd30737 37
jmpin 8:f6699fd30737 38 // Interrupt routine
jmpin 8:f6699fd30737 39 // used to output next analog sample whenever a timer interrupt occurs
jmpin 8:f6699fd30737 40 void Sample_timer_interrupt(void) {
jmpin 8:f6699fd30737 41 // send next analog sample out to D to A
jmpin 8:f6699fd30737 42 this->_pin.write_u16(Analog_scaled_data[i]);
jmpin 8:f6699fd30737 43 // increment pointer and wrap around back to 0 at 32
jmpin 8:f6699fd30737 44 i = (i+1) & 0x01F;
jmpin 8:f6699fd30737 45 }
jmpin 8:f6699fd30737 46 };
jmpin 8:f6699fd30737 47